context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using UnityEngine;
using System.Collections;
using System;
[Serializable]
public class PathNode
{
//If false then there exists a wall
public bool Up = true, Left=true, Down = true, Right = true;
public int TextVal = 4;
public PathNode(int NodeType)
{
switch(NodeType)
{
case 33:
{
this.Left = false;
TextVal = 33;
break;
}
case 34:
{
this.Down = false;
TextVal = 34;
break;
}
case 31:
{
this.Right = false;
TextVal = 31;
break;
}
case 32:
{
this.Up = false;
TextVal = 32;
break;
}
case 22:
{
this.Up = false;
this.Down = false;
TextVal = 22;
break;
}
case 21:
{
this.Left = false;
this.Right = false;
TextVal = 21;
break;
}
case 13:
{
this.Up = false;
this.Down = false;
this.Left = false;
TextVal = 13;
break;
}
case 14:
{
this.Left = false;
this.Down = false;
this.Right = false;
TextVal = 14;
break;
}
case 11:
{
this.Up = false;
this.Down = false;
this.Right = false;
TextVal = 11;
break;
}
case 12:
{
this.Up = false;
this.Left = false;
this.Right = false;
TextVal = 12;
break;
}
case 5:
{
this.Up = false;
this.Down = false;
this.Right = false;
this.Left = false;
TextVal = 5;
break;
}
case 534:
{
this.Left = false;
this.Down = false;
TextVal = 534;
break;
}
case 514:
{
this.Down = false;
this.Right = false;
TextVal = 514;
break;
}
case 512:
{
this.Up = false;
this.Right = false;
TextVal = 512;
break;
}
case 523:
{
this.Up = false;
this.Left = false;
TextVal = 523;
break;
}
case 4:
{
break;
}
}
}
public int PathType()
{
TextVal = CalcPathType(AssignWalls(this.Right,this.Up,this.Left,this.Down));
return TextVal;
}
public int CalcPathType(int Walls)
{
switch(Walls)
{
case 1111:
{
return 4;
}
case 1110:
{
return 34;
}
case 1100:
{
return 534;
}
case 1000:
{
return 13;
}
case 0000:
{
return 5;
}
case 1101:
{
return 33;
}
case 1001:
{
return 523;
}
case 1011:
{
return 32;
}
case 0011:
{
return 512;
}
case 0111:
{
return 31;
}
case 0101:
{
return 21;
}
case 1010:
{
return 22;
}
case 0110:
{
return 514;
}
case 0010:
{
return 11;
}
case 0100:
{
return 14;
}
case 0001:
{
return 12;
}
default:
{
throw new System.InvalidOperationException("Invalid Wall Setup");
}
}
}
public int AssignWalls(bool Right, bool Up, bool Left, bool Down)
{
int Walls;
if(Right == true)
{
Walls = 1;
}
else
{
Walls = 0;
}
Walls *= 10;
if(Up == true)
{
Walls += 1;
}
Walls *= 10;
if(Left == true)
{
Walls += 1;
}
Walls *= 10;
if(Down == true)
{
Walls +=1;
}
return Walls;
}
};
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using InterFAX.Api.Dtos;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace InterFAX.Api
{
public partial class Documents
{
private readonly FaxClient _interfax;
private const string ResourceUri = "/outbound/documents";
public const int MaxChunkSize = 256 * 1024; //quarter of a MB
internal Documents(FaxClient interfax)
{
_interfax = interfax;
}
private Dictionary<string, string> _supportedMediaTypes;
public Dictionary<string, string> SupportedMediaTypes
{
get
{
if (_supportedMediaTypes == null)
{
var assembly = Assembly.GetAssembly(typeof(Documents));
var assemblyPath = Path.GetDirectoryName(assembly.Location);
var typesFile = Path.Combine(assemblyPath, "SupportedMediaTypes.json");
if (!File.Exists(typesFile))
{
// unpack the types file to the assembly path
using (var resource = assembly.GetManifestResourceStream("InterFAX.Api.SupportedMediaTypes.json"))
{
using (var file = new FileStream(typesFile, FileMode.Create, FileAccess.Write))
{
resource.CopyTo(file);
}
}
}
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
var mappings = JsonConvert.DeserializeObject<List<MediaTypeMapping>>(File.ReadAllText(typesFile));
_supportedMediaTypes = mappings.ToDictionary(
mapping => mapping.FileType,
mapping => mapping.MediaType);
}
return _supportedMediaTypes;
}
}
/// <summary>
/// Build an IFaxDocument from a Uri.
/// </summary>
public IFaxDocument BuildFaxDocument(Uri fileUri)
{
return new UriDocument(fileUri);
}
/// <summary>
/// Build and IFaxDocument from a file byte array
/// </summary>
/// <param name="file">byte array contents of the file</param>
/// <param name="extension">file encoding specified as a file extension (eg ".pdf")</param>
/// <returns></returns>
public IFaxDocument BuildFaxDocument(byte[] file, string extension)
{
var ext = extension.Trim('.').ToLower();
var mediaType = SupportedMediaTypes.Keys.Contains(ext)
? SupportedMediaTypes[ext]
: "application/octet-stream";
return new FileDocumentArray(file, mediaType);
}
/// <summary>
/// Build an IFaxDocument from a local file.
/// </summary>
public IFaxDocument BuildFaxDocument(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException(filePath);
var extension = Path.GetExtension(filePath) ?? "*";
extension = extension.TrimStart('.').ToLower();
var mediaType = SupportedMediaTypes.Keys.Contains(extension)
? SupportedMediaTypes[extension]
: "application/octet-stream";
return new FileDocument(filePath, mediaType);
}
/// <summary>
/// Build an IFaxDocument from a FileStream.
/// </summary>
public IFaxDocument BuildFaxDocument(string fileName, FileStream fileStream)
{
var extension = Path.GetExtension(fileName) ?? "*";
extension = extension.TrimStart('.').ToLower();;
var mediaType = SupportedMediaTypes.Keys.Contains(extension)
? SupportedMediaTypes[extension]
: "application/octet-stream";
return new FileStreamDocument(fileName, fileStream, mediaType);
}
/// <summary>
/// Get a list of previous document upload sessions which are currently available.
/// </summary>
/// <param name="listOptions"></param>
public async Task<IEnumerable<UploadSession>> GetUploadSessions(ListOptions listOptions = null)
{
return await _interfax.HttpClient.GetResourceAsync<IEnumerable<UploadSession>>(ResourceUri, listOptions);
}
/// <summary>
/// Create a document upload session.
/// </summary>
/// <param name="options"></param>
/// <returns>The id of the created session.</returns>
public async Task<string> CreateUploadSession(UploadSessionOptions options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
var response = await _interfax.HttpClient.PostAsync(ResourceUri, options);
return response.Headers.Location.Segments.Last();
}
/// <summary>
/// Get a single upload session object.
/// </summary>
/// <param name="sessionId"></param>
public async Task<UploadSession> GetUploadSession(string sessionId)
{
return await _interfax.HttpClient.GetResourceAsync<UploadSession>($"{ResourceUri}/{sessionId}");
}
/// <summary>
/// Uploads a chunk of data to the given document upload session.
/// </summary>
/// <param name="sessionId">The id of an alread existing upload session.</param>
/// <param name="offset">The starting position of <paramref name="data"/> in the document.</param>
/// <param name="data">The data to upload.s</param>
/// <returns>An HttpResponseMessage</returns>
public async Task<HttpResponseMessage> UploadDocumentChunk(string sessionId, long offset, byte[] data)
{
if (data.Length > MaxChunkSize)
throw new ArgumentOutOfRangeException(nameof(data), $"Cannot upload more than {MaxChunkSize} bytes at once.");
var content = new ByteArrayContent(data);
var range = new RangeHeaderValue(offset, offset + data.Length - 1);
return await _interfax.HttpClient.PostRangeAsync($"{ResourceUri}/{sessionId}", content, range);
}
/// Uploads a FileStream to the given document upload session.
/// </summary>
/// <param name="sessionId">The id of an already existing upload session.</param>
/// <param name="fileStream">The FileStream to upload.</param>
public void UploadFileStreamToSession(string sessionId, FileStream fileStream)
{
var buffer = new byte[MaxChunkSize];
int len;
while ((len = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
var data = new byte[len];
Array.Copy(buffer, data, len);
var response = UploadDocumentChunk(sessionId, fileStream.Position - len, data).Result;
if (response.StatusCode == HttpStatusCode.Accepted) continue;
if (response.StatusCode == HttpStatusCode.NoContent) continue;
if (response.StatusCode == HttpStatusCode.OK) break;
throw new ApiException(response.StatusCode, new Error
{
Code = (int) response.StatusCode,
Message = response.ReasonPhrase,
MoreInfo = response.Content.ReadAsStringAsync().Result
});
}
}
/// <summary>
/// Upload a document stream to be attached to a fax.
/// </summary>
/// <param name="fileName">The name of the file to be uploaded.</param>
/// <param name="fileStream">The FileStream to be uploaded.</param>
/// <returns>The upload session created.</returns>
public UploadSession UploadDocument(string fileName, FileStream fileStream)
{
var sessionId = CreateUploadSession(new UploadSessionOptions
{
Name = fileName,
Size = fileStream.Length
}).Result;
UploadFileStreamToSession(sessionId, fileStream);
return GetUploadSession(sessionId).Result;
}
/// <summary>
/// Upload a document to be attached to a fax.
/// </summary>
/// <param name="filePath">The full path of the file to be uploaded.</param>
/// <returns>The upload session created.</returns>
public UploadSession UploadDocument(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"Could not find file : {filePath}", filePath);
var fileInfo = new FileInfo(filePath);
var sessionId = CreateUploadSession(new UploadSessionOptions
{
Name = fileInfo.Name,
Size = (int) fileInfo.Length
}).Result;
using (var fileStream = File.OpenRead(filePath))
{
UploadFileStreamToSession(sessionId, fileStream);
}
return GetUploadSession(sessionId).Result;
}
/// <summary>
/// Cancel a document upload session.
/// </summary>
/// <param name="sessionId">The identifier of the session to cancel.</param>
/// <returns>The server response content.</returns>
public async Task<string> CancelUploadSession(string sessionId)
{
return await _interfax.HttpClient.DeleteResourceAsync($"{ResourceUri}/{sessionId}");
}
}
}
| |
// Copyright (c) 2011 Bob Berkebile
// Please direct any bugs/comments/suggestions to http://www.pixelplacement.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 UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System;
public class StressBall : EditorWindow
{
static float prevTime;
static float deltaTime;
static Texture2D ball;
static Texture2D heldBall;
static Texture2D ballVisual;
static Texture2D shadow;
static Texture2D background;
static Texture2D particleVisual;
static Vector2 velocityScale = new Vector2(.09f,.09f);
static float gravity = .012f;
static float friction = .6f;
static float restitution = .71f;
static Rect ballPosition;
static bool dragging;
static Vector2 ballVelocity;
static Rect bounds = new Rect(0,0,100,100);
static bool initialized;
static bool render=true;
static List<StressBall.StressBallParticle> aliveParticles = new List<StressBall.StressBallParticle>();
static List<int> deadParticles = new List<int>();
static double skinResetLength = .03;
static double skinResetTime;
[MenuItem("Pixelplacement/StressBall")]
static void Init(){
GetWindow(typeof(StressBall), false, "StressBall");
}
static void PlayModeChanged(){
if(EditorApplication.isPlaying || EditorApplication.isPlayingOrWillChangePlaymode){
render=false;
}else{
render=true;
}
}
void OnEnable(){
if(!initialized && render){
EditorApplication.playmodeStateChanged+=PlayModeChanged;
initialized=true;
ball = (Texture2D)Resources.Load("stressBall_ball");
heldBall = (Texture2D)Resources.Load("stressBall_ball_held");
shadow = (Texture2D)Resources.Load("stressBall_shadow");
background = (Texture2D)Resources.Load("stressBall_background");
particleVisual = (Texture2D)Resources.Load("stressBall_particle");
prevTime = (float)EditorApplication.timeSinceStartup;
ballPosition = new Rect(0,0,ball.width,ball.height);
ballVelocity = new Vector2(2,2);
ballVisual = ball;
}
}
void OnGUI(){
//properties:
bounds = position;
CalculateDeltaTime();
Event e = Event.current;
//dragging:
if (e.isMouse) {
//check for drag:
if(e.type == EventType.mouseDown && ballPosition.Contains(e.mousePosition)){
dragging = true;
ballVisual = heldBall;
}
if(e.type == EventType.mouseUp && dragging || e.mousePosition.x < 0 || e.mousePosition.x > bounds.width || e.mousePosition.y < 0 || e.mousePosition.y > bounds.height){
dragging = false;
ballVisual = ball;
}
//apply drag:
if(dragging){
ballPosition.x = ballPosition.x + e.delta.x;
ballPosition.y = ballPosition.y + e.delta.y;
}
//constrain drag:
if(ballPosition.x < 0){
ballPosition.x = 0;
}
if(ballPosition.x > bounds.width - ballPosition.width){
ballPosition.x = bounds.width - ballPosition.width;
}
if(ballPosition.y < 0){
ballPosition.y = 0;
}
if(ballPosition.y > bounds.height - ballPosition.height){
ballPosition.y = bounds.height - ballPosition.height;
}
//set ball's dragged velocity
if(dragging){
ballVelocity = Vector2.Scale(e.delta, velocityScale);
}
}
//physics:
if(!dragging){
ballVelocity.y += gravity;
ballPosition.x += ballVelocity.x * deltaTime;
ballPosition.y += ballVelocity.y * deltaTime;
//floor bounce:
if(ballPosition.y + ball.height > bounds.height){
ballPosition.y = bounds.height - ball.height;
ballVelocity.x *= friction;
ballVelocity.y *= -restitution;
if(Mathf.Abs(ballVelocity.y) > .8){
ParticleBurst(0,new Vector2(ballPosition.x+(ballVisual.width/2),ballPosition.y+ballVisual.height-3));
}
}
//right wall bounce:
if(ballPosition.x + ball.width > bounds.width){
ballPosition.x = bounds.width - ball.width;
ballVelocity.x *= -restitution;
if(Mathf.Abs(ballVelocity.x) > .8){
ParticleBurst(-1,new Vector2(ballPosition.x+ballVisual.width,ballPosition.y+(ballVisual.height/2)));
}
}
//left wall bounce:
if(ballPosition.x < 0){
ballPosition.x = 0;
ballVelocity.x *= -restitution;
if(Mathf.Abs(ballVelocity.x) > .8){
ParticleBurst(1,new Vector2(ballPosition.x,ballPosition.y));
}
}
}
//don't incur draw calls while the editor is rendering to avoiding affecting game performance:
if (render) {
//draw visuals:
//reset ball's visuals after a delay if an impact changed it:
if(EditorApplication.timeSinceStartup - skinResetTime > skinResetLength){
ballVisual = ball;
}
//animate all living particles:
if(aliveParticles.Count > 0){
foreach (StressBallParticle particle in aliveParticles) {
particle.Animate();
}
}
//burn all the dead particles and empty the dead particle roster:
if(aliveParticles.Count > 0){
foreach (int id in deadParticles) {
//buggy solution for ensuring removal doesn't error:
if(id < aliveParticles.Count){
aliveParticles.RemoveAt(id);
}
}
deadParticles = new List<int>();
}
//only draw the shadow and background art if we are below a resonable threshold (save cycles for "work" not "play" ;)
if(bounds.width <550 && bounds.height<550){
GUI.DrawTexture(new Rect(0,0,bounds.width,bounds.height),background);
GUI.DrawTexture(new Rect(ballPosition.x+8,ballPosition.y+11,ballPosition.width,ballPosition.height),shadow);
}
//only paint the ball if it's within view:
if(ballPosition.y>-ballPosition.height){
GUI.DrawTexture(ballPosition,ballVisual);
}
}
Repaint();
}
void CalculateDeltaTime(){
float now = (float)EditorApplication.timeSinceStartup;
deltaTime = (now - prevTime)*800;
prevTime = now;
}
void ParticleBurst(int direction, Vector2 position){
if(ballPosition.y>-ballPosition.height){
ballVisual = heldBall;
skinResetTime = EditorApplication.timeSinceStartup;
int numberOfParticles = UnityEngine.Random.Range(5,15);
int newDirection;
for (int i = 0; i < numberOfParticles; i++) {
//if floor particles are needed generate random direction:
if(direction==0){
int seed = UnityEngine.Random.Range(0,2);
if(seed==0){
newDirection=-1;
}else{
newDirection=1;
}
}else{
newDirection=direction;
}
aliveParticles.Add(new StressBallParticle(newDirection,position));
}
}
}
class StressBallParticle{
Vector2 position;
Vector2 velocity;
Vector2 damping = new Vector2(.999f,.999f);
float decay;
float bounce = -.6f;
float gravity = .0095f;
float alpha = 1.2f;
int direction;
public StressBallParticle(int direction, Vector2 position){
decay = UnityEngine.Random.Range(.0015f,.005f);
this.position=position;
velocity=new Vector2(UnityEngine.Random.Range(.05f,.6f)*direction,UnityEngine.Random.Range(-.8f,-1.4f));
}
public void Animate(){
//apply alpha fade:
GUI.color = new Color(1,1,1, alpha);
//calculate and apply "physics":
velocity = Vector2.Scale(velocity, damping);
velocity.y+=gravity;
position+=velocity;
//bounce off floor:
if(position.y>StressBall.bounds.height-particleVisual.height){
position.y=StressBall.bounds.height-particleVisual.height;
velocity.y*=bounce;
}
//draw particle:
GUI.DrawTexture(new Rect(position.x,position.y,particleVisual.width,particleVisual.height), particleVisual);
alpha -= decay;
if (alpha<=0) {
//get the id of this particle in the living particle list and inject it in the dead particle list:
StressBall.deadParticles.Add(StressBall.aliveParticles.IndexOf(this));
}
GUI.color = Color.white;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Internal.DeveloperExperience;
using Internal.Runtime.Augments;
namespace System
{
internal class PreallocatedOutOfMemoryException
{
public static OutOfMemoryException Instance { get; private set; }
// Eagerly preallocate instance of out of memory exception to avoid infinite recursion once we run out of memory
internal static void Initialize()
{
Instance = new OutOfMemoryException(message: null); // Cannot call the nullary constructor as that triggers non-trivial resource manager logic.
}
}
public class RuntimeExceptionHelpers
{
//------------------------------------------------------------------------------------------------------------
// @TODO: this function is related to throwing exceptions out of Rtm. If we did not have to throw
// out of Rtm, then we would note have to have the code below to get a classlib exception object given
// an exception id, or the special functions to back up the MDIL THROW_* instructions, or the allocation
// failure helper. If we could move to a world where we never throw out of Rtm, perhaps by moving parts
// of Rtm that do need to throw out to Bartok- or Binder-generated functions, then we could remove all of this.
//------------------------------------------------------------------------------------------------------------
// This is the classlib-provided "get exception" function that will be invoked whenever the runtime
// needs to throw an exception back to a method in a non-runtime module. The classlib is expected
// to convert every code in the ExceptionIDs enum to an exception object.
[RuntimeExport("GetRuntimeException")]
public static Exception GetRuntimeException(ExceptionIDs id)
{
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
// @TODO: this function should return pre-allocated exception objects, either frozen in the image
// or preallocated during DllMain(). In particular, this function will be called when out of memory,
// and failure to create an exception will result in infinite recursion and therefore a stack overflow.
switch (id)
{
case ExceptionIDs.OutOfMemory:
return PreallocatedOutOfMemoryException.Instance;
case ExceptionIDs.Arithmetic:
return new ArithmeticException();
case ExceptionIDs.ArrayTypeMismatch:
return new ArrayTypeMismatchException();
case ExceptionIDs.DivideByZero:
return new DivideByZeroException();
case ExceptionIDs.IndexOutOfRange:
return new IndexOutOfRangeException();
case ExceptionIDs.InvalidCast:
return new InvalidCastException();
case ExceptionIDs.Overflow:
return new OverflowException();
case ExceptionIDs.NullReference:
return new NullReferenceException();
case ExceptionIDs.AccessViolation:
FailFast("Access Violation: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The application will be terminated since this platform does not support throwing an AccessViolationException.");
return null;
case ExceptionIDs.DataMisaligned:
return new DataMisalignedException();
default:
FailFast("The runtime requires an exception for a case that this class library does not understand.");
return null;
}
}
catch
{
return null; // returning null will cause the runtime to FailFast via the class library.
}
}
public enum RhFailFastReason
{
Unknown = 0,
InternalError = 1, // "Runtime internal error"
UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope."
UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method."
ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object."
IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code."
PN_UnhandledException = 6, // ProjectN: "Unhandled exception: a managed exception was not handled before reaching unmanaged code"
PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition."
Max
}
private static string GetStringForFailFastReason(RhFailFastReason reason)
{
switch (reason)
{
case RhFailFastReason.InternalError:
return "Runtime internal error";
case RhFailFastReason.UnhandledException_ExceptionDispatchNotAllowed:
return "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope.";
case RhFailFastReason.UnhandledException_CallerDidNotHandle:
return "Unhandled exception: no handler found in calling method.";
case RhFailFastReason.ClassLibDidNotTranslateExceptionID:
return "Unable to translate failure into a classlib-specific exception object.";
case RhFailFastReason.IllegalNativeCallableEntry:
return "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code.";
case RhFailFastReason.PN_UnhandledException:
return "Unhandled exception: a managed exception was not handled before reaching unmanaged code.";
case RhFailFastReason.PN_UnhandledExceptionFromPInvoke:
return "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition.";
default:
return "Unknown reason.";
}
}
public static void FailFast(String message)
{
FailFast(message, null, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero);
}
public static unsafe void FailFast(string message, Exception exception)
{
FailFast(message, exception, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero);
}
// Used to report exceptions that *logically* go unhandled in the Fx code. For example, an
// exception that escapes from a ThreadPool workitem, or from a void-returning async method.
public static void ReportUnhandledException(Exception exception)
{
// ReportUnhandledError will also call this in APPX scenarios,
// but WinRT can failfast before we get another chance
// (in APPX scenarios, this one will get overwritten by the one with the CCW pointer)
GenerateExceptionInformationForDump(exception, IntPtr.Zero);
#if ENABLE_WINRT
// If possible report the exception to GEH, if not fail fast.
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks == null || !callbacks.ReportUnhandledError(exception))
FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception);
#else
FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception);
#endif
}
// This is the classlib-provided fail-fast function that will be invoked whenever the runtime
// needs to cause the process to exit. It is the classlib's opprotunity to customize the
// termination behavior in whatever way necessary.
[RuntimeExport("FailFast")]
public static void RuntimeFailFast(RhFailFastReason reason, Exception exception, IntPtr pExAddress, IntPtr pExContext)
{
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
if (!SafeToPerformRichExceptionSupport)
return;
// Avoid complex processing and allocations if we are already in failfast or out of memory.
// We do not set InFailFast.Value here, because we want rich diagnostics in the FailFast
// call below and reentrancy is not possible for this method (all exceptions are ignored).
bool minimalFailFast = InFailFast.Value || (exception is OutOfMemoryException);
string failFastMessage = "";
if (!minimalFailFast)
{
if ((reason == RhFailFastReason.PN_UnhandledException) && (exception != null))
{
Debug.WriteLine("Unhandled Exception: " + exception.ToString());
}
failFastMessage = String.Format("Runtime-generated FailFast: ({0}): {1}{2}",
reason.ToString(), // Explicit call to ToString() to avoid MissingMetadataException inside String.Format()
GetStringForFailFastReason(reason),
exception != null ? " [exception object available]" : "");
}
FailFast(failFastMessage, exception, reason, pExAddress, pExContext);
}
catch
{
// Returning from this callback will cause the runtime to FailFast without involving the class
// library.
}
}
internal static void FailFast(string message, Exception exception, RhFailFastReason reason, IntPtr pExAddress, IntPtr pExContext)
{
// If this a recursive call to FailFast, avoid all unnecessary and complex actitivy the second time around to avoid the recursion
// that got us here the first time (Some judgement is required as to what activity is "unnecessary and complex".)
bool minimalFailFast = InFailFast.Value || (exception is OutOfMemoryException);
InFailFast.Value = true;
if (!minimalFailFast)
{
String output = (exception != null) ?
"Unhandled Exception: " + exception.ToString()
: message;
DeveloperExperience.Default.WriteLine(output);
GenerateExceptionInformationForDump(exception, IntPtr.Zero);
}
uint errorCode = 0x80004005; // E_FAIL
// To help enable testing to bucket the failures we choose one of the following as errorCode:
// * hashcode of EETypePtr if it is an unhandled managed exception
// * HRESULT, if available
// * RhFailFastReason, if it is one of the known reasons
if (exception != null)
{
if (reason == RhFailFastReason.PN_UnhandledException)
errorCode = (uint)(exception.EETypePtr.GetHashCode());
else if (exception.HResult != 0)
errorCode = (uint)exception.HResult;
}
else if (reason != RhFailFastReason.Unknown)
{
errorCode = (uint)reason + 0x1000; // Add something to avoid common low level exit codes
}
Interop.mincore.RaiseFailFastException(errorCode, pExAddress, pExContext);
}
// Use a nested class to avoid running the class constructor of the outer class when
// accessing this flag.
private static class InFailFast
{
// This boolean is used to stop runaway FailFast recursions. Though this is technically a concurrently set field, it only gets set during
// fatal process shutdowns and it's only purpose is a reasonable-case effort to make a bad situation a little less bad.
// Trying to use locks or other concurrent access apis would actually defeat the purpose of making FailFast as robust as possible.
public static bool Value;
}
#pragma warning disable 414 // field is assigned, but never used -- This is because C# doesn't realize that we
// copy the field into a buffer.
/// <summary>
/// This is the header that describes our 'error report' buffer to the minidump auxillary provider.
/// Its format is know to that system-wide DLL, so do not change it. The remainder of the buffer is
/// opaque to the minidump auxillary provider, so it'll have its own format that is more easily
/// changed.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct ERROR_REPORT_BUFFER_HEADER
{
private int _headerSignature;
private int _bufferByteCount;
public void WriteHeader(int cbBuffer)
{
_headerSignature = 0x31304244; // 'DB01'
_bufferByteCount = cbBuffer;
}
}
/// <summary>
/// This header describes the contents of the serialized error report to DAC, which can deserialize it
/// from a dump file or live debugging session. This format is easier to change than the
/// ERROR_REPORT_BUFFER_HEADER, but it is still well-known to DAC, so any changes must update the
/// version number and also have corresponding changes made to DAC.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct SERIALIZED_ERROR_REPORT_HEADER
{
private int _errorReportSignature; // This is the version of the 'container format'.
private int _exceptionSerializationVersion; // This is the version of the Exception format. It is
// separate from the 'container format' version since the
// implementation of the Exception serialization is owned by
// the Exception class.
private int _exceptionCount; // We just contain a logical array of exceptions.
private int _loadedModuleCount; // Number of loaded modules. present when signature >= ER02.
// {ExceptionCount} serialized Exceptions follow.
// {LoadedModuleCount} module handles follow. present when signature >= ER02.
public void WriteHeader(int nExceptions, int nLoadedModules)
{
_errorReportSignature = 0x32305245; // 'ER02'
_exceptionSerializationVersion = Exception.CurrentSerializationSignature;
_exceptionCount = nExceptions;
_loadedModuleCount = nLoadedModules;
}
}
/// <summary>
/// Holds metadata about an exception in flight. Class because ConditionalWeakTable only accepts reference types
/// </summary>
private class ExceptionData
{
public ExceptionData()
{
// Set this to a non-zero value so that logic mapping entries to threads
// doesn't think an uninitialized ExceptionData is on thread 0
ExceptionMetadata.ThreadId = 0xFFFFFFFF;
}
public struct ExceptionMetadataStruct
{
public UInt32 ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0.
public UInt32 InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception'
public UInt32 ThreadId { get; set; } // Managed thread ID the eception was thrown on
public Int32 NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them.
// The highest number is the most recent exception. -1 means the exception is not currently in flight
// (but it may still be an InnerException).
public IntPtr ExceptionCCWPtr { get; set; } // If the exception was thrown in an interop scenario, this contains the CCW pointer, otherwise, IntPtr.Zero
}
public ExceptionMetadataStruct ExceptionMetadata;
/// <summary>
/// Data created by Exception.SerializeForDump()
/// </summary>
public byte[] SerializedExceptionData { get; set; }
/// <summary>
/// Serializes the exception metadata and SerializedExceptionData
/// </summary>
public unsafe byte[] Serialize()
{
checked
{
byte[] serializedData = new byte[sizeof(ExceptionMetadataStruct) + SerializedExceptionData.Length];
fixed (byte* pSerializedData = &serializedData[0])
{
ExceptionMetadataStruct* pMetadata = (ExceptionMetadataStruct*)pSerializedData;
pMetadata->ExceptionId = ExceptionMetadata.ExceptionId;
pMetadata->InnerExceptionId = ExceptionMetadata.InnerExceptionId;
pMetadata->ThreadId = ExceptionMetadata.ThreadId;
pMetadata->NestingLevel = ExceptionMetadata.NestingLevel;
pMetadata->ExceptionCCWPtr = ExceptionMetadata.ExceptionCCWPtr;
PInvokeMarshal.CopyToNative(SerializedExceptionData, 0, (IntPtr)(pSerializedData + sizeof(ExceptionMetadataStruct)), SerializedExceptionData.Length);
}
return serializedData;
}
}
}
/// <summary>
/// Table of exceptions that were on stacks triggering GenerateExceptionInformationForDump
/// </summary>
private static readonly ConditionalWeakTable<Exception, ExceptionData> s_exceptionDataTable = new ConditionalWeakTable<Exception, ExceptionData>();
/// <summary>
/// Counter for exception ID assignment
/// </summary>
private static int s_currentExceptionId = 0;
/// <summary>
/// This method will call the runtime to gather the Exception objects from every exception dispatch in
/// progress on the current thread. It will then serialize them into a new buffer and pass that
/// buffer back to the runtime, which will publish it to a place where a global "minidump auxillary
/// provider" will be able to save the buffer's contents into triage dumps.
///
/// Thread safety information: The guarantee of this method is that the buffer it produces will have
/// complete and correct information for all live exceptions on the current thread (as long as the same exception object
/// is not thrown simultaneously on multiple threads). It will do a best-effort attempt to serialize information about exceptions
/// already recorded on other threads, but that data can be lost or corrupted. The restrictions are:
/// 1. Only exceptions active or recorded on the current thread have their table data modified.
/// 2. After updating data in the table, we serialize a snapshot of the table (provided by ConditionalWeakTable.Values),
/// regardless of what other threads might do to the table before or after. However, because of #1, this thread's
/// exception data should stay stable
/// 3. There is a dependency on the fact that ConditionalWeakTable's members are all threadsafe and that .Values returns a snapshot
/// </summary>
public static void GenerateExceptionInformationForDump(Exception currentException, IntPtr exceptionCCWPtr)
{
LowLevelList<byte[]> serializedExceptions = new LowLevelList<byte[]>();
// If currentException is null, there's a state corrupting exception in flight and we can't serialize it
if (currentException != null)
{
SerializeExceptionsForDump(currentException, exceptionCCWPtr, serializedExceptions);
}
GenerateErrorReportForDump(serializedExceptions);
}
private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList<byte[]> serializedExceptions)
{
const UInt32 NoInnerExceptionValue = 0xFFFFFFFF;
// Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException)
// If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions.
const int MaxBufferSize = 20000;
int nExceptions;
RuntimeImports.RhGetExceptionsForCurrentThread(null, out nExceptions);
Exception[] curThreadExceptions = new Exception[nExceptions];
RuntimeImports.RhGetExceptionsForCurrentThread(curThreadExceptions, out nExceptions);
LowLevelList<Exception> exceptions = new LowLevelList<Exception>(curThreadExceptions);
LowLevelList<Exception> nonThrownInnerExceptions = new LowLevelList<Exception>();
uint currentThreadId = (uint)Environment.CurrentNativeThreadId;
// Reset nesting levels for exceptions on this thread that might not be currently in flight
foreach (KeyValuePair<Exception, ExceptionData> item in s_exceptionDataTable)
{
ExceptionData exceptionData = item.Value;
if (exceptionData.ExceptionMetadata.ThreadId == currentThreadId)
{
exceptionData.ExceptionMetadata.NestingLevel = -1;
}
}
// Find all inner exceptions, even if they're not currently being handled
for (int i = 0; i < exceptions.Count; i++)
{
if (exceptions[i].InnerException != null && !exceptions.Contains(exceptions[i].InnerException))
{
exceptions.Add(exceptions[i].InnerException);
nonThrownInnerExceptions.Add(exceptions[i].InnerException);
}
}
int currentNestingLevel = curThreadExceptions.Length - 1;
// Make sure we serialize currentException
if (!exceptions.Contains(currentException))
{
// When this happens, currentException is probably passed to this function through System.Environment.FailFast(), we
// would want to treat as if this exception is last thrown in the current thread.
exceptions.Insert(0, currentException);
currentNestingLevel++;
}
// Populate exception data for all exceptions interesting to this thread.
// Whether or not there was previously data for that object, it might have changed.
for (int i = 0; i < exceptions.Count; i++)
{
ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]);
exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId);
if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue)
{
exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId);
}
exceptionData.ExceptionMetadata.ThreadId = currentThreadId;
// Only include nesting information for exceptions that were thrown on this thread
if (!nonThrownInnerExceptions.Contains(exceptions[i]))
{
exceptionData.ExceptionMetadata.NestingLevel = currentNestingLevel;
currentNestingLevel--;
}
else
{
exceptionData.ExceptionMetadata.NestingLevel = -1;
}
// Only match the CCW pointer up to the current exception
if (Object.ReferenceEquals(exceptions[i], currentException))
{
exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr;
}
byte[] serializedEx = exceptions[i].SerializeForDump();
exceptionData.SerializedExceptionData = serializedEx;
}
// Populate inner exception ids now that we have all of them in the table
for (int i = 0; i < exceptions.Count; i++)
{
ExceptionData exceptionData;
if (!s_exceptionDataTable.TryGetValue(exceptions[i], out exceptionData))
{
// This shouldn't happen, but we can't meaningfully throw here
continue;
}
if (exceptions[i].InnerException != null)
{
ExceptionData innerExceptionData;
if (s_exceptionDataTable.TryGetValue(exceptions[i].InnerException, out innerExceptionData))
{
exceptionData.ExceptionMetadata.InnerExceptionId = innerExceptionData.ExceptionMetadata.ExceptionId;
}
}
else
{
exceptionData.ExceptionMetadata.InnerExceptionId = NoInnerExceptionValue;
}
}
int totalSerializedExceptionSize = 0;
// Make sure we include the current exception, regardless of buffer size
ExceptionData currentExceptionData = null;
if (s_exceptionDataTable.TryGetValue(currentException, out currentExceptionData))
{
byte[] serializedExceptionData = currentExceptionData.Serialize();
serializedExceptions.Add(serializedExceptionData);
totalSerializedExceptionSize = serializedExceptionData.Length;
}
checked
{
foreach (KeyValuePair<Exception, ExceptionData> item in s_exceptionDataTable)
{
ExceptionData exceptionData = item.Value;
// Already serialized currentException
if (currentExceptionData != null && exceptionData.ExceptionMetadata.ExceptionId == currentExceptionData.ExceptionMetadata.ExceptionId)
{
continue;
}
byte[] serializedExceptionData = exceptionData.Serialize();
if (totalSerializedExceptionSize + serializedExceptionData.Length >= MaxBufferSize)
{
break;
}
serializedExceptions.Add(serializedExceptionData);
totalSerializedExceptionSize += serializedExceptionData.Length;
}
}
}
private static unsafe void GenerateErrorReportForDump(LowLevelList<byte[]> serializedExceptions)
{
checked
{
int loadedModuleCount = RuntimeAugments.GetLoadedOSModules(null);
int cbModuleHandles = sizeof(System.IntPtr) * loadedModuleCount;
int cbFinalBuffer = sizeof(ERROR_REPORT_BUFFER_HEADER) + sizeof(SERIALIZED_ERROR_REPORT_HEADER) + cbModuleHandles;
for (int i = 0; i < serializedExceptions.Count; i++)
{
cbFinalBuffer += serializedExceptions[i].Length;
}
byte[] finalBuffer = new byte[cbFinalBuffer];
fixed (byte* pBuffer = &finalBuffer[0])
{
byte* pCursor = pBuffer;
int cbRemaining = cbFinalBuffer;
ERROR_REPORT_BUFFER_HEADER* pDacHeader = (ERROR_REPORT_BUFFER_HEADER*)pCursor;
pDacHeader->WriteHeader(cbFinalBuffer);
pCursor += sizeof(ERROR_REPORT_BUFFER_HEADER);
cbRemaining -= sizeof(ERROR_REPORT_BUFFER_HEADER);
SERIALIZED_ERROR_REPORT_HEADER* pPayloadHeader = (SERIALIZED_ERROR_REPORT_HEADER*)pCursor;
pPayloadHeader->WriteHeader(serializedExceptions.Count, loadedModuleCount);
pCursor += sizeof(SERIALIZED_ERROR_REPORT_HEADER);
cbRemaining -= sizeof(SERIALIZED_ERROR_REPORT_HEADER);
// copy the serialized exceptions to report buffer
for (int i = 0; i < serializedExceptions.Count; i++)
{
int cbChunk = serializedExceptions[i].Length;
PInvokeMarshal.CopyToNative(serializedExceptions[i], 0, (IntPtr)pCursor, cbChunk);
cbRemaining -= cbChunk;
pCursor += cbChunk;
}
// copy the module-handle array to report buffer
IntPtr[] loadedModuleHandles = new IntPtr[loadedModuleCount];
RuntimeAugments.GetLoadedOSModules(loadedModuleHandles);
PInvokeMarshal.CopyToNative(loadedModuleHandles, 0, (IntPtr)pCursor, loadedModuleHandles.Length);
cbRemaining -= cbModuleHandles;
pCursor += cbModuleHandles;
Debug.Assert(cbRemaining == 0);
}
UpdateErrorReportBuffer(finalBuffer);
}
}
// This returns "true" once enough of the framework has been initialized to safely perform operations
// such as filling in the stack frame and generating diagnostic support.
public static bool SafeToPerformRichExceptionSupport
{
get
{
// Reflection needs to work as the exception code calls GetType() and GetType().ToString()
if (RuntimeAugments.CallbacksIfAvailable == null)
return false;
return true;
}
}
private static GCHandle s_ExceptionInfoBufferPinningHandle;
private static Lock s_ExceptionInfoBufferLock = new Lock();
private static unsafe void UpdateErrorReportBuffer(byte[] finalBuffer)
{
Debug.Assert(finalBuffer?.Length > 0);
using (LockHolder.Hold(s_ExceptionInfoBufferLock))
{
fixed (byte* pBuffer = &finalBuffer[0])
{
byte* pPrevBuffer = (byte*)RuntimeImports.RhSetErrorInfoBuffer(pBuffer);
Debug.Assert(s_ExceptionInfoBufferPinningHandle.IsAllocated == (pPrevBuffer != null));
if (pPrevBuffer != null)
{
byte[] currentExceptionInfoBuffer = (byte[])s_ExceptionInfoBufferPinningHandle.Target;
Debug.Assert(currentExceptionInfoBuffer?.Length > 0);
fixed (byte* pPrev = ¤tExceptionInfoBuffer[0])
Debug.Assert(pPrev == pPrevBuffer);
}
if (!s_ExceptionInfoBufferPinningHandle.IsAllocated)
{
// We allocate a pinning GC handle because we are logically giving the runtime 'unmanaged memory'.
s_ExceptionInfoBufferPinningHandle = GCHandle.Alloc(finalBuffer, GCHandleType.Pinned);
}
else
{
s_ExceptionInfoBufferPinningHandle.Target = finalBuffer;
}
}
}
}
}
}
| |
/*
* 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 ParquetSharp.Column.Values.Dictionary
{
using System.Text;
using ParquetSharp.Bytes;
using ParquetSharp.Column.Impl;
using ParquetSharp.Column.Page;
using ParquetSharp.Column.Values.Plain;
using ParquetSharp.External;
using ParquetSharp.IO;
using ParquetSharp.IO.Api;
using Encoding = ParquetSharp.Column.Encoding;
/**
* a simple implementation of dictionary for plain encoded values
*
*/
public abstract class PlainValuesDictionary : Dictionary
{
/**
* @param dictionaryPage the PLAIN encoded content of the dictionary
* @throws IOException
*/
protected PlainValuesDictionary(DictionaryPage dictionaryPage)
: base(dictionaryPage.getEncoding())
{
if (dictionaryPage.getEncoding() != Encoding.PLAIN_DICTIONARY
&& dictionaryPage.getEncoding() != Encoding.PLAIN)
{
throw new ParquetDecodingException("Dictionary data encoding type not supported: " + dictionaryPage.getEncoding());
}
}
/**
* a simple implementation of dictionary for plain encoded binary
*/
public class PlainBinaryDictionary : PlainValuesDictionary
{
private Binary[] binaryDictionaryContent = null;
/**
* Decodes {@link Binary} values from a {@link DictionaryPage}.
*
* Values are read as length-prefixed values with a 4-byte little-endian
* length.
*
* @param dictionaryPage a {@code DictionaryPage} of encoded binary values
* @throws IOException
*/
public PlainBinaryDictionary(DictionaryPage dictionaryPage)
: this(dictionaryPage, null)
{
}
/**
* Decodes {@link Binary} values from a {@link DictionaryPage}.
*
* If the given {@code length} is null, the values will be read as length-
* prefixed values with a 4-byte little-endian length. If length is not
* null, it will be used as the length for all fixed-length {@code Binary}
* values read from the page.
*
* @param dictionaryPage a {@code DictionaryPage} of encoded binary values
* @param length a fixed length of binary arrays, or null if not fixed
* @throws IOException
*/
public PlainBinaryDictionary(DictionaryPage dictionaryPage, int? length)
: base(dictionaryPage)
{
ByteBuffer dictionaryBytes = dictionaryPage.getBytes().toByteBuffer();
binaryDictionaryContent = new Binary[dictionaryPage.getDictionarySize()];
// dictionary values are stored in order: size (4 bytes LE) followed by {size} bytes
int offset = dictionaryBytes.position();
if (length == null)
{
// dictionary values are stored in order: size (4 bytes LE) followed by {size} bytes
for (int i = 0; i < binaryDictionaryContent.Length; i++)
{
int len = BytesUtils.readIntLittleEndian(dictionaryBytes, offset);
// read the length
offset += 4;
// wrap the content in a binary
binaryDictionaryContent[i] = Binary.fromConstantByteBuffer(dictionaryBytes, offset, len);
// increment to the next value
offset += len;
}
}
else
{
// dictionary values are stored as fixed-length arrays
Preconditions.checkArgument(length > 0,
"Invalid byte array length: " + length);
for (int i = 0; i < binaryDictionaryContent.Length; i++)
{
// wrap the content in a Binary
binaryDictionaryContent[i] = Binary.fromConstantByteBuffer(
dictionaryBytes, offset, length.Value);
// increment to the next value
offset += length.Value;
}
}
}
public override Binary decodeToBinary(int id)
{
return binaryDictionaryContent[id];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("PlainBinaryDictionary {\n");
for (int i = 0; i < binaryDictionaryContent.Length; i++)
{
sb.Append(i).Append(" => ").Append(binaryDictionaryContent[i]).Append("\n");
}
return sb.Append("}").ToString();
}
public override int getMaxId()
{
return binaryDictionaryContent.Length - 1;
}
}
/**
* a simple implementation of dictionary for plain encoded long values
*/
public class PlainLongDictionary : PlainValuesDictionary
{
private long[] longDictionaryContent = null;
/**
* @param dictionaryPage
* @throws IOException
*/
public PlainLongDictionary(DictionaryPage dictionaryPage)
: base(dictionaryPage)
{
ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer();
longDictionaryContent = new long[dictionaryPage.getDictionarySize()];
PlainValuesReader.LongPlainValuesReader longReader = new PlainValuesReader.LongPlainValuesReader();
longReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, dictionaryByteBuf.position());
for (int i = 0; i < longDictionaryContent.Length; i++)
{
longDictionaryContent[i] = longReader.readLong();
}
}
public override long decodeToLong(int id)
{
return longDictionaryContent[id];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("PlainLongDictionary {\n");
for (int i = 0; i < longDictionaryContent.Length; i++)
{
sb.Append(i).Append(" => ").Append(longDictionaryContent[i]).Append("\n");
}
return sb.Append("}").ToString();
}
public override int getMaxId()
{
return longDictionaryContent.Length - 1;
}
}
/**
* a simple implementation of dictionary for plain encoded double values
*/
public class PlainDoubleDictionary : PlainValuesDictionary
{
private double[] doubleDictionaryContent = null;
/**
* @param dictionaryPage
* @throws IOException
*/
public PlainDoubleDictionary(DictionaryPage dictionaryPage)
: base(dictionaryPage)
{
ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer();
doubleDictionaryContent = new double[dictionaryPage.getDictionarySize()];
PlainValuesReader.DoublePlainValuesReader doubleReader = new PlainValuesReader.DoublePlainValuesReader();
doubleReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, 0);
for (int i = 0; i < doubleDictionaryContent.Length; i++)
{
doubleDictionaryContent[i] = doubleReader.readDouble();
}
}
public override double decodeToDouble(int id)
{
return doubleDictionaryContent[id];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("PlainDoubleDictionary {\n");
for (int i = 0; i < doubleDictionaryContent.Length; i++)
{
sb.Append(i).Append(" => ").Append(doubleDictionaryContent[i]).Append("\n");
}
return sb.Append("}").ToString();
}
public override int getMaxId()
{
return doubleDictionaryContent.Length - 1;
}
}
/**
* a simple implementation of dictionary for plain encoded integer values
*/
public class PlainIntegerDictionary : PlainValuesDictionary
{
private int[] intDictionaryContent = null;
/**
* @param dictionaryPage
* @throws IOException
*/
public PlainIntegerDictionary(DictionaryPage dictionaryPage)
: base(dictionaryPage)
{
ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer();
intDictionaryContent = new int[dictionaryPage.getDictionarySize()];
PlainValuesReader.IntegerPlainValuesReader intReader = new PlainValuesReader.IntegerPlainValuesReader();
intReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, 0);
for (int i = 0; i < intDictionaryContent.Length; i++)
{
intDictionaryContent[i] = intReader.readInteger();
}
}
public override int decodeToInt(int id)
{
return intDictionaryContent[id];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("PlainIntegerDictionary {\n");
for (int i = 0; i < intDictionaryContent.Length; i++)
{
sb.Append(i).Append(" => ").Append(intDictionaryContent[i]).Append("\n");
}
return sb.Append("}").ToString();
}
public override int getMaxId()
{
return intDictionaryContent.Length - 1;
}
}
/**
* a simple implementation of dictionary for plain encoded float values
*/
public class PlainFloatDictionary : PlainValuesDictionary
{
private float[] floatDictionaryContent = null;
/**
* @param dictionaryPage
* @throws IOException
*/
public PlainFloatDictionary(DictionaryPage dictionaryPage)
: base(dictionaryPage)
{
ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer();
floatDictionaryContent = new float[dictionaryPage.getDictionarySize()];
PlainValuesReader.FloatPlainValuesReader floatReader = new PlainValuesReader.FloatPlainValuesReader();
floatReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, dictionaryByteBuf.position());
for (int i = 0; i < floatDictionaryContent.Length; i++)
{
floatDictionaryContent[i] = floatReader.readFloat();
}
}
public override float decodeToFloat(int id)
{
return floatDictionaryContent[id];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("PlainFloatDictionary {\n");
for (int i = 0; i < floatDictionaryContent.Length; i++)
{
sb.Append(i).Append(" => ").Append(floatDictionaryContent[i]).Append("\n");
}
return sb.Append("}").ToString();
}
public override int getMaxId()
{
return floatDictionaryContent.Length - 1;
}
}
}
}
| |
using System;
using System.Text;
namespace Vostok.Commons.Binary
{
public class BinaryBufferReader : IBinaryReader
{
public BinaryBufferReader(byte[] buffer, int position)
{
Buffer = buffer;
Position = position;
}
public byte[] Buffer { get; }
public int Position { get; set; }
public int BytesRemaining => Buffer.Length - Position;
public unsafe int ReadInt32()
{
CheckBounds(sizeof(int));
int result;
fixed (byte* ptr = &Buffer[Position])
result = *(int*)ptr;
Position += sizeof(int);
return result;
}
public unsafe long ReadInt64()
{
CheckBounds(sizeof(long));
long result;
fixed (byte* ptr = &Buffer[Position])
result = *(long*)ptr;
Position += sizeof(long);
return result;
}
public unsafe short ReadInt16()
{
CheckBounds(sizeof(short));
short result;
fixed (byte* ptr = &Buffer[Position])
result = *(short*)ptr;
Position += sizeof(short);
return result;
}
public unsafe uint ReadUInt32()
{
CheckBounds(sizeof(uint));
uint result;
fixed (byte* ptr = &Buffer[Position])
result = *(uint*)ptr;
Position += sizeof(uint);
return result;
}
public unsafe ulong ReadUInt64()
{
CheckBounds(sizeof(ulong));
ulong result;
fixed (byte* ptr = &Buffer[Position])
result = *(ulong*)ptr;
Position += sizeof(ulong);
return result;
}
public unsafe ushort ReadUInt16()
{
CheckBounds(sizeof(ushort));
ushort result;
fixed (byte* ptr = &Buffer[Position])
result = *(ushort*)ptr;
Position += sizeof(ushort);
return result;
}
public unsafe Guid ReadGuid()
{
CheckBounds(sizeof(Guid));
Guid result;
fixed (byte* ptr = &Buffer[Position])
result = *(Guid*)ptr;
Position += sizeof(Guid);
return result;
}
public byte ReadByte()
{
return Buffer[Position++];
}
public bool ReadBool()
{
return ReadByte() != 0;
}
public unsafe float ReadFloat()
{
CheckBounds(sizeof(float));
float result;
fixed (byte* ptr = &Buffer[Position])
result = *(float*)ptr;
Position += sizeof(float);
return result;
}
public unsafe double ReadDouble()
{
CheckBounds(sizeof(double));
double result;
fixed (byte* ptr = &Buffer[Position])
result = *(double*)ptr;
Position += sizeof(double);
return result;
}
public string ReadString(Encoding encoding)
{
var size = ReadInt32();
CheckBounds(size);
var result = encoding.GetString(Buffer, Position, size);
Position += size;
return result;
}
public string ReadString(Encoding encoding, int size)
{
CheckBounds(size);
var result = encoding.GetString(Buffer, Position, size);
Position += size;
return result;
}
public byte[] ReadByteArray()
{
var size = ReadInt32();
CheckBounds(size);
var result = new byte[size];
System.Buffer.BlockCopy(Buffer, Position, result, 0, size);
Position += size;
return result;
}
public byte[] ReadByteArray(int size)
{
CheckBounds(size);
var result = new byte[size];
System.Buffer.BlockCopy(Buffer, Position, result, 0, size);
Position += size;
return result;
}
private void CheckBounds(int size)
{
if (Position + size > Buffer.Length)
throw new IndexOutOfRangeException();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.SecurityTokenService;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace MyCSOMAppWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
SecondaryClientSecret,
authorizationCode,
redirectUri,
resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, SecondaryClientSecret, refreshToken, resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, SecondaryClientSecret, resource);
oauth2Request.Resource = resource;
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an add-in event
/// </summary>
/// <param name="properties">Properties of an add-in event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted add-in configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// 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.Globalization;
using System.Linq;
using Xunit;
namespace System.Tests
{
public partial class StringTests
{
[Theory]
[InlineData("Hello", 'o', true)]
[InlineData("Hello", 'O', false)]
[InlineData("o", 'o', true)]
[InlineData("o", 'O', false)]
[InlineData("Hello", 'e', false)]
[InlineData("Hello", '\0', false)]
[InlineData("", '\0', false)]
[InlineData("\0", '\0', true)]
[InlineData("", 'a', false)]
[InlineData("abcdefghijklmnopqrstuvwxyz", 'z', true)]
public static void EndsWith(string s, char value, bool expected)
{
Assert.Equal(expected, s.EndsWith(value));
}
[Theory]
[InlineData("Hello", 'H', true)]
[InlineData("Hello", 'h', false)]
[InlineData("H", 'H', true)]
[InlineData("H", 'h', false)]
[InlineData("Hello", 'e', false)]
[InlineData("Hello", '\0', false)]
[InlineData("", '\0', false)]
[InlineData("\0", '\0', true)]
[InlineData("", 'a', false)]
[InlineData("abcdefghijklmnopqrstuvwxyz", 'a', true)]
public static void StartsWith(string s, char value, bool expected)
{
Assert.Equal(expected, s.StartsWith(value));
}
public static IEnumerable<object[]> Join_Char_StringArray_TestData()
{
yield return new object[] { '|', new string[0], 0, 0, "" };
yield return new object[] { '|', new string[] { "a" }, 0, 1, "a" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 3, "a|b|c" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 2, "a|b" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 1, "b" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 1, 2, "b|c" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 3, 0, "" };
yield return new object[] { '|', new string[] { "a", "b", "c" }, 0, 0, "" };
yield return new object[] { '|', new string[] { "", "", "" }, 0, 3, "||" };
yield return new object[] { '|', new string[] { null, null, null }, 0, 3, "||" };
}
[Theory]
[MemberData(nameof(Join_Char_StringArray_TestData))]
public static void Join_Char_StringArray(char separator, string[] values, int startIndex, int count, string expected)
{
if (startIndex == 0 && count == values.Length)
{
Assert.Equal(expected, string.Join(separator, values));
Assert.Equal(expected, string.Join(separator, (IEnumerable<string>)values));
Assert.Equal(expected, string.Join(separator, (object[])values));
Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values));
}
Assert.Equal(expected, string.Join(separator, values, startIndex, count));
Assert.Equal(expected, string.Join(separator.ToString(), values, startIndex, count));
}
public static IEnumerable<object[]> Join_Char_ObjectArray_TestData()
{
yield return new object[] { '|', new object[0], "" };
yield return new object[] { '|', new object[] { 1 }, "1" };
yield return new object[] { '|', new object[] { 1, 2, 3 }, "1|2|3" };
yield return new object[] { '|', new object[] { new ObjectWithNullToString(), 2, new ObjectWithNullToString() }, "|2|" };
yield return new object[] { '|', new object[] { "1", null, "3" }, "1||3" };
yield return new object[] { '|', new object[] { "", "", "" }, "||" };
yield return new object[] { '|', new object[] { "", null, "" }, "||" };
yield return new object[] { '|', new object[] { null, null, null }, "||" };
}
[Theory]
[MemberData(nameof(Join_Char_ObjectArray_TestData))]
public static void Join_Char_ObjectArray(char separator, object[] values, string expected)
{
Assert.Equal(expected, string.Join(separator, values));
Assert.Equal(expected, string.Join(separator, (IEnumerable<object>)values));
}
[Fact]
public static void Join_Char_NullValues_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null));
AssertExtensions.Throws<ArgumentNullException>("value", () => string.Join('|', (string[])null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (object[])null));
AssertExtensions.Throws<ArgumentNullException>("values", () => string.Join('|', (IEnumerable<object>)null));
}
[Fact]
public static void Join_Char_NegativeStartIndex_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, -1, 0));
}
[Fact]
public static void Join_Char_NegativeCount_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => string.Join('|', new string[] { "Foo" }, 0, -1));
}
[Theory]
[InlineData(2, 1)]
[InlineData(2, 0)]
[InlineData(1, 2)]
[InlineData(1, 1)]
[InlineData(0, 2)]
[InlineData(-1, 0)]
public static void Join_Char_InvalidStartIndexCount_ThrowsArgumentOutOfRangeException(int startIndex, int count)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => string.Join('|', new string[] { "Foo" }, startIndex, count));
}
public static IEnumerable<object[]> Replace_StringComparison_TestData()
{
yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCulture, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCulture, "abc" };
yield return new object[] { "abc", "abc", "", StringComparison.CurrentCulture, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCulture, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.CurrentCulture, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.CurrentCulture, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCulture, "def" };
yield return new object[] { "abc", "abc", "def", StringComparison.CurrentCultureIgnoreCase, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.CurrentCultureIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "", StringComparison.CurrentCultureIgnoreCase, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.CurrentCultureIgnoreCase, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.CurrentCultureIgnoreCase, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.CurrentCultureIgnoreCase, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.CurrentCultureIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "def", StringComparison.Ordinal, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.Ordinal, "abc" };
yield return new object[] { "abc", "abc", "", StringComparison.Ordinal, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.Ordinal, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.Ordinal, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.Ordinal, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.Ordinal, "abc" };
yield return new object[] { "abc", "abc", "def", StringComparison.OrdinalIgnoreCase, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.OrdinalIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "", StringComparison.OrdinalIgnoreCase, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.OrdinalIgnoreCase, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.OrdinalIgnoreCase, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.OrdinalIgnoreCase, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.OrdinalIgnoreCase, "abc" };
yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCulture, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCulture, "abc" };
yield return new object[] { "abc", "abc", "", StringComparison.InvariantCulture, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCulture, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.InvariantCulture, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.InvariantCulture, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCulture, "def" };
yield return new object[] { "abc", "abc", "def", StringComparison.InvariantCultureIgnoreCase, "def" };
yield return new object[] { "abc", "ABC", "def", StringComparison.InvariantCultureIgnoreCase, "def" };
yield return new object[] { "abc", "abc", "", StringComparison.InvariantCultureIgnoreCase, "" };
yield return new object[] { "abc", "b", "LONG", StringComparison.InvariantCultureIgnoreCase, "aLONGc" };
yield return new object[] { "abc", "b", "d", StringComparison.InvariantCultureIgnoreCase, "adc" };
yield return new object[] { "abc", "b", null, StringComparison.InvariantCultureIgnoreCase, "ac" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", StringComparison.InvariantCultureIgnoreCase, "def" };
string turkishSource = "\u0069\u0130";
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.Ordinal, "a\u0130" };
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.OrdinalIgnoreCase, "a\u0130" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.Ordinal, "\u0069a" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.OrdinalIgnoreCase, "\u0069a" };
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCulture, "a\u0130" };
yield return new object[] { turkishSource, "\u0069", "a", StringComparison.InvariantCultureIgnoreCase, "a\u0130" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCulture, "\u0069a" };
yield return new object[] { turkishSource, "\u0130", "a", StringComparison.InvariantCultureIgnoreCase, "\u0069a" };
}
[Theory]
[MemberData(nameof(Replace_StringComparison_TestData))]
public void Replace_StringComparison_ReturnsExpected(string original, string oldValue, string newValue, StringComparison comparisonType, string expected)
{
Assert.Equal(expected, original.Replace(oldValue, newValue, comparisonType));
}
[Fact]
public void Replace_StringComparison_TurkishI()
{
string source = "\u0069\u0130";
Helpers.PerformActionWithCulture(new CultureInfo("tr-TR"), () =>
{
Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture));
Assert.Equal("aa", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture));
Assert.Equal("aa", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
});
Helpers.PerformActionWithCulture(new CultureInfo("en-US"), () =>
{
Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture));
Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture));
Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
});
}
public static IEnumerable<object[]> Replace_StringComparisonCulture_TestData()
{
yield return new object[] { "abc", "abc", "def", false, null, "def" };
yield return new object[] { "abc", "ABC", "def", false, null, "abc" };
yield return new object[] { "abc", "abc", "def", false, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "ABC", "def", false, CultureInfo.InvariantCulture, "abc" };
yield return new object[] { "abc", "abc", "def", true, null, "def" };
yield return new object[] { "abc", "ABC", "def", true, null, "def" };
yield return new object[] { "abc", "abc", "def", true, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "ABC", "def", true, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, null, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, null, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", false, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "abc", "abc" + SoftHyphen, "def", true, CultureInfo.InvariantCulture, "def" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", false, new CultureInfo("tr-TR"), "a\u0130" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", true, new CultureInfo("tr-TR"), "aa" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", false, CultureInfo.InvariantCulture, "a\u0130" };
yield return new object[] { "\u0069\u0130", "\u0069", "a", true, CultureInfo.InvariantCulture, "a\u0130" };
}
[Theory]
[MemberData(nameof(Replace_StringComparisonCulture_TestData))]
public void Replace_StringComparisonCulture_ReturnsExpected(string original, string oldValue, string newValue, bool ignoreCase, CultureInfo culture, string expected)
{
Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, culture));
if (culture == null)
{
Assert.Equal(expected, original.Replace(oldValue, newValue, ignoreCase, CultureInfo.CurrentCulture));
}
}
[Fact]
public void Replace_StringComparison_NullOldValue_ThrowsArgumentException()
{
Assert.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", StringComparison.CurrentCulture));
Assert.Throws<ArgumentNullException>("oldValue", () => "abc".Replace(null, "def", true, CultureInfo.CurrentCulture));
}
[Fact]
public void Replace_StringComparison_EmptyOldValue_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", StringComparison.CurrentCulture));
Assert.Throws<ArgumentException>("oldValue", () => "abc".Replace("", "def", true, CultureInfo.CurrentCulture));
}
[Theory]
[InlineData(StringComparison.CurrentCulture - 1)]
[InlineData(StringComparison.OrdinalIgnoreCase + 1)]
public void Replace_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType)
{
Assert.Throws<ArgumentException>("comparisonType", () => "abc".Replace("abc", "def", comparisonType));
}
private static readonly StringComparison[] StringComparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
public static IEnumerable<object[]> GetHashCode_StringComparison_Data => StringComparisons.Select(value => new object[] { value });
[Theory]
[MemberData(nameof(GetHashCode_StringComparison_Data))]
public static void GetHashCode_StringComparison(StringComparison comparisonType)
{
Assert.Equal(StringComparer.FromComparison(comparisonType).GetHashCode("abc"), "abc".GetHashCode(comparisonType));
}
public static IEnumerable<object[]> GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data => new[]
{
new object[] { StringComparisons.Min() - 1 },
new object[] { StringComparisons.Max() + 1 },
};
[Theory]
[MemberData(nameof(GetHashCode_NoSuchStringComparison_ThrowsArgumentException_Data))]
public static void GetHashCode_NoSuchStringComparison_ThrowsArgumentException(StringComparison comparisonType)
{
Assert.Throws<ArgumentException>("comparisonType", () => "abc".GetHashCode(comparisonType));
}
}
}
| |
/*
Copyright (c) 2013, Keripo
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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.IO;
using System.Collections.Generic;
namespace Beats2.Data {
/// <summary>
/// Parser for .bsf files (Beats Simfiles)
/// </summary>
public class ParserBSF : ParserBase {
new protected const string TAG = "ParserBSF";
/// <summary>
/// "Info" section header name
/// </summary>
private const string INFO_SECTION = "Info";
/// <summary>
/// Minimum .bsf format version supported by this parser
/// </summary>
private const int MIN_VERSION = 1;
/// <summary>
/// Checks the Beats simfile format version
/// </summary>
private void CheckVersion(string val) {
int version = this.ParseInt("Version", val, true);
if (version < MIN_VERSION) {
this.Error("Format version of " + version + " is less than the minimum supported version " + MIN_VERSION);
}
}
/// <summary>
/// Parses a key-value pair using '=' as the separator, see <see cref="ParserBase.ParseKeyValuePair"/>
/// </summary>
private bool ParseKeyValuePair(string line, out string key, out string val) {
return this.ParseKeyValuePair(line, '=', out key, out val);
}
/// <summary>
/// Parses for DisplayBPM values
/// </summary>
private List<float> ParseDisplayBpms(string val) {
List<float> bpms = new List<float>();
foreach (string s in val.Split(',')) {
if (s == "*") {
bpms.Add(Info.RANDOM_DISPLAY_BPM);
} else {
float bpm = this.ParseFloat("DisplayBpm", s, false);
if (bpm > 0f) {
bpms.Add(bpm);
}
}
}
return bpms;
}
/// <summary>
/// Parses for Backgrounds image files
/// </summary>
private List<string> ParseBackgrounds(string val) {
List<string> backgrounds = new List<string>();
foreach (string s in val.Split(',')) {
string background = this.FindImageFile("Background", s, false);
if (background != null) {
backgrounds.Add(background);
}
}
return backgrounds;
}
/// <summary>
/// Parses a pattern section
/// </summary>
private Pattern ParsePattern(string section) {
// Indicies for easy referene
int indexDash = section.IndexOf('-');
int indexComma = section.IndexOf(',');
// Parse pattern type
PatternType patternType = PatternType.BEATS;
try {
patternType = (PatternType)Enum.Parse(
typeof(PatternType),
section.Substring(0, indexDash),
true
);
} catch (ArgumentException e) {
this.Error("Unable to parse section game type, " + e.Message);
}
// Parse key count
int keyCount;
if (!int.TryParse(section.Substring(indexDash + 1, (indexComma - 1) - indexDash), out keyCount)) {
this.Error("Unable to parse sectionkey count");
}
// Parse difficulty level
int difficulty;
if (!int.TryParse(section.Substring(indexComma + 1), out difficulty)) {
this.Error("Unable to parse section difficulty level");
}
// Set the pattern
Pattern pattern = new Pattern();
pattern.type = patternType;
pattern.keyCount = keyCount;
pattern.difficulty = difficulty;
pattern.lineIndex = _index + 1;
pattern.loaded = false;
return pattern;
}
public override void Load(string path) {
base.Load(path);
// Parse line-by-line
_index = 0;
_line = "";
string section = String.Empty;
ReadAheadStreamReader reader = new ReadAheadStreamReader(path);
// Main loop
while (reader.PeekLine() != null) {
_index++;
_line = reader.ReadLine().Trim();
// Empty line
if (_line.Length == 0) {
continue;
// Comment
} else if (_line[0] == '/' || _line[0] == ';') {
continue;
// Section start
} else if (_line[0] == '[') {
if (_line.IndexOf(']') != -1) {
section = _line.Substring(_line.IndexOf('[') + 1, _line.IndexOf(']') - 1);
if (section == INFO_SECTION) {
continue;
} else if (section.IndexOf('-') != -1 && section.IndexOf(',') != -1) {
Pattern pattern = this.ParsePattern(section);
_info.patterns.Add(pattern);
}
}
// Info section
// Note: pattern data is parsed with LoadPattern
} else if (section == INFO_SECTION) {
// Parse key-value pair
string key, val;
if (!this.ParseKeyValuePair(_line, out key, out val)) {
// Skip if not a key-value pair
this.Warning("Unparsed line");
continue;
}
// Set data based on key
switch(key) {
case "Version": this.CheckVersion(val); break;
case "Song": _info.song = this.FindAudioFile("Song", val, true); break;
case "Title": _info.title = val; break;
case "TitleTranslit": _info.titleTranslit = val; break;
case "Subtitle": _info.subtitle = val; break;
case "SubtitleTranslit": _info.subtitleTranslit = val; break;
case "Artist": _info.artist = val; break;
case "ArtistTranslit": _info.artistTranslit = val; break;
case "Album": _info.album = val; break;
case "AlbumTranslit": _info.albumTranslit = val; break;
case "Genre": _info.genre = val; break;
case "Credits": _info.credits = val; break;
case "Link": _info.link = val; break;
case "Description": _info.description = val; break;
case "Tags": _info.tags.AddRange(val.Split(',')); break;
case "DisplayBpm": _info.displayBpm = this.ParseDisplayBpms(val); break;
case "SampleStart": _info.sampleStart = this.ParseFloat("SampleStart", val, false); break;
case "SampleLength": _info.sampleLength = this.ParseFloat("SampleLength", val, false); break;
case "Cover": _info.cover = this.FindImageFile("Cover", val, false); break;
case "Banner": _info.banner = this.FindImageFile("Banner", val, false); break;
case "Backgrounds": _info.backgrounds = this.ParseBackgrounds(val); break;
case "Lyrics": _info.lyrics = this.FindLyricsFile("Lyrics", val, false); break;
default: this.Warning("Unrecognized key: " + key); break;
}
} else {
this.Warning("Unparsed line");
}
}
// Cleanup
reader.Close();
}
/// <summary>
/// Parses the NoteType
/// </summary>
private NoteType ParseNoteType(char c) {
switch (c) {
case '0': return NoteType.MINE;
case '1': return NoteType.TAP;
case '2': return NoteType.HOLD;
case '3': return NoteType.ROLL;
case '4': return NoteType.REPEAT;
case '5': return NoteType.SLIDE;
case 'L': return NoteType.LABEL;
case 'G': return NoteType.BG;
case 'B': return NoteType.BPM;
case 'S': return NoteType.STOP;
default: return NoteType.UNKNOWN;
}
}
/// <summary>
/// Parses notes data
/// </summary>
private void ParseNote(Pattern pattern, string noteType, string noteData) {
Note note;
string[] commaSplit;
string[] lineSplit;
string[] colonSplit;
float time;
int column;
// For now, note types are single characters, may change if necessary in future
if (noteType.Length != 1) {
this.Warning("Unrecognized note type");
return;
}
// Get the first time, because its used by everyone
colonSplit = noteData.Split(':');
if (colonSplit.Length < 2) goto ParseWarning;
time = this.ParseFloat("note time", colonSplit[0], false);
if (time == -1f) goto ParseWarning;
// Parse based on note type
NoteType type = this.ParseNoteType(noteType[0]);
switch (type) {
// MINE: 0=time:column,column,column,...
case NoteType.MINE:
// TAP: 1=time:column,column,column,...
case NoteType.TAP:
// Note columns
commaSplit = noteData.Split(',');
foreach (string s in commaSplit) {
column = this.ParseInt(type + " note column", s, false);
if (column == -1) goto ParseWarning;
note = new Note();
note.type = type;
note.AddPoint(time, column);
this.AddNote(pattern, note);
}
break;
// HOLD: 2=time:column,column,column,...
case NoteType.HOLD:
// ROLL: 3=time:column,column,column,...|time
case NoteType.ROLL:
// Note end time
lineSplit = colonSplit[1].Split('|');
if (lineSplit.Length != 2) goto ParseWarning;
float endTime = this.ParseFloat(type + " note end time", lineSplit[1], false);
if (endTime == -1f) goto ParseWarning;
// Columns
commaSplit = colonSplit[0].Split(',');
foreach (string s in commaSplit) {
column = this.ParseInt(type + " note column", s, false);
if (column == -1) goto ParseWarning;
note = new Note();
note.type = type;
note.AddPoint(time, column);
note.AddPoint(endTime, column);
this.AddNote(pattern, note);
}
break;
// REPEAT: 4=time:column,column,column,...|time|time|time|...
case NoteType.REPEAT:
List<float> times = new List<float>();
List<int> columns = new List<int>();
// Note start time
times.Add(time);
// Time split
lineSplit = noteData.Split('|');
if (lineSplit.Length < 2) goto ParseWarning;
for (int i = 1; i < lineSplit.Length; i++) {
time = this.ParseFloat(type + " note time", lineSplit[i], false);
if (time == -1f) goto ParseWarning;
times.Add(time);
}
// Column
commaSplit = lineSplit[0].Split(',');
if (commaSplit.Length < 1) goto ParseWarning;
foreach (string s in commaSplit) {
column = this.ParseInt(type + " note column", s, false);
if (column == -1) goto ParseWarning;
columns.Add(column);
}
// Add notes
foreach (int c in columns) {
note = new Note();
note.type = type;
foreach (int t in times) {
note.AddPoint(t, c);
}
this.AddNote(pattern, note);
}
break;
// SLIDE: 5=time:column|time:column|time:column|...
case NoteType.SLIDE:
// Only one Note per Slide line
note = new Note();
note.type = type;
// Split into time:column pairs
lineSplit = noteData.Split('|');
if (lineSplit.Length < 2) goto ParseWarning;
// Parse each pair
foreach (string s in lineSplit) {
colonSplit = s.Split(':');
if (colonSplit.Length != 2) goto ParseWarning;
time = this.ParseFloat(type + " note time", colonSplit[0], false);
if (time == -1f) goto ParseWarning;
column = this.ParseInt(type + " note column", colonSplit[1], false);
if (column == -1f) goto ParseWarning;
note.AddPoint(time, column);
}
// Add the note
this.AddNote(pattern, note);
break;
// LABEL: L=time:text
case NoteType.LABEL:
string text = colonSplit[1];
note = new Note();
note.type = NoteType.LABEL;
note.eventTime = time;
note.eventStringVal = text;
this.AddNote(pattern, note);
break;
// BG: G=time:index
case NoteType.BG:
int backgroundIndex = this.ParseInt("Background index", colonSplit[1], false);
if (backgroundIndex == -1) goto ParseWarning;
note = new Note();
note.type = NoteType.BG;
note.eventTime = time;
note.eventIntVal = backgroundIndex;
this.AddNote(pattern, note);
break;
// BPM: B=time:value
case NoteType.BPM:
float bpm = this.ParseFloat("BPM change value", colonSplit[1], false);
if (bpm == -1f) goto ParseWarning;
note = new Note();
note.type = NoteType.BPM;
note.eventTime = time;
note.eventFloatVal = bpm;
this.AddNote(pattern, note);
break;
// STOP: S=time:duration
case NoteType.STOP:
float duration = this.ParseFloat("Stop duration value", colonSplit[1], false);
if (duration == -1f) goto ParseWarning;
note = new Note();
note.type = NoteType.STOP;
note.eventTime = time;
note.eventFloatVal = duration;
this.AddNote(pattern, note);
break;
default:
goto ParseWarning;
}
// Generic warning, out of laziness
ParseWarning:
Warning("Improperly formatted line");
}
public override void LoadPattern(Pattern pattern) {
// Don't unnecessarily reload
if (pattern.loaded == true) {
return;
}
// Parse line-by-line
_index = 0;
_line = "";
ReadAheadStreamReader reader = new ReadAheadStreamReader(_info.path);
// Skip to main section
while (_index < pattern.lineIndex) {
_index++;
reader.SkipLine();
}
// Parsing loop
while (reader.PeekLine() != null) {
_index++;
_line = reader.ReadLine().Trim();
// Empty line
if (_line.Length == 0) {
continue;
// Comment
} else if (_line[0] == ';' || _line[0] == '/') {
continue;
// Section start
} else if (_line[0] == '[') {
break; // End of pattern data
// Pattern data
} else {
// Parse key-value pair
string key, val;
if (!this.ParseKeyValuePair(_line, out key, out val)) {
// Skip if not a key-value pair
this.Warning("Unparsed line");
continue;
}
this.ParseNote(pattern, key, val);
}
}
// Sort notes
this.SortNotes(pattern);
// Cleanup
pattern.loaded = true;
reader.Close();
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Util.Automaton;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
using JCG = J2N.Collections.Generic;
namespace 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 AutomatonQuery = Lucene.Net.Search.AutomatonQuery;
using BytesRef = Lucene.Net.Util.BytesRef;
using CheckHits = Lucene.Net.Search.CheckHits;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using SeekStatus = Lucene.Net.Index.TermsEnum.SeekStatus;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestTermsEnum2 : LuceneTestCase
{
private Directory dir;
private IndexReader reader;
private IndexSearcher searcher;
private JCG.SortedSet<BytesRef> terms; // the terms we put in the index
private Automaton termsAutomaton; // automata of the same
internal int numIterations;
[SetUp]
public override void SetUp()
{
base.SetUp();
// we generate aweful regexps: good for testing.
// but for preflex codec, the test can be very slow, so use less iterations.
numIterations = Codec.Default.Name.Equals("Lucene3x", StringComparison.Ordinal) ? 10 * RandomMultiplier : AtLeast(50);
dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt32(Random, 50, 1000)));
Document doc = new Document();
Field field = NewStringField("field", "", Field.Store.YES);
doc.Add(field);
terms = new JCG.SortedSet<BytesRef>();
int num = AtLeast(200);
for (int i = 0; i < num; i++)
{
string s = TestUtil.RandomUnicodeString(Random);
field.SetStringValue(s);
terms.Add(new BytesRef(s));
writer.AddDocument(doc);
}
termsAutomaton = BasicAutomata.MakeStringUnion(terms);
reader = writer.GetReader();
searcher = NewSearcher(reader);
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
reader.Dispose();
dir.Dispose();
base.TearDown();
}
/// <summary>
/// tests a pre-intersected automaton against the original </summary>
[Test]
public virtual void TestFiniteVersusInfinite()
{
for (int i = 0; i < numIterations; i++)
{
string reg = AutomatonTestUtil.RandomRegexp(Random);
Automaton automaton = (new RegExp(reg, RegExpSyntax.NONE)).ToAutomaton();
IList<BytesRef> matchedTerms = new List<BytesRef>();
foreach (BytesRef t in terms)
{
if (BasicOperations.Run(automaton, t.Utf8ToString()))
{
matchedTerms.Add(t);
}
}
Automaton alternate = BasicAutomata.MakeStringUnion(matchedTerms);
//System.out.println("match " + matchedTerms.Size() + " " + alternate.getNumberOfStates() + " states, sigma=" + alternate.getStartPoints().length);
//AutomatonTestUtil.minimizeSimple(alternate);
//System.out.println("minmize done");
AutomatonQuery a1 = new AutomatonQuery(new Term("field", ""), automaton);
AutomatonQuery a2 = new AutomatonQuery(new Term("field", ""), alternate);
CheckHits.CheckEqual(a1, searcher.Search(a1, 25).ScoreDocs, searcher.Search(a2, 25).ScoreDocs);
}
}
/// <summary>
/// seeks to every term accepted by some automata </summary>
[Test]
public virtual void TestSeeking()
{
for (int i = 0; i < numIterations; i++)
{
string reg = AutomatonTestUtil.RandomRegexp(Random);
Automaton automaton = (new RegExp(reg, RegExpSyntax.NONE)).ToAutomaton();
TermsEnum te = MultiFields.GetTerms(reader, "field").GetEnumerator();
IList<BytesRef> unsortedTerms = new List<BytesRef>(terms);
unsortedTerms.Shuffle(Random);
foreach (BytesRef term in unsortedTerms)
{
if (BasicOperations.Run(automaton, term.Utf8ToString()))
{
// term is accepted
if (Random.NextBoolean())
{
// seek exact
Assert.IsTrue(te.SeekExact(term));
}
else
{
// seek ceil
Assert.AreEqual(SeekStatus.FOUND, te.SeekCeil(term));
Assert.AreEqual(term, te.Term);
}
}
}
}
}
/// <summary>
/// mixes up seek and next for all terms </summary>
[Test]
public virtual void TestSeekingAndNexting()
{
for (int i = 0; i < numIterations; i++)
{
TermsEnum te = MultiFields.GetTerms(reader, "field").GetEnumerator();
foreach (BytesRef term in terms)
{
int c = Random.Next(3);
if (c == 0)
{
Assert.IsTrue(te.MoveNext());
Assert.AreEqual(term, te.Term);
}
else if (c == 1)
{
Assert.AreEqual(SeekStatus.FOUND, te.SeekCeil(term));
Assert.AreEqual(term, te.Term);
}
else
{
Assert.IsTrue(te.SeekExact(term));
}
}
}
}
/// <summary>
/// tests intersect: TODO start at a random term! </summary>
[Test]
public virtual void TestIntersect()
{
for (int i = 0; i < numIterations; i++)
{
string reg = AutomatonTestUtil.RandomRegexp(Random);
Automaton automaton = (new RegExp(reg, RegExpSyntax.NONE)).ToAutomaton();
CompiledAutomaton ca = new CompiledAutomaton(automaton, SpecialOperations.IsFinite(automaton), false);
TermsEnum te = MultiFields.GetTerms(reader, "field").Intersect(ca, null);
Automaton expected = BasicOperations.Intersection(termsAutomaton, automaton);
JCG.SortedSet<BytesRef> found = new JCG.SortedSet<BytesRef>();
while (te.MoveNext())
{
found.Add(BytesRef.DeepCopyOf(te.Term));
}
Automaton actual = BasicAutomata.MakeStringUnion(found);
Assert.IsTrue(BasicOperations.SameLanguage(expected, actual));
}
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Text;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Util;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
class BalanceNodeMgr
{
NodeBalanceData _nodeBalData;
private long _weightToMove = 0;
BalanceDataForNode _primaryNode;
ArrayList _hashMap;
ClusterCacheBase _parent;
public BalanceNodeMgr(ClusterCacheBase parent)
{
_parent = parent;
}
public DistributionMaps BalanceNodes(DistributionInfoData distInfo, ArrayList hashMap, Hashtable bucketStats, ArrayList members)
{
_hashMap = hashMap;
_nodeBalData = new NodeBalanceData(hashMap, bucketStats, members);
//Check if any other state transfer is not in progress...
bool bAllFunctional = this.SanityCheckForAllFunctional(hashMap);
//Add some status saying that node balancing is not possible at the moment.
if (!bAllFunctional)
{
DistributionMaps result = new DistributionMaps(BalancingResult.AlreadyInBalancing);
return result;
}
//Check if really the node needs some balancing or not.
bool bShouldBalance = this.SanityCheckForCandidateNode((Address)distInfo.AffectedNode.NodeAddress);
if (!bShouldBalance)
{
DistributionMaps result = new DistributionMaps(BalancingResult.NotRequired);
return result;
}
ArrayList dataListForNodes = _nodeBalData.BalanceDataListForNodes;
ArrayList candidates = FilterCandidateNodes();
foreach (AddressWeightPair awPair in candidates)
{
BalanceDataForNode secNode = GetBalDataForNode(awPair.NodeAddress);
BalanceTwoNodes(_primaryNode, secNode, awPair.WeightShare);
ApplyChangesInHashMap(secNode);
}
ApplyChangesInHashMap(_primaryNode);
return new DistributionMaps(_hashMap, null);
} //end func.
//data to be moved from Primary node to the secondary node.
//As a result priNode and secNode got updated WeightIdPairLists.
private static void BalanceTwoNodes(BalanceDataForNode priNode, BalanceDataForNode secNode, long dataToMove)
{
int priBucketCount = priNode.ItemsCount;
int secBucketCount = secNode.ItemsCount;
ArrayList priWIPairList = priNode.WeightIdList;
ArrayList secWIPairList = secNode.WeightIdList;
int cushionFactor = 10; // 10% cushion for balancing... +- 10%
long swapWeightGain = 0; // weight gain for this swap
long cushionWeight = Convert.ToInt64(((double)(dataToMove * cushionFactor) / (double)100));
bool bTargetAchieved = false; //loop-invariant, in case we need to exit the loop in middle.
long movedSoFar = 0;
ArrayList usedIndex = new ArrayList(); //this list would keep all those indicies related to Inner loop that are consumed/used in swap.
//Making pivot node to be the secondary one, the one that needs to gain weight.
//swapping or try to swap each element of secNode to all elements of priNode.
//primary is traversed in Descending order, and secondary is traversed in ascending order.
for (int i = 0; i < secBucketCount && !bTargetAchieved; i++)
{
WeightIdPair secWIPair = (WeightIdPair)secWIPairList[i];
for (int j = priBucketCount - 1; j >= 0; j--)
{
WeightIdPair priWIPair = (WeightIdPair) priWIPairList[j];
//only move when there is a gain.
if (priWIPair.Weight > secWIPair.Weight && !usedIndex.Contains(j))
{
swapWeightGain = priWIPair.Weight - secWIPair.Weight;
movedSoFar+= swapWeightGain;
if (movedSoFar <= dataToMove)
{
if (dataToMove - movedSoFar <= cushionWeight)
{
//swap the buckets and exit
secWIPairList[i] = priWIPair;
priWIPairList[j] = secWIPair;
bTargetAchieved = true;
break;
}
else
{
secWIPairList[i] = priWIPair;
priWIPairList[j] = secWIPair;
usedIndex.Add(j);
break; //i need to move fwd now
}
} //end if
else
{
if (movedSoFar - dataToMove <= cushionWeight)
{
//swap the buckets an exit
secWIPairList[i] = priWIPair;
priWIPairList[j] = secWIPair;
bTargetAchieved = true;
break;
}
else
{
movedSoFar-=swapWeightGain;
}
} //end else
}//end if for priWeight > seWeight
}//end inner for loop
}//end outer for loop
//re-assign the WeightIdPairList to respective BalanceDataForNode
priNode.WeightIdList = priWIPairList;
priNode.WeightIdList.Sort();
secNode.WeightIdList = secWIPairList;
secNode.WeightIdList.Sort();
}
private bool SanityCheckForAllFunctional(ArrayList hashMap)
{
bool bAllFunctional = true;
foreach (HashMapBucket hmBuck in hashMap)
{
if (!hmBuck.PermanentAddress.Equals(hmBuck.TempAddress))
{
bAllFunctional = false;
break;
}
}
return bAllFunctional;
}
//Need to check if the source node really needs any balancing?. If the weight is more then the Avg weight/Node then its true else false.
private bool SanityCheckForCandidateNode(Address sourceNode)
{
ArrayList dataListForNodes = _nodeBalData.BalanceDataListForNodes;
foreach (BalanceDataForNode balData in dataListForNodes)
{
if (balData.NodeAddress.Equals(sourceNode))
{
if (balData.PercentData > _nodeBalData.PercentWeightPerNode)
{
this._weightToMove = balData.TotalWeight - this._nodeBalData.WeightPerNode; //Weight to move is the one that is above the Avg. weight the node Should bear.
_primaryNode = balData;
return true;
}
else
return false;
}
} //end foreach loop
return false; //nothing found.
}
//returns list of those nodes that need to be participated in sharing load from Source node.
private ArrayList FilterCandidateNodes()
{
ArrayList dataListForNodes = _nodeBalData.BalanceDataListForNodes;
ArrayList filteredNodes = new ArrayList();
int totalPercentMissing = 0;
int percentMissing = 0;
int percentShareToGain = 0;
//total percentage that the candidate nodes are missing...
foreach (BalanceDataForNode balData in dataListForNodes)
{
if (balData.TotalWeight < _nodeBalData.WeightPerNode)
{
totalPercentMissing += _nodeBalData.PercentWeightPerNode - balData.PercentData;
}
}
//Assigning each candidate node its share from the Source node.
foreach (BalanceDataForNode balData in dataListForNodes)
{
if (balData.TotalWeight < _nodeBalData.WeightPerNode)
{
long weightToGain = 0;
percentMissing = _nodeBalData.PercentWeightPerNode - balData.PercentData;
try
{
percentShareToGain = Convert.ToInt32((double)((double)percentMissing / (double)totalPercentMissing) * 100);
weightToGain = Convert.ToInt64((double)(percentShareToGain * this._weightToMove) / (double)100);
}
catch (Exception) { }
AddressWeightPair awPair = new AddressWeightPair(balData.NodeAddress, weightToGain);
filteredNodes.Add(awPair);
}
}
return filteredNodes;
}
//Returns BalancDataForNode instance for demanded node. from the list
private BalanceDataForNode GetBalDataForNode(Address addr)
{
ArrayList dataListForNodes = _nodeBalData.BalanceDataListForNodes;
foreach (BalanceDataForNode balData in dataListForNodes)
{
if (balData.NodeAddress.Equals(addr))
return balData;
}
return null;
}
private void ApplyChangesInHashMap(BalanceDataForNode secNode)
{
ArrayList weightIdPair = secNode.WeightIdList;
Address newAddr = secNode.NodeAddress;
HashMapBucket bucket = null;
foreach (WeightIdPair widPair in weightIdPair)
{
bucket = (HashMapBucket)_hashMap[widPair.BucketId];
if (!newAddr.Equals(bucket.TempAddress))
bucket.Status = BucketStatus.NeedTransfer;
bucket.TempAddress = newAddr;
}
}
/// <summary>
///
/// </summary>
internal class AddressWeightPair
{
Address _nodeAddr;
long _weightShare = 0;
public AddressWeightPair(Address address, long weightShare)
{
_nodeAddr = address;
_weightShare = weightShare;
}
public Address NodeAddress
{
get { return _nodeAddr; }
}
public long WeightShare
{
get { return _weightShare; }
set { _weightShare = value; }
}
}
}
//This class keeps information related to each indivisual node.
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlInt64.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">junfang</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
//**************************************************************************
// @File: SqlInt64.cs
//
// Create by: JunFang
//
// Purpose: Implementation of SqlInt64 which is equivalent to
// data type "bigint" in SQL Server
//
// Notes:
//
// History:
//
// 10/28/99 JunFang Created.
//
// @EndHeader@
//**************************************************************************
using System;
using System.Data.Common;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes {
/// <devdoc>
/// <para>
/// Represents a 64-bit signed integer to be stored in
/// or retrieved from a database.
/// </para>
/// </devdoc>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
public struct SqlInt64 : INullable, IComparable, IXmlSerializable {
private bool m_fNotNull; // false if null
private long m_value;
private static readonly long x_lLowIntMask = 0xffffffff;
private static readonly long x_lHighIntMask = unchecked((long)0xffffffff00000000);
// constructor
// construct a Null
private SqlInt64(bool fNull) {
m_fNotNull = false;
m_value = 0;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlInt64(long value) {
m_value = value;
m_fNotNull = true;
}
// INullable
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsNull {
get { return !m_fNotNull;}
}
// property: Value
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public long Value {
get {
if (m_fNotNull)
return m_value;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from long to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt64(long x) {
return new SqlInt64(x);
}
// Explicit conversion from SqlInt64 to long. Throw exception if x is Null.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator long(SqlInt64 x) {
return x.Value;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override String ToString() {
return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 Parse(String s) {
if (s == SQLResource.NullString)
return SqlInt64.Null;
else
return new SqlInt64(Int64.Parse(s, (IFormatProvider)null));
}
// Unary operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator -(SqlInt64 x) {
return x.IsNull ? Null : new SqlInt64(-x.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator ~(SqlInt64 x) {
return x.IsNull ? Null : new SqlInt64(~x.m_value);
}
// Binary operators
// Arithmetic operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator +(SqlInt64 x, SqlInt64 y) {
if (x.IsNull || y.IsNull)
return Null;
long lResult = x.m_value + y.m_value;
if (SameSignLong(x.m_value, y.m_value) && !SameSignLong(x.m_value, lResult))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64(lResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator -(SqlInt64 x, SqlInt64 y) {
if (x.IsNull || y.IsNull)
return Null;
long lResult = x.m_value - y.m_value;
if (!SameSignLong(x.m_value, y.m_value) && SameSignLong(y.m_value, lResult))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64(lResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator *(SqlInt64 x, SqlInt64 y) {
if (x.IsNull || y.IsNull)
return Null;
bool fNeg = false;
long lOp1 = x.m_value;
long lOp2 = y.m_value;
long lResult;
long lPartialResult = 0;
if (lOp1 < 0) {
fNeg = true;
lOp1 = - lOp1;
}
if (lOp2 < 0) {
fNeg = !fNeg;
lOp2 = - lOp2;
}
long lLow1 = lOp1 & x_lLowIntMask;
long lHigh1 = (lOp1 >> 32) & x_lLowIntMask;
long lLow2 = lOp2 & x_lLowIntMask;
long lHigh2 = (lOp2 >> 32) & x_lLowIntMask;
// if both of the high order dwords are non-zero then overflow results
if (lHigh1 != 0 && lHigh2 != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
lResult = lLow1 * lLow2;
if (lResult < 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
if (lHigh1 != 0) {
SQLDebug.Check(lHigh2 == 0);
lPartialResult = lHigh1 * lLow2;
if (lPartialResult < 0 || lPartialResult > Int64.MaxValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
}
else if (lHigh2 != 0) {
SQLDebug.Check(lHigh1 == 0);
lPartialResult = lLow1 * lHigh2;
if (lPartialResult < 0 || lPartialResult > Int64.MaxValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
}
lResult += lPartialResult << 32;
if (lResult < 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
if (fNeg)
lResult = - lResult;
return new SqlInt64(lResult);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator /(SqlInt64 x, SqlInt64 y) {
if (x.IsNull || y.IsNull)
return Null;
if (y.m_value != 0) {
if ((x.m_value == Int64.MinValue) && (y.m_value == -1))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlInt64(x.m_value / y.m_value);
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator %(SqlInt64 x, SqlInt64 y) {
if (x.IsNull || y.IsNull)
return Null;
if (y.m_value != 0) {
if ((x.m_value == Int64.MinValue) && (y.m_value == -1))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlInt64(x.m_value % y.m_value);
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
// Bitwise operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator &(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? Null : new SqlInt64(x.m_value & y.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator |(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? Null : new SqlInt64(x.m_value | y.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlInt64 operator ^(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? Null : new SqlInt64(x.m_value ^ y.m_value);
}
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt64(SqlBoolean x) {
return x.IsNull ? Null : new SqlInt64((long)x.ByteValue);
}
// Implicit conversion from SqlByte to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt64(SqlByte x) {
return x.IsNull ? Null : new SqlInt64((long)(x.Value));
}
// Implicit conversion from SqlInt16 to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt64(SqlInt16 x) {
return x.IsNull ? Null : new SqlInt64((long)(x.Value));
}
// Implicit conversion from SqlInt32 to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlInt64(SqlInt32 x) {
return x.IsNull ? Null : new SqlInt64((long)(x.Value));
}
// Explicit conversions
// Explicit conversion from SqlSingle to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt64(SqlSingle x) {
if (x.IsNull)
return Null;
float value = x.Value;
if (value > (float)Int64.MaxValue || value < (float)Int64.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64((long)value);
}
// Explicit conversion from SqlDouble to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt64(SqlDouble x) {
if (x.IsNull)
return Null;
double value = x.Value;
if (value > (double)Int64.MaxValue || value < (double)Int64.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64((long)value);
}
// Explicit conversion from SqlMoney to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt64(SqlMoney x) {
return x.IsNull ? Null : new SqlInt64(x.ToInt64());
}
// Explicit conversion from SqlDecimal to SqlInt64
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt64(SqlDecimal x) {
if (x.IsNull)
return SqlInt64.Null;
SqlDecimal ssnumTemp = x;
long llRetVal;
// Throw away decimal portion
ssnumTemp.AdjustScale (-ssnumTemp.m_bScale, false);
// More than 8 bytes of data will always overflow
if (ssnumTemp.m_bLen > 2)
throw new OverflowException(SQLResource.ConversionOverflowMessage);
// If 8 bytes of data, see if fits in LONGLONG
if (ssnumTemp.m_bLen == 2) {
ulong dwl = SqlDecimal.DWL(ssnumTemp.m_data1, ssnumTemp.m_data2);
if (dwl > SqlDecimal.x_llMax && (ssnumTemp.IsPositive || dwl != 1 + SqlDecimal.x_llMax))
throw new OverflowException(SQLResource.ConversionOverflowMessage);
llRetVal = (long) dwl;
}
// 4 bytes of data always fits in a LONGLONG
else
llRetVal = (long) ssnumTemp.m_data1;
//negate result if ssnumTemp negative
if (!ssnumTemp.IsPositive)
llRetVal = -llRetVal;
return new SqlInt64(llRetVal);
}
// Explicit conversion from SqlString to SqlInt
// Throws FormatException or OverflowException if necessary.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlInt64(SqlString x) {
return x.IsNull ? Null : new SqlInt64(Int64.Parse(x.Value, (IFormatProvider)null));
}
// Utility functions
private static bool SameSignLong(long x, long y) {
return((x ^ y) & unchecked((long)0x8000000000000000L)) == 0;
}
// Overloading comparison operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator==(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value == y.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator!=(SqlInt64 x, SqlInt64 y) {
return ! (x == y);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator<(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value < y.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator>(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value > y.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator<=(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value <= y.m_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator>=(SqlInt64 x, SqlInt64 y) {
return(x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value >= y.m_value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ~
public static SqlInt64 OnesComplement(SqlInt64 x) {
return ~x;
}
// Alternative method for operator +
public static SqlInt64 Add(SqlInt64 x, SqlInt64 y) {
return x + y;
}
// Alternative method for operator -
public static SqlInt64 Subtract(SqlInt64 x, SqlInt64 y) {
return x - y;
}
// Alternative method for operator *
public static SqlInt64 Multiply(SqlInt64 x, SqlInt64 y) {
return x * y;
}
// Alternative method for operator /
public static SqlInt64 Divide(SqlInt64 x, SqlInt64 y) {
return x / y;
}
// Alternative method for operator %
public static SqlInt64 Mod(SqlInt64 x, SqlInt64 y) {
return x % y;
}
public static SqlInt64 Modulus(SqlInt64 x, SqlInt64 y) {
return x % y;
}
// Alternative method for operator &
public static SqlInt64 BitwiseAnd(SqlInt64 x, SqlInt64 y) {
return x & y;
}
// Alternative method for operator |
public static SqlInt64 BitwiseOr(SqlInt64 x, SqlInt64 y) {
return x | y;
}
// Alternative method for operator ^
public static SqlInt64 Xor(SqlInt64 x, SqlInt64 y) {
return x ^ y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlInt64 x, SqlInt64 y) {
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlInt64 x, SqlInt64 y) {
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlInt64 x, SqlInt64 y) {
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlInt64 x, SqlInt64 y) {
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlInt64 x, SqlInt64 y) {
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlInt64 x, SqlInt64 y) {
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean() {
return (SqlBoolean)this;
}
public SqlByte ToSqlByte() {
return (SqlByte)this;
}
public SqlDouble ToSqlDouble() {
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16() {
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32() {
return (SqlInt32)this;
}
public SqlMoney ToSqlMoney() {
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal() {
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle() {
return (SqlSingle)this;
}
public SqlString ToSqlString() {
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int CompareTo(Object value) {
if (value is SqlInt64) {
SqlInt64 i = (SqlInt64)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlInt64));
}
public int CompareTo(SqlInt64 value) {
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(Object value) {
if (!(value is SqlInt64)) {
return false;
}
SqlInt64 i = (SqlInt64)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode() {
return IsNull ? 0 : Value.GetHashCode();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
XmlSchema IXmlSerializable.GetSchema() { return null; }
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
void IXmlSerializable.ReadXml(XmlReader reader) {
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull)) {
// VSTFDevDiv# 479603 - SqlTypes read null value infinitely and never read the next value. Fix - Read the next value.
reader.ReadElementString();
m_fNotNull = false;
}
else {
m_value = XmlConvert.ToInt64(reader.ReadElementString());
m_fNotNull = true;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
void IXmlSerializable.WriteXml(XmlWriter writer) {
if (IsNull) {
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else {
writer.WriteString(XmlConvert.ToString(m_value));
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) {
return new XmlQualifiedName("long", XmlSchema.Namespace);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt64 Null = new SqlInt64(true);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt64 Zero = new SqlInt64(0);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt64 MinValue = new SqlInt64(Int64.MinValue);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly SqlInt64 MaxValue = new SqlInt64(Int64.MaxValue);
} // SqlInt64
} // namespace System.Data.SqlTypes
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// 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.Text;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace NUnit.TestUtilities
{
/// <summary>
/// A static helper to Verify that Setup/Teardown 'events' occur, and that they are in the correct order...
/// </summary>
public static class SimpleEventRecorder
{
/// <summary>
/// A helper class for matching test events.
/// </summary>
public class EventMatcher
{
private readonly List<string> _expectedEvents;
public EventMatcher(IEnumerable<string> expectedEvents)
{
_expectedEvents = new List<string>(expectedEvents);
}
/// <summary>
/// Matches a test event with one of the expected events.
/// </summary>
/// <param name="event">A string identifying the test event</param>
/// <param name="item">The index of the recorded test event</param>
/// <returns>true, if there are expected events left to match, otherwise false.</returns>
public bool MatchEvent(string @event, int item)
{
Assert.Contains(@event, _expectedEvents, "Item {0}", item);
_expectedEvents.Remove(@event);
return _expectedEvents.Count > 0;
}
}
/// <summary>
/// Helper class for recording expected events.
/// </summary>
public class ExpectedEventsRecorder
{
private readonly Queue<string> _actualEvents;
private readonly Queue<EventMatcher> _eventMatchers;
public ExpectedEventsRecorder(Queue<string> actualEvents, params string[] expectedEvents)
{
_actualEvents = actualEvents;
_eventMatchers = new Queue<EventMatcher>();
AndThen(expectedEvents);
}
/// <summary>
/// Adds the specified events as expected events.
/// </summary>
/// <param name="expectedEvents">An array of strings identifying the test events</param>
/// <returns>Returns the ExpectedEventsRecorder for adding new expected events.</returns>
public ExpectedEventsRecorder AndThen(params string[] expectedEvents)
{
_eventMatchers.Enqueue(new EventMatcher(expectedEvents));
return this;
}
/// <summary>
/// Verifies the recorded expected events with the actual recorded events.
/// </summary>
public void Verify()
{
EventMatcher eventMatcher = _eventMatchers.Dequeue();
int item = 0;
foreach (string actualEvent in _actualEvents)
{
if (eventMatcher == null)
{
Assert.Fail(
"More events than expected were recorded. Current event: {0} (Item {1})",
actualEvent,
item);
}
if (!eventMatcher.MatchEvent(actualEvent, item++))
{
if (_eventMatchers.Count > 0)
eventMatcher = _eventMatchers.Dequeue();
else
eventMatcher = null;
}
}
}
}
// Because it is static, this class can only be used by one fixture at a time.
// Currently, only one fixture uses it, if more use it, they should not be run in parallel.
// TODO: Create a utility that can be used by multiple fixtures
private static readonly Queue<string> _events = new Queue<string>();
/// <summary>
/// Registers an event.
/// </summary>
/// <param name="evnt">The event to register.</param>
public static void RegisterEvent(string evnt)
{
_events.Enqueue(evnt);
}
/// <summary>
/// Verifies the specified expected events occurred and that they occurred in the specified order.
/// </summary>
/// <param name="expectedEvents">The expected events.</param>
public static void Verify(params string[] expectedEvents)
{
foreach (string expected in expectedEvents)
{
int item = 0;
string actual = _events.Count > 0 ? _events.Dequeue() : null;
Assert.AreEqual( expected, actual, "Item {0}", item++ );
}
}
/// <summary>
/// Record the specified events as recorded expected events.
/// </summary>
/// <param name="expectedEvents">An array of strings identifying the test events</param>
/// <returns>An ExpectedEventsRecorder so that further expected events can be recorded and verified</returns>
public static ExpectedEventsRecorder ExpectEvents(params string[] expectedEvents)
{
return new ExpectedEventsRecorder(_events, expectedEvents);
}
/// <summary>
/// Clears any unverified events.
/// </summary>
public static void Clear()
{
_events.Clear();
}
}
}
namespace NUnit.TestData.SetupFixture
{
namespace Namespace1
{
#region SomeFixture
[TestFixture]
public class SomeFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Fixture.TearDown");
}
}
#endregion SomeFixture
[SetUpFixture]
public class NUnitNamespaceSetUpFixture1
{
[OneTimeSetUp]
public void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.OneTimeSetup");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.OneTimeTearDown");
}
}
}
namespace Namespace2
{
#region Fixtures
/// <summary>
/// Summary description for SetUpFixtureTests.
/// </summary>
[TestFixture]
public class SomeFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.TearDown");
}
}
[TestFixture]
public class AnotherFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.TearDown");
}
}
#endregion
[SetUpFixture]
public class NUnitNamespaceSetUpFixture2
{
[OneTimeSetUp]
public void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.OneTimeSetUp");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.OneTimeTearDown");
}
}
}
namespace Namespace3
{
namespace SubNamespace
{
#region SomeFixture
[TestFixture]
public class SomeFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Fixture.TearDown");
}
}
#endregion SomeTestFixture
[SetUpFixture]
public class NUnitNamespaceSetUpFixture
{
[OneTimeSetUp]
public void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.OneTimeSetUp");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.OneTimeTearDown");
}
}
}
#region SomeFixture
[TestFixture]
public class SomeFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Fixture.TearDown");
}
}
#endregion SomeTestFixture
[SetUpFixture]
public class NUnitNamespaceSetUpFixture
{
[OneTimeSetUp]
public static void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.OneTimeSetUp");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.OneTimeTearDown");
}
}
}
namespace Namespace4
{
#region SomeFixture
[TestFixture]
public class SomeFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Fixture.TearDown");
}
}
#endregion SomeTestFixture
[SetUpFixture]
public class NUnitNamespaceSetUpFixture
{
[OneTimeSetUp]
public void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeSetUp1");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeTearDown1");
}
}
[SetUpFixture]
public class NUnitNamespaceSetUpFixture2
{
[OneTimeSetUp]
public void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeSetUp2");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeTearDown2");
}
}
}
namespace Namespace5
{
#region SomeFixture
[TestFixture]
public class SomeFixture
{
[OneTimeSetUp]
public void FixtureSetup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Fixture.SetUp");
}
[SetUp]
public void Setup()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Test.SetUp");
}
[Test]
public void Test()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Test");
}
[TearDown]
public void TearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Test.TearDown");
}
[OneTimeTearDown]
public void FixtureTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Fixture.TearDown");
}
}
#endregion SomeTestFixture
[SetUpFixture]
public class NUnitNamespaceSetUpFixture
{
[OneTimeSetUp]
public static void DoNamespaceSetUp()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.OneTimeSetUp");
}
[OneTimeTearDown]
public static void DoNamespaceTearDown()
{
TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.OneTimeTearDown");
}
}
}
namespace Namespace6
{
[SetUpFixture]
public class InvalidSetUpFixture
{
[SetUp]
public void InvalidForOneTimeSetUp()
{
}
}
[TestFixture]
public class SomeFixture
{
[Test]
public void Test() { }
}
}
}
#region NoNamespaceSetupFixture
[SetUpFixture]
public class NoNamespaceSetupFixture
{
[OneTimeSetUp]
public void DoNamespaceSetUp()
{
NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("Assembly.OneTimeSetUp");
}
[OneTimeTearDown]
public void DoNamespaceTearDown()
{
NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("Assembly.OneTimeTearDown");
}
}
[TestFixture]
public class SomeFixture
{
[Test]
public void Test()
{
NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("NoNamespaceTest");
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Marten.Events;
using Marten.Events.Projections;
using Microsoft.Extensions.DependencyInjection;
namespace Marten.Testing.Events.Examples
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMarten(opts =>
{
opts.Connection("some connection");
// Direct Marten to update the Project aggregate
// inline as new events are captured
opts
.Projections
.SelfAggregate<Project>(ProjectionLifecycle.Inline);
});
}
}
public class NewProjectCommand
{
public string Name { get; set; }
public string[] Tasks { get; set; }
public string ProjectId { get; set; }
}
public class NewProjectHandler
{
private readonly IDocumentSession _session;
public NewProjectHandler(IDocumentSession session)
{
_session = session;
}
public Task Handle(NewProjectCommand command)
{
var timestamp = DateTimeOffset.UtcNow;
var started = new ProjectStarted {Name = command.Name, Timestamp = timestamp};
var tasks = command.Tasks
.Select(name => new TaskRecorded {Timestamp = timestamp, Title = name});
_session.Events.StartStream(command.ProjectId, started);
_session.Events.Append(command.ProjectId, tasks);
return _session.SaveChangesAsync();
}
}
public class Project
{
private readonly IList<ProjectTask> _tasks = new List<ProjectTask>();
public Project(ProjectStarted started)
{
Version = 1;
Name = started.Name;
StartedTime = started.Timestamp;
}
// This gets set by Marten
public Guid Id { get; set; }
public long Version { get; set; }
public DateTimeOffset StartedTime { get; private set; }
public DateTimeOffset? CompletedTime { get; private set; }
public string Name { get; private set; }
public ProjectTask[] Tasks
{
get
{
return _tasks.ToArray();
}
set
{
_tasks.Clear();
_tasks.AddRange(value);
}
}
public void Apply(TaskRecorded recorded, IEvent e)
{
Version = e.Version;
var task = new ProjectTask
{
Title = recorded.Title,
Number = _tasks.Max(x => x.Number) + 1,
Recorded = recorded.Timestamp
};
_tasks.Add(task);
}
public void Apply(TaskStarted started, IEvent e)
{
// Update the Project document based on the event version
Version = e.Version;
var task = _tasks.FirstOrDefault(x => x.Number == started.Number);
// Remember this isn't production code:)
if (task != null) task.Started = started.Timestamp;
}
public void Apply(TaskFinished finished, IEvent e)
{
Version = e.Version;
var task = _tasks.FirstOrDefault(x => x.Number == finished.Number);
// Remember this isn't production code:)
if (task != null) task.Finished = finished.Timestamp;
}
public void Apply(ProjectCompleted completed, IEvent e)
{
Version = e.Version;
CompletedTime = completed.Timestamp;
}
}
public class ProjectTask
{
public string Title { get; set; }
public DateTimeOffset? Started { get; set; }
public DateTimeOffset? Finished { get; set; }
public int Number { get; set; }
public DateTimeOffset Recorded { get; set; }
}
public class ProjectStarted
{
public string Name { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
public class TaskRecorded
{
public string Title { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
public class TaskStarted
{
public int Number { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
public class TaskFinished
{
public int Number { get; set; }
public DateTimeOffset? Timestamp { get; set; }
}
public class ProjectCompleted
{
public DateTimeOffset Timestamp { get; set; }
}
public class CreateTaskCommand
{
public string ProjectId { get; set; }
public string Title { get; set; }
}
public class CreateTaskHandler
{
private readonly IDocumentSession _session;
public CreateTaskHandler(IDocumentSession session)
{
_session = session;
}
public Task Handle(CreateTaskCommand command)
{
var recorded = new TaskRecorded
{
Timestamp = DateTimeOffset.UtcNow,
Title = command.Title
};
_session.Events.Append(command.ProjectId, recorded);
return _session.SaveChangesAsync();
}
}
public class CompleteTaskCommand
{
public string ProjectId { get; set; }
public int TaskNumber { get; set; }
// This is the version of the project data
// that was being edited in the user interface
public long ExpectedVersion { get; set; }
}
public class CompleteTaskHandler
{
private readonly IDocumentSession _session;
public CompleteTaskHandler(IDocumentSession session)
{
_session = session;
}
public Task Handle(CompleteTaskCommand command)
{
var @event = new TaskFinished
{
Number = command.TaskNumber,
Timestamp = DateTimeOffset.UtcNow
};
_session.Events.Append(
command.ProjectId,
// Using this overload will make Marten do
// an optimistic concurrency check against
// the existing version of the project event
// stream as it commits
command.ExpectedVersion,
@event);
return _session.SaveChangesAsync();
}
}
public class CompleteTaskHandler2
{
private readonly IDocumentSession _session;
public CompleteTaskHandler2(IDocumentSession session)
{
_session = session;
}
public Task Handle(CompleteTaskCommand command)
{
var @event = new TaskFinished
{
Number = command.TaskNumber,
Timestamp = DateTimeOffset.UtcNow
};
// If some other process magically zips
// in and updates this project event stream
// between the call to AppendOptimistic()
// and SaveChangesAsync(), Marten will detect
// that and reject the transaction
_session.Events.AppendOptimistic(
command.ProjectId,
@event);
return _session.SaveChangesAsync();
}
}
public class CompleteTaskHandler3
{
private readonly IDocumentSession _session;
public CompleteTaskHandler3(IDocumentSession session)
{
_session = session;
}
public Task Handle(CompleteTaskCommand command)
{
var @event = new TaskFinished
{
Number = command.TaskNumber,
Timestamp = DateTimeOffset.UtcNow
};
// This tries to acquire an exclusive
// lock on the stream identified by
// command.ProjectId in the database
// so that only one process at a time
// can update this event stream
_session.Events.AppendExclusive(
command.ProjectId,
@event);
return _session.SaveChangesAsync();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Game.Input;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Components;
using osu.Game.Screens.OnlinePlay.Match;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsRoomSubScreen : RoomSubScreen
{
public override string Title { get; }
public override string ShortTitle => "playlist";
[Resolved]
private IAPIProvider api { get; set; }
private readonly IBindable<bool> isIdle = new BindableBool();
private MatchLeaderboard leaderboard;
private SelectionPollingComponent selectionPollingComponent;
private FillFlowContainer progressSection;
public PlaylistsRoomSubScreen(Room room)
: base(room, false) // Editing is temporarily not allowed.
{
Title = room.RoomID.Value == null ? "New playlist" : room.Name.Value;
Activity.Value = new UserActivity.InLobby(room);
}
[BackgroundDependencyLoader(true)]
private void load([CanBeNull] IdleTracker idleTracker)
{
if (idleTracker != null)
isIdle.BindTo(idleTracker.IsIdle);
AddInternal(selectionPollingComponent = new SelectionPollingComponent(Room));
}
protected override void LoadComplete()
{
base.LoadComplete();
isIdle.BindValueChanged(_ => updatePollingRate(), true);
RoomId.BindValueChanged(id =>
{
if (id.NewValue != null)
{
// Set the first playlist item.
// This is scheduled since updating the room and playlist may happen in an arbitrary order (via Room.CopyFrom()).
Schedule(() => SelectedItem.Value = Room.Playlist.FirstOrDefault());
}
}, true);
Room.MaxAttempts.BindValueChanged(attempts => progressSection.Alpha = Room.MaxAttempts.Value != null ? 1 : 0, true);
}
protected override Drawable CreateMainContent() => new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Right = 5 },
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[] { new OverlinedPlaylistHeader(), },
new Drawable[]
{
new DrawableRoomPlaylistWithResults
{
RelativeSizeAxes = Axes.Both,
Items = { BindTarget = Room.Playlist },
SelectedItem = { BindTarget = SelectedItem },
RequestShowResults = item =>
{
Debug.Assert(RoomId.Value != null);
ParentScreen?.Push(new PlaylistsResultsScreen(null, RoomId.Value.Value, item, false));
}
}
},
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(),
}
}
},
null,
new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new[]
{
UserModsSection = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Alpha = 0,
Margin = new MarginPadding { Bottom = 10 },
Children = new Drawable[]
{
new OverlinedHeader("Extra mods"),
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(10, 0),
Children = new Drawable[]
{
new UserModSelectButton
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Width = 90,
Text = "Select",
Action = ShowUserModSelect,
},
new ModDisplay
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Current = UserMods,
Scale = new Vector2(0.8f),
},
}
}
}
},
},
new Drawable[]
{
progressSection = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Alpha = 0,
Margin = new MarginPadding { Bottom = 10 },
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new OverlinedHeader("Progress"),
new RoomLocalUserInfo(),
}
},
},
new Drawable[]
{
new OverlinedHeader("Leaderboard")
},
new Drawable[] { leaderboard = new MatchLeaderboard { RelativeSizeAxes = Axes.Both }, },
new Drawable[] { new OverlinedHeader("Chat"), },
new Drawable[] { new MatchChatDisplay(Room) { RelativeSizeAxes = Axes.Both } }
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.Relative, size: 0.4f, minSize: 120),
}
},
},
},
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 400),
new Dimension(),
new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 600),
}
};
protected override Drawable CreateFooter() => new PlaylistsRoomFooter
{
OnStart = StartPlay
};
protected override RoomSettingsOverlay CreateRoomSettingsOverlay(Room room) => new PlaylistsRoomSettingsOverlay(room)
{
EditPlaylist = () =>
{
if (this.IsCurrentScreen())
this.Push(new PlaylistsSongSelect(Room));
},
};
private void updatePollingRate()
{
selectionPollingComponent.TimeBetweenPolls.Value = isIdle.Value ? 30000 : 5000;
Logger.Log($"Polling adjusted (selection: {selectionPollingComponent.TimeBetweenPolls.Value})");
}
protected override Screen CreateGameplayScreen() => new PlayerLoader(() => new PlaylistsPlayer(Room, SelectedItem.Value)
{
Exited = () => leaderboard.RefreshScores()
});
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using Microsoft.PowerShell.Commands;
using Microsoft.Win32;
namespace System.Management.Automation.Help
{
/// <summary>
/// Updatable help system exception.
/// </summary>
[Serializable]
internal class UpdatableHelpSystemException : Exception
{
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="errorId">FullyQualifiedErrorId.</param>
/// <param name="message">Exception message.</param>
/// <param name="cat">Category.</param>
/// <param name="targetObject">Target object.</param>
/// <param name="innerException">Inner exception.</param>
internal UpdatableHelpSystemException(string errorId, string message, ErrorCategory cat, object targetObject, Exception innerException)
: base(message, innerException)
{
FullyQualifiedErrorId = errorId;
ErrorCategory = cat;
TargetObject = targetObject;
}
#if !CORECLR
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="serializationInfo">Serialization info.</param>
/// <param name="streamingContext">Streaming context.</param>
protected UpdatableHelpSystemException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
#endif
/// <summary>
/// Fully qualified error id.
/// </summary>
internal string FullyQualifiedErrorId { get; }
/// <summary>
/// Error category.
/// </summary>
internal ErrorCategory ErrorCategory { get; }
/// <summary>
/// Target object.
/// </summary>
internal object TargetObject { get; }
}
/// <summary>
/// Exception context.
/// </summary>
internal class UpdatableHelpExceptionContext
{
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="exception">Exception to wrap.</param>
internal UpdatableHelpExceptionContext(UpdatableHelpSystemException exception)
{
Exception = exception;
Modules = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Cultures = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// A list of modules.
/// </summary>
internal HashSet<string> Modules { get; set; }
/// <summary>
/// A list of UI cultures.
/// </summary>
internal HashSet<string> Cultures { get; set; }
/// <summary>
/// Gets the help system exception.
/// </summary>
internal UpdatableHelpSystemException Exception { get; }
/// <summary>
/// Creates an error record from this context.
/// </summary>
/// <param name="commandType">Command type.</param>
/// <returns>Error record.</returns>
internal ErrorRecord CreateErrorRecord(UpdatableHelpCommandType commandType)
{
Debug.Assert(Modules.Count != 0);
return new ErrorRecord(new Exception(GetExceptionMessage(commandType)), Exception.FullyQualifiedErrorId, Exception.ErrorCategory,
Exception.TargetObject);
}
/// <summary>
/// Gets the exception message.
/// </summary>
/// <param name="commandType"></param>
/// <returns></returns>
internal string GetExceptionMessage(UpdatableHelpCommandType commandType)
{
string message = string.Empty;
SortedSet<string> sortedModules = new SortedSet<string>(Modules, StringComparer.CurrentCultureIgnoreCase);
SortedSet<string> sortedCultures = new SortedSet<string>(Cultures, StringComparer.CurrentCultureIgnoreCase);
string modules = string.Join(", ", sortedModules);
string cultures = string.Join(", ", sortedCultures);
if (commandType == UpdatableHelpCommandType.UpdateHelpCommand)
{
if (Cultures.Count == 0)
{
message = StringUtil.Format(HelpDisplayStrings.FailedToUpdateHelpForModule, modules, Exception.Message);
}
else
{
message = StringUtil.Format(HelpDisplayStrings.FailedToUpdateHelpForModuleWithCulture, modules, cultures, Exception.Message);
}
}
else
{
if (Cultures.Count == 0)
{
message = StringUtil.Format(HelpDisplayStrings.FailedToSaveHelpForModule, modules, Exception.Message);
}
else
{
message = StringUtil.Format(HelpDisplayStrings.FailedToSaveHelpForModuleWithCulture, modules, cultures, Exception.Message);
}
}
return message;
}
}
/// <summary>
/// Enumeration showing Update or Save help.
/// </summary>
internal enum UpdatableHelpCommandType
{
UnknownCommand = 0,
UpdateHelpCommand = 1,
SaveHelpCommand = 2
}
/// <summary>
/// Progress event arguments.
/// </summary>
internal class UpdatableHelpProgressEventArgs : EventArgs
{
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="moduleName">Module name.</param>
/// <param name="status">Progress status.</param>
/// <param name="percent">Progress percentage.</param>
internal UpdatableHelpProgressEventArgs(string moduleName, string status, int percent)
{
Debug.Assert(!string.IsNullOrEmpty(status));
CommandType = UpdatableHelpCommandType.UnknownCommand;
ProgressStatus = status;
ProgressPercent = percent;
ModuleName = moduleName;
}
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="moduleName">Module name.</param>
/// <param name="type">Command type.</param>
/// <param name="status">Progress status.</param>
/// <param name="percent">Progress percentage.</param>
internal UpdatableHelpProgressEventArgs(string moduleName, UpdatableHelpCommandType type, string status, int percent)
{
Debug.Assert(!string.IsNullOrEmpty(status));
CommandType = type;
ProgressStatus = status;
ProgressPercent = percent;
ModuleName = moduleName;
}
/// <summary>
/// Progress status.
/// </summary>
internal string ProgressStatus { get; }
/// <summary>
/// Progress percentage.
/// </summary>
internal int ProgressPercent { get; }
/// <summary>
/// Module name.
/// </summary>
internal string ModuleName { get; }
/// <summary>
/// Command type.
/// </summary>
internal UpdatableHelpCommandType CommandType { get; set; }
}
/// <summary>
/// This class implements the Updatable Help System common operations.
/// </summary>
internal class UpdatableHelpSystem : IDisposable
{
private TimeSpan _defaultTimeout;
private Collection<UpdatableHelpProgressEventArgs> _progressEvents;
private bool _stopping;
private object _syncObject;
private UpdatableHelpCommandBase _cmdlet;
private CancellationTokenSource _cancelTokenSource;
internal WebClient WebClient { get; }
internal string CurrentModule { get; set; }
/// <summary>
/// Class constructor.
/// </summary>
internal UpdatableHelpSystem(UpdatableHelpCommandBase cmdlet, bool useDefaultCredentials)
{
WebClient = new WebClient();
_defaultTimeout = new TimeSpan(0, 0, 30);
_progressEvents = new Collection<UpdatableHelpProgressEventArgs>();
Errors = new Collection<Exception>();
_stopping = false;
_syncObject = new object();
_cmdlet = cmdlet;
_cancelTokenSource = new CancellationTokenSource();
WebClient.UseDefaultCredentials = useDefaultCredentials;
#if !CORECLR
WebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(HandleDownloadProgressChanged);
WebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(HandleDownloadFileCompleted);
#endif
}
/// <summary>
/// Disposes the help system.
/// </summary>
public void Dispose()
{
#if !CORECLR
_completionEvent.Dispose();
#endif
_cancelTokenSource.Dispose();
WebClient.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
/// Help system errors.
/// </summary>
internal Collection<Exception> Errors { get; }
/// <summary>
/// Gets the current UIculture (includes the fallback chain)
/// </summary>
/// <returns>A list of cultures.</returns>
internal IEnumerable<string> GetCurrentUICulture()
{
CultureInfo culture = CultureInfo.CurrentUICulture;
while (culture != null)
{
if (string.IsNullOrEmpty(culture.Name))
{
yield break;
}
yield return culture.Name;
culture = culture.Parent;
}
yield break;
}
#region Help Metadata Retrieval
/// <summary>
/// Gets an internal help URI.
/// </summary>
/// <param name="module">Internal module information.</param>
/// <param name="culture">Help content culture.</param>
/// <returns>Internal help uri representation.</returns>
internal UpdatableHelpUri GetHelpInfoUri(UpdatableHelpModuleInfo module, CultureInfo culture)
{
return new UpdatableHelpUri(module.ModuleName, module.ModuleGuid, culture, ResolveUri(module.HelpInfoUri, false));
}
/// <summary>
/// Gets the HelpInfo xml from the given URI.
/// </summary>
/// <param name="commandType">Command type.</param>
/// <param name="uri">HelpInfo URI.</param>
/// <param name="moduleName">Module name.</param>
/// <param name="moduleGuid">Module GUID.</param>
/// <param name="culture">Current UI culture.</param>
/// <returns>HelpInfo object.</returns>
internal UpdatableHelpInfo GetHelpInfo(UpdatableHelpCommandType commandType, string uri, string moduleName, Guid moduleGuid, string culture)
{
try
{
OnProgressChanged(this, new UpdatableHelpProgressEventArgs(CurrentModule, commandType, StringUtil.Format(
HelpDisplayStrings.UpdateProgressLocating), 0));
string xml;
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.UseDefaultCredentials = WebClient.UseDefaultCredentials;
using (HttpClient client = new HttpClient(handler))
{
client.Timeout = _defaultTimeout;
Task<string> responseBody = client.GetStringAsync(uri);
xml = responseBody.Result;
if (responseBody.Exception != null)
{
return null;
}
}
}
UpdatableHelpInfo helpInfo = CreateHelpInfo(xml, moduleName, moduleGuid,
currentCulture: culture, pathOverride: null, verbose: true,
shouldResolveUri: true, ignoreValidationException: false);
return helpInfo;
}
#if !CORECLR
catch (WebException)
{
return null;
}
#endif
finally
{
OnProgressChanged(this, new UpdatableHelpProgressEventArgs(CurrentModule, commandType, StringUtil.Format(
HelpDisplayStrings.UpdateProgressLocating), 100));
}
}
/// <summary>
/// Sends a standard HTTP request to get the resolved URI (potential FwLinks)
/// </summary>
/// <param name="baseUri">Base URI.</param>
/// <param name="verbose"></param>
/// <returns>Resolved URI.</returns>
private string ResolveUri(string baseUri, bool verbose)
{
Debug.Assert(!string.IsNullOrEmpty(baseUri));
// Directory.Exists checks if baseUri is a network drive or
// a local directory. If baseUri is local, we don't need to resolve it.
//
// The / check works because all of our fwlinks must resolve
// to a remote virtual directory. I think HTTP always appends /
// in reference to a directory.
// Like if you send a request to www.technet.com/powershell you will get
// a 301/203 response with the response URI set to www.technet.com/powershell/
//
if (Directory.Exists(baseUri) || baseUri.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
if (verbose)
{
_cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, baseUri));
}
return baseUri;
}
if (verbose)
{
_cmdlet.WriteVerbose(StringUtil.Format(HelpDisplayStrings.UpdateHelpResolveUriVerbose, baseUri));
}
string uri = baseUri;
try
{
// We only allow 10 redirections
for (int i = 0; i < 10; i++)
{
if (_stopping)
{
return uri;
}
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.AllowAutoRedirect = false;
handler.UseDefaultCredentials = WebClient.UseDefaultCredentials;
using (HttpClient client = new HttpClient(handler))
{
client.Timeout = new TimeSpan(0, 0, 30); // Set 30 second timeout
Task<HttpResponseMessage> responseMessage = client.GetAsync(uri);
using (HttpResponseMessage response = responseMessage.Result)
{
if (response.StatusCode == HttpStatusCode.Found ||
response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.MovedPermanently)
{
Uri responseUri = response.Headers.Location;
if (responseUri.IsAbsoluteUri)
{
uri = responseUri.ToString();
}
else
{
Uri originalAbs = new Uri(uri);
uri = uri.Replace(originalAbs.AbsolutePath, responseUri.ToString());
}
uri = uri.Trim();
if (verbose)
{
_cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, uri));
}
if (uri.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
return uri;
}
}
else if (response.StatusCode == HttpStatusCode.OK)
{
if (uri.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
return uri;
}
else
{
throw new UpdatableHelpSystemException("InvalidHelpInfoUri", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUri, uri),
ErrorCategory.InvalidOperation, null, null);
}
}
}
}
}
}
}
catch (UriFormatException e)
{
throw new UpdatableHelpSystemException("InvalidUriFormat", e.Message, ErrorCategory.InvalidData, null, e);
}
throw new UpdatableHelpSystemException("TooManyRedirections", StringUtil.Format(HelpDisplayStrings.TooManyRedirections),
ErrorCategory.InvalidOperation, null, null);
}
/// <summary>
/// HelpInfo.xml schema.
/// </summary>
private const string HelpInfoXmlSchema = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified""
targetNamespace=""http://schemas.microsoft.com/powershell/help/2010/05"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""HelpInfo"">
<xs:complexType>
<xs:sequence>
<xs:element name=""HelpContentURI"" type=""xs:anyURI"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""SupportedUICultures"" minOccurs=""1"" maxOccurs=""1"">
<xs:complexType>
<xs:sequence>
<xs:element name=""UICulture"" minOccurs=""1"" maxOccurs=""unbounded"">
<xs:complexType>
<xs:sequence>
<xs:element name=""UICultureName"" type=""xs:language"" minOccurs=""1"" maxOccurs=""1"" />
<xs:element name=""UICultureVersion"" type=""xs:string"" minOccurs=""1"" maxOccurs=""1"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
private const string HelpInfoXmlNamespace = "http://schemas.microsoft.com/powershell/help/2010/05";
private const string HelpInfoXmlValidationFailure = "HelpInfoXmlValidationFailure";
/// <summary>
/// Creates a HelpInfo object.
/// </summary>
/// <param name="xml">XML text.</param>
/// <param name="moduleName">Module name.</param>
/// <param name="moduleGuid">Module GUID.</param>
/// <param name="currentCulture">Current UI cultures.</param>
/// <param name="pathOverride">Overrides the path contained within HelpInfo.xml.</param>
/// <param name="verbose"></param>
/// <param name="shouldResolveUri">
/// Resolve the uri retrieved from the <paramref name="xml"/> content. The uri is resolved
/// to handle redirections if any.
/// </param>
/// <param name="ignoreValidationException">Ignore the xsd validation exception and return null in such case.</param>
/// <returns>HelpInfo object.</returns>
internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid moduleGuid,
string currentCulture, string pathOverride, bool verbose, bool shouldResolveUri, bool ignoreValidationException)
{
XmlDocument document = null;
try
{
document = CreateValidXmlDocument(xml, HelpInfoXmlNamespace, HelpInfoXmlSchema,
new ValidationEventHandler(HelpInfoValidationHandler),
true);
}
catch (UpdatableHelpSystemException e)
{
if (ignoreValidationException && HelpInfoXmlValidationFailure.Equals(e.FullyQualifiedErrorId, StringComparison.Ordinal))
{
return null;
}
throw;
}
catch (XmlException e)
{
if (ignoreValidationException) { return null; }
throw new UpdatableHelpSystemException(HelpInfoXmlValidationFailure,
e.Message, ErrorCategory.InvalidData, null, e);
}
string uri = pathOverride;
string unresolvedUri = document["HelpInfo"]["HelpContentURI"].InnerText;
if (string.IsNullOrEmpty(pathOverride))
{
if (shouldResolveUri)
{
uri = ResolveUri(unresolvedUri, verbose);
}
else
{
uri = unresolvedUri;
}
}
XmlNodeList cultures = document["HelpInfo"]["SupportedUICultures"].ChildNodes;
CultureSpecificUpdatableHelp[] updatableHelpItem = new CultureSpecificUpdatableHelp[cultures.Count];
for (int i = 0; i < cultures.Count; i++)
{
updatableHelpItem[i] = new CultureSpecificUpdatableHelp(
new CultureInfo(cultures[i]["UICultureName"].InnerText),
new Version(cultures[i]["UICultureVersion"].InnerText));
}
UpdatableHelpInfo helpInfo = new UpdatableHelpInfo(unresolvedUri, updatableHelpItem);
if (!string.IsNullOrEmpty(currentCulture))
{
WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
IEnumerable<WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { currentCulture }, wildcardOptions);
for (int i = 0; i < updatableHelpItem.Length; i++)
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(updatableHelpItem[i].Culture.Name, patternList, true))
{
helpInfo.HelpContentUriCollection.Add(new UpdatableHelpUri(moduleName, moduleGuid, updatableHelpItem[i].Culture, uri));
}
}
}
if (!string.IsNullOrEmpty(currentCulture) && helpInfo.HelpContentUriCollection.Count == 0)
{
// throw exception
throw new UpdatableHelpSystemException("HelpCultureNotSupported",
StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported,
currentCulture, helpInfo.GetSupportedCultures()), ErrorCategory.InvalidOperation, null, null);
}
return helpInfo;
}
/// <summary>
/// Creates a valid xml document.
/// </summary>
/// <param name="xml">Input xml.</param>
/// <param name="ns">Schema namespace.</param>
/// <param name="schema">Xml schema.</param>
/// <param name="handler">Validation event handler.</param>
/// <param name="helpInfo">HelpInfo or HelpContent?</param>
private XmlDocument CreateValidXmlDocument(string xml, string ns, string schema, ValidationEventHandler handler,
bool helpInfo)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(ns, new XmlTextReader(new StringReader(schema)));
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
XmlDocument document = new XmlDocument();
try
{
document.Load(reader);
document.Validate(handler);
}
catch (XmlSchemaValidationException e)
{
if (helpInfo)
{
throw new UpdatableHelpSystemException(HelpInfoXmlValidationFailure,
StringUtil.Format(HelpDisplayStrings.HelpInfoXmlValidationFailure, e.Message),
ErrorCategory.InvalidData, null, e);
}
else
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, e.Message),
ErrorCategory.InvalidData, null, e);
}
}
return document;
}
/// <summary>
/// Handles HelpInfo XML validation events.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="arg">Event arguments.</param>
private void HelpInfoValidationHandler(object sender, ValidationEventArgs arg)
{
switch (arg.Severity)
{
case XmlSeverityType.Error:
{
throw new UpdatableHelpSystemException(HelpInfoXmlValidationFailure,
StringUtil.Format(HelpDisplayStrings.HelpInfoXmlValidationFailure),
ErrorCategory.InvalidData, null, arg.Exception);
}
case XmlSeverityType.Warning:
break;
}
}
/// <summary>
/// Handles Help content MAML validation events.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="arg">Event arguments.</param>
private void HelpContentValidationHandler(object sender, ValidationEventArgs arg)
{
switch (arg.Severity)
{
case XmlSeverityType.Error:
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure),
ErrorCategory.InvalidData, null, arg.Exception);
}
case XmlSeverityType.Warning:
break;
}
}
#endregion
#region Help Content Retrieval
/// <summary>
/// Cancels all asynchronous download operations.
/// </summary>
internal void CancelDownload()
{
_cancelTokenSource.Cancel();
_stopping = true;
}
/// <summary>
/// Downloads and installs help content.
/// </summary>
/// <param name="commandType">Command type.</param>
/// <param name="context">Execution context.</param>
/// <param name="destPaths">Destination paths.</param>
/// <param name="fileName">File names.</param>
/// <param name="culture">Culture to update.</param>
/// <param name="helpContentUri">Help content uri.</param>
/// <param name="xsdPath">Path of the maml XSDs.</param>
/// <param name="installed">Files installed.</param>
/// <returns>True if the operation succeeded, false if not.</returns>
internal bool DownloadAndInstallHelpContent(UpdatableHelpCommandType commandType, ExecutionContext context, Collection<string> destPaths,
string fileName, CultureInfo culture, string helpContentUri, string xsdPath, out Collection<string> installed)
{
if (_stopping)
{
installed = new Collection<string>();
return false;
}
string cache = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
if (!DownloadHelpContent(commandType, cache, helpContentUri, fileName, culture.Name))
{
installed = new Collection<string>();
return false;
}
InstallHelpContent(commandType, context, cache, destPaths, fileName, cache, culture, xsdPath, out installed);
return true;
}
/// <summary>
/// Downloads the help content.
/// </summary>
/// <param name="commandType">Command type.</param>
/// <param name="path">Destination path.</param>
/// <param name="helpContentUri">Help content uri.</param>
/// <param name="fileName">Combined file name.</param>
/// <param name="culture">Culture name.</param>
/// <returns>True if the operation succeeded, false if not.</returns>
internal bool DownloadHelpContent(UpdatableHelpCommandType commandType, string path, string helpContentUri, string fileName, string culture)
{
if (_stopping)
{
return false;
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
OnProgressChanged(this, new UpdatableHelpProgressEventArgs(CurrentModule, commandType, StringUtil.Format(
HelpDisplayStrings.UpdateProgressConnecting), 0));
string uri = helpContentUri + fileName;
return DownloadHelpContentHttpClient(uri, Path.Combine(path, fileName), commandType);
}
/// <summary>
/// Downloads the help content and saves it to a directory.
/// </summary>
/// <param name="uri"></param>
/// <param name="fileName"></param>
/// <param name="commandType"></param>
/// <returns></returns>
private bool DownloadHelpContentHttpClient(string uri, string fileName, UpdatableHelpCommandType commandType)
{
// TODO: Was it intentional for them to remove IDisposable from Task?
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.AllowAutoRedirect = false;
handler.UseDefaultCredentials = WebClient.UseDefaultCredentials;
using (HttpClient client = new HttpClient(handler))
{
client.Timeout = _defaultTimeout;
Task<HttpResponseMessage> responseMsg = client.GetAsync(new Uri(uri), _cancelTokenSource.Token);
// TODO: Should I use a continuation to write the stream to a file?
responseMsg.Wait();
if (_stopping)
{
return true;
}
if (!responseMsg.IsCanceled)
{
if (responseMsg.Exception != null)
{
Errors.Add(new UpdatableHelpSystemException("HelpContentNotFound",
StringUtil.Format(HelpDisplayStrings.HelpContentNotFound),
ErrorCategory.ResourceUnavailable, null, responseMsg.Exception));
}
else
{
lock (_syncObject)
{
_progressEvents.Add(new UpdatableHelpProgressEventArgs(CurrentModule, StringUtil.Format(
HelpDisplayStrings.UpdateProgressDownloading), 100));
}
// Write the stream to the specified file to achieve functional parity with WebClient.DownloadFileAsync().
HttpResponseMessage response = responseMsg.Result;
if (response.IsSuccessStatusCode)
{
WriteResponseToFile(response, fileName);
}
else
{
Errors.Add(new UpdatableHelpSystemException("HelpContentNotFound",
StringUtil.Format(HelpDisplayStrings.HelpContentNotFound),
ErrorCategory.ResourceUnavailable, null, responseMsg.Exception));
}
}
}
SendProgressEvents(commandType);
}
}
return (Errors.Count == 0);
}
/// <summary>
/// Writes the content of an HTTP response to the specified file.
/// </summary>
/// <param name="response"></param>
/// <param name="fileName"></param>
private void WriteResponseToFile(HttpResponseMessage response, string fileName)
{
// TODO: Settings to use? FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite
using (FileStream downloadedFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
Task copyStreamOp = response.Content.CopyToAsync(downloadedFileStream);
copyStreamOp.Wait();
if (copyStreamOp.Exception != null)
{
Errors.Add(copyStreamOp.Exception);
}
}
}
private void SendProgressEvents(UpdatableHelpCommandType commandType)
{
// Send progress events
lock (_syncObject)
{
if (_progressEvents.Count > 0)
{
foreach (UpdatableHelpProgressEventArgs evt in _progressEvents)
{
evt.CommandType = commandType;
OnProgressChanged(this, evt);
}
_progressEvents.Clear();
}
}
}
/// <summary>
/// Installs HelpInfo.xml.
/// </summary>
/// <param name="moduleName"></param>
/// <param name="moduleGuid"></param>
/// <param name="culture">Culture updated.</param>
/// <param name="version">Version updated.</param>
/// <param name="contentUri">Help content uri.</param>
/// <param name="destPath">Destination name.</param>
/// <param name="fileName">Combined file name.</param>
/// <param name="force">Forces the file to copy.</param>
internal void GenerateHelpInfo(string moduleName, Guid moduleGuid, string contentUri, string culture, Version version, string destPath, string fileName, bool force)
{
Debug.Assert(Directory.Exists(destPath));
if (_stopping)
{
return;
}
string destHelpInfo = Path.Combine(destPath, fileName);
if (force)
{
RemoveReadOnly(destHelpInfo);
}
UpdatableHelpInfo oldHelpInfo = null;
string xml = UpdatableHelpSystem.LoadStringFromPath(_cmdlet, destHelpInfo, null);
if (xml != null)
{
// constructing the helpinfo object from previous update help log xml..
// no need to resolve the uri's in this case.
oldHelpInfo = CreateHelpInfo(xml, moduleName, moduleGuid, currentCulture: null, pathOverride: null,
verbose: false, shouldResolveUri: false, ignoreValidationException: force);
}
using (FileStream file = new FileStream(destHelpInfo, FileMode.Create, FileAccess.Write))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true; // Default indentation is two spaces
using (XmlWriter writer = XmlWriter.Create(file, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("HelpInfo", "http://schemas.microsoft.com/powershell/help/2010/05");
writer.WriteStartElement("HelpContentURI");
writer.WriteValue(contentUri);
writer.WriteEndElement();
writer.WriteStartElement("SupportedUICultures");
bool found = false;
if (oldHelpInfo != null)
{
foreach (CultureSpecificUpdatableHelp oldInfo in oldHelpInfo.UpdatableHelpItems)
{
if (oldInfo.Culture.Name.Equals(culture, StringComparison.OrdinalIgnoreCase))
{
if (oldInfo.Version.Equals(version))
{
writer.WriteStartElement("UICulture");
writer.WriteStartElement("UICultureName");
writer.WriteValue(oldInfo.Culture.Name);
writer.WriteEndElement();
writer.WriteStartElement("UICultureVersion");
writer.WriteValue(oldInfo.Version.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
else
{
writer.WriteStartElement("UICulture");
writer.WriteStartElement("UICultureName");
writer.WriteValue(culture);
writer.WriteEndElement();
writer.WriteStartElement("UICultureVersion");
writer.WriteValue(version.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
found = true;
}
else
{
writer.WriteStartElement("UICulture");
writer.WriteStartElement("UICultureName");
writer.WriteValue(oldInfo.Culture.Name);
writer.WriteEndElement();
writer.WriteStartElement("UICultureVersion");
writer.WriteValue(oldInfo.Version.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
if (!found)
{
writer.WriteStartElement("UICulture");
writer.WriteStartElement("UICultureName");
writer.WriteValue(culture);
writer.WriteEndElement();
writer.WriteStartElement("UICultureVersion");
writer.WriteValue(version.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
/// <summary>
/// Removes the read only attribute.
/// </summary>
/// <param name="path"></param>
private void RemoveReadOnly(string path)
{
if (File.Exists(path))
{
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
attributes = (attributes & ~FileAttributes.ReadOnly);
File.SetAttributes(path, attributes);
}
}
}
/// <summary>
/// Installs (unzips) the help content.
/// </summary>
/// <param name="commandType">Command type.</param>
/// <param name="context">Execution context.</param>
/// <param name="sourcePath">Source directory.</param>
/// <param name="destPaths">Destination paths.</param>
/// <param name="fileName">Help content file name.</param>
/// <param name="tempPath">Temporary path.</param>
/// <param name="culture">Current culture.</param>
/// <param name="xsdPath">Path of the maml XSDs.</param>
/// <param name="installed">Files installed.</param>
/// <remarks>
/// Directory pointed by <paramref name="tempPath"/> (if any) will be deleted.
/// </remarks>
internal void InstallHelpContent(UpdatableHelpCommandType commandType, ExecutionContext context, string sourcePath,
Collection<string> destPaths, string fileName, string tempPath, CultureInfo culture, string xsdPath,
out Collection<string> installed)
{
installed = new Collection<string>();
if (_stopping)
{
installed = new Collection<string>();
return;
}
// These paths must exist
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
Debug.Assert(destPaths.Count > 0);
try
{
OnProgressChanged(this, new UpdatableHelpProgressEventArgs(CurrentModule, commandType, StringUtil.Format(
HelpDisplayStrings.UpdateProgressInstalling), 0));
string combinedSourcePath = GetFilePath(Path.Combine(sourcePath, fileName));
if (string.IsNullOrEmpty(combinedSourcePath))
{
throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound),
ErrorCategory.ResourceUnavailable, null, null);
}
string combinedTempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(fileName));
if (Directory.Exists(combinedTempPath))
{
Directory.Delete(combinedTempPath, true);
}
bool needToCopy = true;
UnzipHelpContent(context, combinedSourcePath, combinedTempPath, out needToCopy);
if (needToCopy)
{
ValidateAndCopyHelpContent(combinedTempPath, destPaths, culture.Name, xsdPath, out installed);
}
}
finally
{
OnProgressChanged(this, new UpdatableHelpProgressEventArgs(CurrentModule, commandType, StringUtil.Format(
HelpDisplayStrings.UpdateProgressInstalling), 100));
try
{
if (Directory.Exists(tempPath))
{
Directory.Delete(tempPath);
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
catch (ArgumentException) { }
}
}
#if UNIX
private bool ExpandArchive(string source, string destination)
{
bool sucessfulDecompression = false;
try
{
using (ZipArchive zipArchive = ZipFile.Open(source, ZipArchiveMode.Read))
{
zipArchive.ExtractToDirectory(destination);
sucessfulDecompression = true;
}
}
catch (ArgumentException) { }
catch (InvalidDataException) { }
catch (NotSupportedException) { }
catch (FileNotFoundException) { }
catch (IOException) { }
catch (SecurityException) { }
catch (UnauthorizedAccessException) { }
catch (ObjectDisposedException) { }
return sucessfulDecompression;
}
#endif
/// <summary>
/// Unzips to help content to a given location.
/// </summary>
/// <param name="context">Execution context.</param>
/// <param name="srcPath">Source path.</param>
/// <param name="destPath">Destination path.</param>
/// <param name="needToCopy">Is set to false if we find a single file placeholder.txt in cab. This means we no longer need to install help files.</param>
private void UnzipHelpContent(ExecutionContext context, string srcPath, string destPath, out bool needToCopy)
{
needToCopy = true;
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(destPath);
}
string sourceDirectory = Path.GetDirectoryName(srcPath);
bool sucessfulDecompression = false;
#if UNIX
sucessfulDecompression = ExpandArchive(Path.Combine(sourceDirectory, Path.GetFileName(srcPath)), destPath);
#else
// Cabinet API doesn't handle the trailing back slash
if (!sourceDirectory.EndsWith("\\", StringComparison.Ordinal))
{
sourceDirectory += "\\";
}
if (!destPath.EndsWith("\\", StringComparison.Ordinal))
{
destPath += "\\";
}
sucessfulDecompression = CabinetExtractorFactory.GetCabinetExtractor().Extract(Path.GetFileName(srcPath), sourceDirectory, destPath);
#endif
if (!sucessfulDecompression)
{
throw new UpdatableHelpSystemException("UnableToExtract", StringUtil.Format(HelpDisplayStrings.UnzipFailure),
ErrorCategory.InvalidOperation, null, null);
}
string[] files = Directory.GetFiles(destPath);
if (files.Length == 1)
{
// If there is a single file
string file = Path.GetFileName(files[0]);
if (!string.IsNullOrEmpty(file) && file.Equals("placeholder.txt", StringComparison.OrdinalIgnoreCase))
{
// And that single file is named "placeholder.txt"
var fileInfo = new FileInfo(files[0]);
if (fileInfo.Length == 0)
{
// And if that single file has length 0, then we delete that file and no longer install help
needToCopy = false;
try
{
File.Delete(files[0]);
string directory = Path.GetDirectoryName(files[0]);
if (!string.IsNullOrEmpty(directory))
{
Directory.Delete(directory);
}
}
catch (FileNotFoundException)
{ }
catch (DirectoryNotFoundException)
{ }
catch (UnauthorizedAccessException)
{ }
catch (System.Security.SecurityException)
{ }
catch (ArgumentNullException)
{ }
catch (ArgumentException)
{ }
catch (PathTooLongException)
{ }
catch (NotSupportedException)
{ }
catch (IOException)
{ }
}
}
}
else
{
foreach (string file in files)
{
if (File.Exists(file))
{
FileInfo fInfo = new FileInfo(file);
if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Clear the read-only attribute
fInfo.Attributes &= ~(FileAttributes.ReadOnly);
}
}
}
}
}
/// <summary>
/// Validates all XML files within a given path.
/// </summary>
/// <param name="sourcePath">Path containing files to validate.</param>
/// <param name="destPaths">Destination paths.</param>
/// <param name="culture">Culture name.</param>
/// <param name="xsdPath">Path of the maml XSDs.</param>
/// <param name="installed">Installed files.</param>
private void ValidateAndCopyHelpContent(string sourcePath, Collection<string> destPaths, string culture, string xsdPath,
out Collection<string> installed)
{
installed = new Collection<string>();
string xsd = LoadStringFromPath(_cmdlet, xsdPath, null);
// We only accept txt files and xml files
foreach (string file in Directory.GetFiles(sourcePath))
{
if (!string.Equals(Path.GetExtension(file), ".xml", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(Path.GetExtension(file), ".txt", StringComparison.OrdinalIgnoreCase))
{
throw new UpdatableHelpSystemException("HelpContentContainsInvalidFiles",
StringUtil.Format(HelpDisplayStrings.HelpContentContainsInvalidFiles), ErrorCategory.InvalidData,
null, null);
}
}
// xml validation
foreach (string file in Directory.GetFiles(sourcePath))
{
if (string.Equals(Path.GetExtension(file), ".xml", StringComparison.OrdinalIgnoreCase))
{
if (xsd == null)
{
throw new ItemNotFoundException(StringUtil.Format(HelpDisplayStrings.HelpContentXsdNotFound, xsdPath));
}
else
{
string xml = LoadStringFromPath(_cmdlet, file, null);
XmlReader documentReader = XmlReader.Create(new StringReader(xml));
XmlDocument contentDocument = new XmlDocument();
contentDocument.Load(documentReader);
if (contentDocument.ChildNodes.Count != 1 && contentDocument.ChildNodes.Count != 2)
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, HelpDisplayStrings.RootElementMustBeHelpItems),
ErrorCategory.InvalidData, null, null);
}
XmlNode helpItemsNode = null;
if (contentDocument.DocumentElement != null &&
contentDocument.DocumentElement.LocalName.Equals("providerHelp", StringComparison.OrdinalIgnoreCase))
{
helpItemsNode = contentDocument;
}
else
{
if (contentDocument.ChildNodes.Count == 1)
{
if (!contentDocument.ChildNodes[0].LocalName.Equals("helpItems", StringComparison.OrdinalIgnoreCase))
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, HelpDisplayStrings.RootElementMustBeHelpItems),
ErrorCategory.InvalidData, null, null);
}
else
{
helpItemsNode = contentDocument.ChildNodes[0];
}
}
else if (contentDocument.ChildNodes.Count == 2)
{
if (!contentDocument.ChildNodes[1].LocalName.Equals("helpItems", StringComparison.OrdinalIgnoreCase))
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, HelpDisplayStrings.RootElementMustBeHelpItems),
ErrorCategory.InvalidData, null, null);
}
else
{
helpItemsNode = contentDocument.ChildNodes[1];
}
}
}
Debug.Assert(helpItemsNode != null, "helpItemsNode must not be null");
string targetNamespace = "http://schemas.microsoft.com/maml/2004/10";
foreach (XmlNode node in helpItemsNode.ChildNodes)
{
if (node.NodeType == XmlNodeType.Element)
{
if (!node.LocalName.Equals("providerHelp", StringComparison.OrdinalIgnoreCase))
{
if (node.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase))
{
if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/2004/10", StringComparison.OrdinalIgnoreCase))
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure,
StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null);
}
else
{
continue;
}
}
if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/command/2004/10", StringComparison.OrdinalIgnoreCase) &&
!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/dscResource/2004/10", StringComparison.OrdinalIgnoreCase))
{
throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure",
StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure,
StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null);
}
}
CreateValidXmlDocument(node.OuterXml, targetNamespace, xsd,
new ValidationEventHandler(HelpContentValidationHandler),
false);
}
}
}
}
else if (string.Equals(Path.GetExtension(file), ".txt", StringComparison.OrdinalIgnoreCase))
{
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
if (fileStream.Length > 2)
{
byte[] firstTwoBytes = new byte[2];
fileStream.Read(firstTwoBytes, 0, 2);
// Check for Mark Zbikowski's magic initials
if (firstTwoBytes[0] == 'M' && firstTwoBytes[1] == 'Z')
{
throw new UpdatableHelpSystemException("HelpContentContainsInvalidFiles",
StringUtil.Format(HelpDisplayStrings.HelpContentContainsInvalidFiles), ErrorCategory.InvalidData,
null, null);
}
}
}
foreach (string path in destPaths)
{
Debug.Assert(Directory.Exists(path));
string combinedPath = Path.Combine(path, culture);
if (!Directory.Exists(combinedPath))
{
Directory.CreateDirectory(combinedPath);
}
string destPath = Path.Combine(combinedPath, Path.GetFileName(file));
// Make the destpath writeable if force is used
FileAttributes? originalFileAttributes = null;
try
{
if (File.Exists(destPath) && (_cmdlet.Force))
{
FileInfo fInfo = new FileInfo(destPath);
if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// remember to reset the read-only attribute later
originalFileAttributes = fInfo.Attributes;
// Clear the read-only attribute
fInfo.Attributes &= ~(FileAttributes.ReadOnly);
}
}
File.Copy(file, destPath, true);
}
finally
{
if (originalFileAttributes.HasValue)
{
File.SetAttributes(destPath, originalFileAttributes.Value);
}
}
installed.Add(destPath);
}
}
}
/// <summary>
/// Loads string from the given path.
/// </summary>
/// <param name="cmdlet">Cmdlet instance.</param>
/// <param name="path">Path to load.</param>
/// <param name="credential">Credential.</param>
/// <returns>String loaded.</returns>
internal static string LoadStringFromPath(PSCmdlet cmdlet, string path, PSCredential credential)
{
Debug.Assert(path != null);
if (credential != null)
{
// New PSDrive
using (UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(cmdlet, Path.GetDirectoryName(path), credential))
{
string tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
if (!cmdlet.InvokeProvider.Item.Exists(Path.Combine(drive.DriveName, Path.GetFileName(path))))
{
return null;
}
cmdlet.InvokeProvider.Item.Copy(new string[1] { Path.Combine(drive.DriveName, Path.GetFileName(path)) }, tempPath,
false, CopyContainers.CopyTargetContainer, true, true);
path = tempPath;
}
}
string filePath = GetFilePath(path);
if (!string.IsNullOrEmpty(filePath))
{
using (FileStream currentHelpInfoFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
StreamReader reader = new StreamReader(currentHelpInfoFile);
return reader.ReadToEnd();
}
}
return null;
}
/// <summary>
/// Validate the given path. If it exists, return the full path to the file.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
internal static string GetFilePath(string path)
{
FileInfo item = new FileInfo(path);
// We use 'FileInfo.Attributes' (not 'FileInfo.Exist')
// because we want to get exceptions
// like UnauthorizedAccessException or IOException.
if ((int)item.Attributes != -1)
{
return path;
}
#if UNIX
// On Linux, file paths are case sensitive.
// The user does not have control over the files (HelpInfo.xml, .zip, and cab) that are generated by the Publishing team.
// The logic below is to support updating help content via sourcepath parameter for case insensitive files.
var dirInfo = item.Directory;
string fileName = item.Name;
// Prerequisite: The directory in the given path must exist and it is case sensitive.
if (dirInfo.Exists)
{
// Get the list of files in the directory.
FileInfo[] fileList = dirInfo.GetFiles(searchPattern: fileName, new System.IO.EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive });
if (fileList.Length > 0)
{
return fileList[0].FullName;
}
}
#endif
return null;
}
/// <summary>
/// Gets the default source path from GP.
/// </summary>
/// <returns></returns>
internal string GetDefaultSourcePath()
{
var updatableHelpSetting = Utils.GetPolicySetting<UpdatableHelp>(Utils.SystemWideOnlyConfig);
string defaultSourcePath = updatableHelpSetting?.DefaultSourcePath;
return string.IsNullOrEmpty(defaultSourcePath) ? null : defaultSourcePath;
}
/// <summary>
/// Sets the DisablePromptToUpdatableHelp regkey.
/// </summary>
internal static void SetDisablePromptToUpdateHelp()
{
try
{
PowerShellConfig.Instance.SetDisablePromptToUpdateHelp(true);
}
catch (UnauthorizedAccessException)
{
// Ignore AccessDenied related exceptions
}
catch (SecurityException)
{
// Ignore AccessDenied related exceptions
}
}
/// <summary>
/// Checks if it is necessary to prompt to update help.
/// </summary>
/// <returns></returns>
internal static bool ShouldPromptToUpdateHelp()
{
#if UNIX
// TODO: This workaround needs to be removed once updatable help
// works on Linux.
return false;
#else
try
{
if (!Utils.IsAdministrator())
{
return false;
}
return PowerShellConfig.Instance.GetDisablePromptToUpdateHelp();
}
catch (SecurityException)
{
return false;
}
#endif
}
#endregion
#region Events
internal event EventHandler<UpdatableHelpProgressEventArgs> OnProgressChanged;
#if !CORECLR
/// <summary>
/// Handles the download completion event.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void HandleDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (_stopping)
{
return;
}
if (!e.Cancelled)
{
if (e.Error != null)
{
if (e.Error is WebException)
{
Errors.Add(new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound, e.UserState.ToString()),
ErrorCategory.ResourceUnavailable, null, null));
}
else
{
Errors.Add(e.Error);
}
}
else
{
lock (_syncObject)
{
_progressEvents.Add(new UpdatableHelpProgressEventArgs(CurrentModule, StringUtil.Format(
HelpDisplayStrings.UpdateProgressDownloading), 100));
}
}
_completed = true;
_completionEvent.Set();
}
}
/// <summary>
/// Handles the download progress changed event.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void HandleDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
if (_stopping)
{
return;
}
lock (_syncObject)
{
_progressEvents.Add(new UpdatableHelpProgressEventArgs(CurrentModule, StringUtil.Format(
HelpDisplayStrings.UpdateProgressDownloading), e.ProgressPercentage));
}
_completionEvent.Set();
}
#endif
#endregion
}
/// <summary>
/// Controls the updatable help system drive.
/// </summary>
internal class UpdatableHelpSystemDrive : IDisposable
{
private string _driveName;
private PSCmdlet _cmdlet;
/// <summary>
/// Gets the drive name.
/// </summary>
internal string DriveName
{
get
{
return _driveName + ":\\";
}
}
/// <summary>
/// </summary>
/// <param name="cmdlet"></param>
/// <param name="path"></param>
/// <param name="credential"></param>
internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential credential)
{
for (int i = 0; i < 6; i++)
{
_driveName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
_cmdlet = cmdlet;
// Need to get rid of the trailing \, otherwise New-PSDrive will not work...
if (path.EndsWith("\\", StringComparison.OrdinalIgnoreCase) || path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
{
path = path.Remove(path.Length - 1);
}
PSDriveInfo mappedDrive = cmdlet.SessionState.Drive.GetAtScope(_driveName, "local");
if (mappedDrive != null)
{
if (mappedDrive.Root.Equals(path))
{
return;
}
// Remove the drive after 5 tries
if (i < 5)
{
continue;
}
cmdlet.SessionState.Drive.Remove(_driveName, true, "local");
}
mappedDrive = new PSDriveInfo(_driveName, cmdlet.SessionState.Internal.GetSingleProvider("FileSystem"),
path, string.Empty, credential);
cmdlet.SessionState.Drive.New(mappedDrive, "local");
break;
}
}
/// <summary>
/// Disposes the class.
/// </summary>
public void Dispose()
{
PSDriveInfo mappedDrive = _cmdlet.SessionState.Drive.GetAtScope(_driveName, "local");
if (mappedDrive != null)
{
_cmdlet.SessionState.Drive.Remove(_driveName, true, "local");
}
GC.SuppressFinalize(this);
}
}
}
| |
//
// EngineBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
// Eric Maupin <[email protected]>
//
// Copyright (c) 2011-2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Reflection;
using System.IO;
using Xwt.Drawing;
using System.Collections.Generic;
namespace Xwt.Backends
{
public abstract class ToolkitEngineBackend
{
Dictionary<Type,Type> backendTypes;
Dictionary<Type,Type> backendTypesByFrontend;
Toolkit toolkit;
bool isGuest;
bool initializeToolkit;
/// <summary>
/// Initialize the specified toolkit.
/// </summary>
/// <param name="toolkit">Toolkit to initialize.</param>
/// <param name="isGuest">If set to <c>true</c> the toolkit will be initialized as guest of another toolkit.</param>
internal void Initialize (Toolkit toolkit, bool isGuest, bool initializeToolkit)
{
this.toolkit = toolkit;
this.isGuest = isGuest;
this.initializeToolkit = initializeToolkit;
if (backendTypes == null) {
backendTypes = new Dictionary<Type, Type> ();
backendTypesByFrontend = new Dictionary<Type, Type> ();
InitializeBackends ();
}
InitializeApplication ();
}
/// <summary>
/// Gets the toolkit engine backend.
/// </summary>
/// <returns>The toolkit backend.</returns>
/// <typeparam name="T">The Type of the toolkit backend.</typeparam>
public static T GetToolkitBackend<T> () where T : ToolkitEngineBackend
{
return (T)Toolkit.GetToolkitBackend (typeof (T));
}
/// <summary>
/// Gets the application context.
/// </summary>
/// <value>The application context.</value>
public ApplicationContext ApplicationContext {
get { return toolkit.Context; }
}
/// <summary>
/// Gets a value indicating whether this toolkit is running as a guest of another toolkit
/// </summary>
/// <remarks>
/// A toolkit is a guest toolkit when it is loaded after the main toolkit of an application
/// </remarks>
public bool IsGuest {
get { return isGuest; }
}
public bool InitializeToolkit
{
get { return initializeToolkit; }
}
/// <summary>
/// Initializes the application.
/// </summary>
public virtual void InitializeApplication ()
{
}
/// <summary>
/// Initializes the widget registry used by the application.
/// </summary>
/// <remarks>
/// Don't do any toolkit initialization there, do them in InitializeApplication.
/// Override to register the backend classes, by calling RegisterBackend() methods.
/// </remarks>
public virtual void InitializeBackends ()
{
}
/// <summary>
/// Runs the main GUI loop
/// </summary>
public abstract void RunApplication ();
/// <summary>
/// Exits the main GUI loop
/// </summary>
public abstract void ExitApplication ();
/// <summary>
/// Exits the main GUI loop with an exit code
/// </summary>
public virtual void ExitApplication(int exitCode)
{
ExitApplication();
}
/// <summary>
/// Releases all resource used by the <see cref="Xwt.Backends.ToolkitEngineBackend"/> object.
/// </summary>
public virtual void Dispose ()
{
}
/// <summary>
/// Asynchronously invokes <paramref name="action"/> on the engine UI thread.
/// </summary>
/// <param name="action">The action to invoke.</param>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
public abstract void InvokeAsync (Action action);
/// <summary>
/// Begins invoking <paramref name="action"/> on a timer period of <paramref name="timeSpan"/>.
/// </summary>
/// <param name="action">The function to invoke. Returning <c>false</c> stops the timer.</param>
/// <param name="timeSpan">The period before the initial invoke and between subsequent invokes.</param>
/// <returns>An identifying object that can be used to cancel the timer with <seealso cref="CancelTimerInvoke"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
/// <seealso cref="CancelTimerInvoke"/>
public abstract object TimerInvoke (Func<bool> action, TimeSpan timeSpan);
/// <summary>
/// Cancels an invoke timer started from <see cref="TimerInvoke"/>.
/// </summary>
/// <param name="id">The unique object returned from <see cref="TimerInvoke"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception>
public abstract void CancelTimerInvoke (object id);
/// <summary>
/// Gets a reference to the native widget wrapped by an XWT widget
/// </summary>
/// <returns>
/// The native widget.
/// </returns>
/// <param name='w'>
/// A widget
/// </param>
public abstract object GetNativeWidget (Widget w);
/// <summary>
/// Gets a reference to the image object wrapped by an XWT Image
/// </summary>
/// <returns>
/// The native image.
/// </returns>
/// <param name='image'>
/// An image.
/// </param>
public virtual object GetNativeImage (Image image)
{
return Toolkit.GetBackend (image);
}
/// <summary>
/// Dispatches pending events in the UI event queue
/// </summary>
public abstract void DispatchPendingEvents ();
/// <summary>
/// Gets the backend for a native window.
/// </summary>
/// <returns>
/// The backend for the window.
/// </returns>
/// <param name='nativeWindow'>
/// A native window reference.
/// </param>
public abstract IWindowFrameBackend GetBackendForWindow (object nativeWindow);
/// <summary>
/// Gets a native window reference from an Xwt window.
/// </summary>
/// <returns> The native window object. </returns>
/// <param name='window'> The Xwt window. </param>
public virtual object GetNativeWindow (WindowFrame window)
{
if (window == null)
return null;
return GetNativeWindow (window.GetBackend () as IWindowFrameBackend);
}
/// <summary>
/// Gets a native window reference from an Xwt window backend.
/// </summary>
/// <returns> The native window object. </returns>
/// <param name='backend'> The Xwt window backend. </param>
public abstract object GetNativeWindow (IWindowFrameBackend backend);
/// <summary>
/// Gets the native parent window of a widget
/// </summary>
/// <returns>
/// The native parent window.
/// </returns>
/// <param name='w'>
/// A widget
/// </param>
/// <remarks>
/// This method is used by XWT to get the window of a widget, when the widget is
/// embedded in a native application
/// </remarks>
public virtual object GetNativeParentWindow (Widget w)
{
return null;
}
/// <summary>
/// Gets the backend for a native drawing context.
/// </summary>
/// <returns>The backend for context.</returns>
/// <param name="nativeContext">The native context.</param>
public virtual object GetBackendForContext (object nativeWidget, object nativeContext)
{
return nativeContext;
}
/// <summary>
/// Gets the backend for a native image.
/// </summary>
/// <returns>The image backend .</returns>
/// <param name="nativeImage">The native image.</param>
public virtual object GetBackendForImage (object nativeImage)
{
return nativeImage;
}
/// <summary>
/// Gets a value indicating whether this <see cref="ToolkitEngineBackend" /> handles size negotiation on its own
/// </summary>
/// <value>
/// <c>true</c> if the engine backend handles size negotiation; otherwise, <c>false</c>.
/// </value>
public virtual bool HandlesSizeNegotiation {
get { return false; }
}
void CheckInitialized ()
{
if (backendTypes == null)
throw new InvalidOperationException ("XWT toolkit not initialized");
}
/// <summary>
/// Creates a backend for a frontend.
/// </summary>
/// <returns>The backend for the specified frontend.</returns>
/// <param name="frontendType">The Frontend type.</param>
internal IBackend CreateBackendForFrontend (Type frontendType)
{
CheckInitialized ();
Type bt = null;
if (!backendTypesByFrontend.TryGetValue (frontendType, out bt)) {
var attr = (BackendTypeAttribute) Attribute.GetCustomAttribute (frontendType, typeof(BackendTypeAttribute), true);
if (attr == null || attr.Type == null)
throw new InvalidOperationException ("Backend type not specified for type: " + frontendType);
if (!typeof(IBackend).IsAssignableFrom (attr.Type))
throw new InvalidOperationException ("Backend type for frontend '" + frontendType + "' is not a IBackend implementation");
bt = GetBackendImplementationType (attr.Type);
backendTypesByFrontend [frontendType] = bt;
}
if (bt == null)
return null;
return (IBackend) Activator.CreateInstance (bt);
}
/// <summary>
/// Creates the backend.
/// </summary>
/// <returns>The backend.</returns>
/// <param name="backendType">The Backend type.</param>
internal object CreateBackend (Type backendType)
{
CheckInitialized ();
Type bt = GetBackendImplementationType (backendType);
if (bt == null)
return null;
var res = Activator.CreateInstance (bt);
if (!backendType.IsInstanceOfType (res))
throw new InvalidOperationException ("Invalid backend type. Expected '" + backendType + "' found '" + res.GetType () + "'");
if (res is BackendHandler)
((BackendHandler)res).Initialize (toolkit);
return res;
}
/// <summary>
/// Gets the type that implements the provided backend interface
/// </summary>
/// <returns>The backend implementation type.</returns>
/// <param name="backendType">Backend interface type.</param>
protected virtual Type GetBackendImplementationType (Type backendType)
{
Type bt;
backendTypes.TryGetValue (backendType, out bt);
return bt;
}
/// <summary>
/// Creates the backend.
/// </summary>
/// <returns>The backend.</returns>
/// <typeparam name="T">The Backend type.</typeparam>
internal T CreateBackend<T> ()
{
return (T) CreateBackend (typeof(T));
}
/// <summary>
/// Registers a backend for an Xwt backend interface.
/// </summary>
/// <typeparam name="Backend">The backend Type</typeparam>
/// <typeparam name="Implementation">The Xwt interface implemented by the backend</typeparam>
public void RegisterBackend<Backend, Implementation> () where Implementation: Backend
{
CheckInitialized ();
backendTypes [typeof(Backend)] = typeof(Implementation);
}
/// <summary>
/// Creates the Xwt frontend for a backend.
/// </summary>
/// <returns>The Xwt frontend.</returns>
/// <param name="backend">The backend.</param>
/// <typeparam name="T">The frontend type.</typeparam>
public T CreateFrontend<T> (object backend)
{
return (T) Activator.CreateInstance (typeof(T), backend);
}
/// <summary>
/// Registers a callback to be invoked just before the execution returns to the main loop
/// </summary>
/// <param name='action'>
/// Callback to execute
/// </param>
/// <remarks>
/// The default implementation does the invocation using InvokeAsync.
/// </remarks>
public virtual void InvokeBeforeMainLoop (Action action)
{
InvokeAsync (action);
}
/// <summary>
/// Determines whether a widget has a native parent widget
/// </summary>
/// <returns><c>true</c> if the widget has native parent; otherwise, <c>false</c>.</returns>
/// <param name="w">The widget.</param>
/// <remarks>This funciton is used to determine if a widget is a child of another non-XWT widget
/// </remarks>
public abstract bool HasNativeParent (Widget w);
/// <summary>
/// Renders a widget into a bitmap
/// </summary>
/// <param name="w">A widget</param>
/// <returns>An image backend</returns>
public virtual object RenderWidget (Widget w)
{
throw new NotSupportedException ();
}
/// <summary>
/// Renders an image at the provided native context
/// </summary>
/// <param name="nativeContext">Native context.</param>
/// <param name="img">Image.</param>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
public virtual void RenderImage (object nativeWidget, object nativeContext, ImageDescription img, double x, double y)
{
}
/// <summary>
/// Gets the bounds of a native widget in screen coordinates.
/// </summary>
/// <returns>The screen bounds relative to <see cref="P:Xwt.Desktop.Bounds"/>.</returns>
/// <param name="nativeWidget">The native widget.</param>
/// <exception cref="NotSupportedException">This toolkit does not support this operation.</exception>
/// <exception cref="InvalidOperationException"><paramref name="nativeWidget"/> does not belong to this toolkit.</exception>
public virtual Rectangle GetScreenBounds (object nativeWidget)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets the information about Xwt features supported by the toolkit.
/// </summary>
/// <value>The supported features.</value>
public virtual ToolkitFeatures SupportedFeatures {
get { return ToolkitFeatures.All; }
}
}
}
| |
using System.Security.Principal;
using System.Windows.Media.Imaging;
using Microsoft.Deployment.WindowsInstaller;
using Caliburn.Micro;
using WixSharp;
using WixSharp.CommonTasks;
using WixSharp.UI.Forms;
using WixSharp.UI.WPF;
namespace $safeprojectname$
{
/// <summary>
/// The standard ProgressDialog.
/// <para>Follows the design of the canonical Caliburn.Micro View (MVVM).</para>
/// <para>See https://caliburnmicro.com/documentation/cheat-sheet</para>
/// </summary>
/// <seealso cref="WixSharp.UI.WPF.WpfDialog" />
/// <seealso cref="WixSharp.IWpfDialog" />
/// <seealso cref="System.Windows.Markup.IComponentConnector" />
public partial class ProgressDialog : WpfDialog, IWpfDialog, IProgressDialog
{
/// <summary>
/// Initializes a new instance of the <see cref="ProgressDialog" /> class.
/// </summary>
public ProgressDialog()
{
InitializeComponent();
}
/// <summary>
/// This method is invoked by WixSHarp runtime when the custom dialog content is internally fully initialized.
/// This is a convenient place to do further initialization activities (e.g. localization).
/// </summary>
public void Init()
{
UpdateTitles(ManagedFormHost.Runtime.Session);
model = new ProgressDialogModel { Host = ManagedFormHost };
ViewModelBinder.Bind(model, this, null);
model.StartExecute();
}
/// <summary>
/// Updates the titles of the dialog depending on what type of installation action MSI is performing.
/// </summary>
/// <param name="session">The session.</param>
public void UpdateTitles(ISession session)
{
if (session.IsUninstalling())
{
DialogTitleLabel.Text = "[ProgressDlgTitleRemoving]";
DialogDescription.Text = "[ProgressDlgTextRemoving]";
}
else if (session.IsRepairing())
{
DialogTitleLabel.Text = "[ProgressDlgTextRepairing]";
DialogDescription.Text = "[ProgressDlgTitleRepairing]";
}
else if (session.IsInstalling())
{
DialogTitleLabel.Text = "[ProgressDlgTitleInstalling]";
DialogDescription.Text = "[ProgressDlgTextInstalling]";
}
// `Localize` resolves [...] titles and descriptions into the localized strings stored in MSI resources tables
this.Localize();
}
ProgressDialogModel model;
/// <summary>
/// Processes information and progress messages sent to the user interface.
/// <para> This method directly mapped to the
/// <see cref="T:Microsoft.Deployment.WindowsInstaller.IEmbeddedUI.ProcessMessage" />.</para>
/// </summary>
/// <param name="messageType">Type of the message.</param>
/// <param name="messageRecord">The message record.</param>
/// <param name="buttons">The buttons.</param>
/// <param name="icon">The icon.</param>
/// <param name="defaultButton">The default button.</param>
/// <returns></returns>
public override MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, MessageButtons buttons, MessageIcon icon, MessageDefaultButton defaultButton)
=> model?.ProcessMessage(messageType, messageRecord, CurrentStatus.Text) ?? MessageResult.None;
/// <summary>
/// Called when MSI execution is complete.
/// </summary>
public override void OnExecuteComplete()
=> model?.OnExecuteComplete();
/// <summary>
/// Called when MSI execution progress is changed.
/// </summary>
/// <param name="progressPercentage">The progress percentage.</param>
public override void OnProgress(int progressPercentage)
{
if (model != null)
model.ProgressValue = progressPercentage;
}
}
/// <summary>
/// ViewModel for standard ProgressDialog.
/// <para>Follows the design of the canonical Caliburn.Micro ViewModel (MVVM).</para>
/// <para>See https://caliburnmicro.com/documentation/cheat-sheet</para>
/// </summary>
/// <seealso cref="Caliburn.Micro.Screen" />
class ProgressDialogModel : Caliburn.Micro.Screen
{
public ManagedForm Host;
ISession session => Host?.Runtime.Session;
IManagedUIShell shell => Host?.Shell;
public BitmapImage Banner => session?.GetResourceBitmap("WixUI_Bmp_Banner").ToImageSource();
public bool UacPromptIsVisible => (!WindowsIdentity.GetCurrent().IsAdmin() && Uac.IsEnabled() && !uacPromptActioned);
public string CurrentAction { get => currentAction; set { currentAction = value; base.NotifyOfPropertyChange(() => CurrentAction); } }
public int ProgressValue { get => progressValue; set { progressValue = value; base.NotifyOfPropertyChange(() => ProgressValue); } }
bool uacPromptActioned = false;
string currentAction;
int progressValue;
public string UacPrompt
{
get
{
if (Uac.IsEnabled())
{
var prompt = session?.Property("UAC_WARNING");
if (prompt.IsNotEmpty())
return prompt;
else
return
"Please wait for UAC prompt to appear. " +
"If it appears minimized then activate it from the taskbar.";
}
else
return null;
}
}
public void StartExecute()
=> shell?.StartExecute();
public void Cancel()
{
if (shell.IsDemoMode)
shell.GoNext();
else
shell.Cancel();
}
public MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, string currentStatus)
{
switch (messageType)
{
case InstallMessage.InstallStart:
case InstallMessage.InstallEnd:
{
uacPromptActioned = true;
base.NotifyOfPropertyChange(() => UacPromptIsVisible);
}
break;
case InstallMessage.ActionStart:
{
try
{
//messageRecord[0] - is reserved for FormatString value
/*
messageRecord[2] unconditionally contains the string to display
Examples:
messageRecord[0] "Action 23:14:50: [1]. [2]"
messageRecord[1] "InstallFiles"
messageRecord[2] "Copying new files"
messageRecord[3] "File: [1], Directory: [9], Size: [6]"
messageRecord[0] "Action 23:15:21: [1]. [2]"
messageRecord[1] "RegisterUser"
messageRecord[2] "Registering user"
messageRecord[3] "[1]"
*/
if (messageRecord.FieldCount >= 3)
CurrentAction = messageRecord[2].ToString();
else
CurrentAction = null;
}
catch
{
//Catch all, we don't want the installer to crash in an attempt to process message.
}
}
break;
}
return MessageResult.OK;
}
public void OnExecuteComplete()
{
CurrentAction = null;
shell?.GoNext();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Desafio.API.Areas.HelpPage.ModelDescriptions;
using Desafio.API.Areas.HelpPage.Models;
namespace Desafio.API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Transactions
{
using System;
using System.ServiceModel.Channels;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Transactions;
using System.ServiceModel.Security;
using System.ServiceModel.Diagnostics;
using Microsoft.Transactions.Bridge;
using Microsoft.Transactions.Wsat.Messaging;
using Microsoft.Transactions.Wsat.Protocol;
using DiagnosticUtility = System.ServiceModel.DiagnosticUtility;
using System.Security.Permissions;
class WsatProxy
{
WsatConfiguration wsatConfig;
ProtocolVersion protocolVersion;
CoordinationService coordinationService;
ActivationProxy activationProxy;
object proxyLock = new object();
public WsatProxy(WsatConfiguration wsatConfig, ProtocolVersion protocolVersion)
{
this.wsatConfig = wsatConfig;
this.protocolVersion = protocolVersion;
}
//=============================================================================================
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls to CoordinationContext properties are safe.")]
public Transaction UnmarshalTransaction(WsatTransactionInfo info)
{
if (info.Context.ProtocolVersion != this.protocolVersion)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.GetString(SR.InvalidWsatProtocolVersion)));
}
if (wsatConfig.OleTxUpgradeEnabled)
{
byte[] propToken = info.Context.PropagationToken;
if (propToken != null)
{
try
{
return OleTxTransactionInfo.UnmarshalPropagationToken(propToken);
}
catch (TransactionException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
}
// Fall back to WS-AT unmarshal
if (DiagnosticUtility.ShouldTraceInformation)
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.TxFailedToNegotiateOleTx,
SR.GetString(SR.TraceCodeTxFailedToNegotiateOleTx, info.Context.Identifier));
}
}
// Optimization: if the context's registration service points to our local TM, we can
// skip the CreateCoordinationContext step
CoordinationContext localContext = info.Context;
if (!this.wsatConfig.IsLocalRegistrationService(localContext.RegistrationService, this.protocolVersion))
{
// Our WS-AT protocol service for the context's protocol version should be enabled
if (!this.wsatConfig.IsProtocolServiceEnabled(this.protocolVersion))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.WsatProtocolServiceDisabled, this.protocolVersion)));
}
// We should have enabled inbound transactions
if (!this.wsatConfig.InboundEnabled)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.InboundTransactionsDisabled)));
}
// The sender should have enabled both WS-AT and outbound transactions
if (this.wsatConfig.IsDisabledRegistrationService(localContext.RegistrationService))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.SourceTransactionsDisabled)));
}
// Ask the WS-AT protocol service to unmarshal the transaction
localContext = CreateCoordinationContext(info);
}
Guid transactionId = localContext.LocalTransactionId;
if (transactionId == Guid.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.InvalidCoordinationContextTransactionId)));
}
byte[] propagationToken = MarshalPropagationToken(ref transactionId,
localContext.IsolationLevel,
localContext.IsolationFlags,
localContext.Description);
return OleTxTransactionInfo.UnmarshalPropagationToken(propagationToken);
}
//=============================================================================================
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
/*
// We demand full trust because we use CreateCoordinationContext from a non-APTCA assembly and the CreateCoordinationContext constructor does an Environment.FailFast
// if the argument is invalid. It's recommended to not let partially trusted callers to bring down the process.
// WSATs are not supported in partial trust, so customers should not be broken by this demand.
[PermissionSet(SecurityAction.Demand, Unrestricted = true)]
*/
CoordinationContext CreateCoordinationContext(WsatTransactionInfo info)
{
CreateCoordinationContext cccMessage = new CreateCoordinationContext(this.protocolVersion);
cccMessage.CurrentContext = info.Context;
cccMessage.IssuedToken = info.IssuedToken;
try
{
// This was necessary during some portions of WCF 1.0 development
// It is probably not needed now. However, it seems conceptually
// solid to separate this operation from the incoming app message as
// much as possible. There have also been enough ServiceModel bugs in
// this area that it does not seem wise to remove this at the moment
// (2006/3/30, WCF 1.0 RC1 milestone)
using (new OperationContextScope((OperationContext)null))
{
return Enlist(ref cccMessage).CoordinationContext;
}
}
catch (WsatFaultException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.UnmarshalTransactionFaulted, e.Message), e));
}
catch (WsatSendFailureException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionManagerCommunicationException(SR.GetString(SR.TMCommunicationError), e));
}
}
//=============================================================================================
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
/*
[PermissionSet(SecurityAction.Demand, Unrestricted = true)] // because we call code from a non-APTCA assembly; WSATs are not supported in partial trust, so customers should not be broken by this demand
*/
CreateCoordinationContextResponse Enlist(ref CreateCoordinationContext cccMessage)
{
int attempts = 0;
while (true)
{
ActivationProxy proxy = GetActivationProxy();
EndpointAddress address = proxy.To;
EndpointAddress localActivationService = this.wsatConfig.LocalActivationService(this.protocolVersion);
EndpointAddress remoteActivationService = this.wsatConfig.RemoteActivationService(this.protocolVersion);
try
{
return proxy.SendCreateCoordinationContext(ref cccMessage);
}
catch (WsatSendFailureException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
// Don't retry if we're not likely to succeed on the next pass
Exception inner = e.InnerException;
if (inner is TimeoutException ||
inner is QuotaExceededException ||
inner is FaultException)
throw;
// Give up after 10 attempts
if (attempts > 10)
throw;
if (attempts > 5 &&
remoteActivationService != null &&
ReferenceEquals(address, localActivationService))
{
// Switch over to the remote activation service.
// In clustered scenarios this uses the cluster name,
// so it should always work if the resource is online
// This covers the case where we were using a local cluster
// resource which failed over to another node
address = remoteActivationService;
}
}
finally
{
proxy.Release();
}
TryStartMsdtcService();
// We need to refresh our proxy here because the channel is sessionful
// and may simply decided to enter the faulted state if something fails.
RefreshActivationProxy(address);
// Don't spin
Thread.Sleep(0);
attempts++;
}
}
//=============================================================================================
void TryStartMsdtcService()
{
try
{
TransactionInterop.GetWhereabouts();
}
catch (TransactionException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
}
}
//=============================================================================================
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
/*
// We demand full trust because we call ActivationProxy.AddRef(), which is defined in a non-APTCA assembly and can do Environment.FailFast.
// It's recommended to not let partially trusted callers to bring down the process.
// WSATs are not supported in partial trust, so customers should not be broken by this demand.
[PermissionSet(SecurityAction.Demand, Unrestricted = true)]
*/
ActivationProxy GetActivationProxy()
{
if (this.activationProxy == null)
{
RefreshActivationProxy(null);
}
lock (this.proxyLock)
{
ActivationProxy proxy = this.activationProxy;
proxy.AddRef();
return proxy;
}
}
//=============================================================================================
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
/*
// We demand full trust because we call ActivationProxy.Release(), which is defined in a non-APTCA assembly and can do Environment.FailFast.
// It's recommended to not let partially trusted callers to bring down the process.
// WSATs are not supported in partial trust, so customers should not be broken by this demand.
[PermissionSet(SecurityAction.Demand, Unrestricted = true)]
*/
void RefreshActivationProxy(EndpointAddress suggestedAddress)
{
// Pick an address in the following order...
EndpointAddress address = suggestedAddress;
if (address == null)
{
address = this.wsatConfig.LocalActivationService(this.protocolVersion);
if (address == null)
{
address = this.wsatConfig.RemoteActivationService(this.protocolVersion);
}
}
if (!(address != null))
{
// tx processing requires failfast when state is inconsistent
DiagnosticUtility.FailFast("Must have valid activation service address");
}
lock (this.proxyLock)
{
ActivationProxy newProxy = CreateActivationProxy(address);
if (this.activationProxy != null)
this.activationProxy.Release();
this.activationProxy = newProxy;
}
}
//=============================================================================================
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
/*
[PermissionSet(SecurityAction.Demand, Unrestricted = true)] // because we call code from a non-APTCA assembly; WSATs are not supported in partial trust, so customers should not be broken by this demand
*/
ActivationProxy CreateActivationProxy(EndpointAddress address)
{
CoordinationService coordination = GetCoordinationService();
try
{
return coordination.CreateActivationProxy(address, false);
}
catch (CreateChannelFailureException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.WsatProxyCreationFailed), e));
}
}
//=============================================================================================
//[SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "We call PartialTrustHelpers.DemandForFullTrust().")]
CoordinationService GetCoordinationService()
{
if (this.coordinationService == null)
{
lock (this.proxyLock)
{
if (this.coordinationService == null)
{
// The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
/*
// We demand full trust because CoordinationService is defined in a non-APTCA assembly and can call Environment.FailFast.
// It's recommended to not let partially trusted callers to bring down the process.
System.Runtime.PartialTrustHelpers.DemandForFullTrust();
*/
try
{
CoordinationServiceConfiguration config = new CoordinationServiceConfiguration();
config.Mode = CoordinationServiceMode.Formatter;
config.RemoteClientsEnabled = this.wsatConfig.RemoteActivationService(this.protocolVersion) != null;
this.coordinationService = new CoordinationService(config, this.protocolVersion);
}
catch (MessagingInitializationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TransactionException(SR.GetString(SR.WsatMessagingInitializationFailed), e));
}
}
}
}
return this.coordinationService;
}
//-------------------------------------------------------------------------------
// Marshal/Unmarshaling related stuff
//-------------------------------------------------------------------------------
// Keep a propagation token around as a template for hydrating transactions
static byte[] fixedPropagationToken;
static byte[] CreateFixedPropagationToken()
{
if (fixedPropagationToken == null)
{
CommittableTransaction tx = new CommittableTransaction();
byte[] token = TransactionInterop.GetTransmitterPropagationToken(tx);
// Don't abort the transaction. People notice this and do not like it.
try
{
tx.Commit();
}
catch (TransactionException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
Interlocked.CompareExchange<byte[]>(ref fixedPropagationToken, token, null);
}
byte[] tokenCopy = new byte[fixedPropagationToken.Length];
Array.Copy(fixedPropagationToken, tokenCopy, fixedPropagationToken.Length);
return tokenCopy;
}
// This is what a propagation token looks like:
//
// struct PropagationToken
// {
// DWORD dwVersionMin;
// DWORD dwVersionMax;
// GUID guidTx;
// ISOLATIONLEVEL isoLevel;
// ISOFLAG isoFlags;
// ULONG cbSourceTmAddr;
// char szDesc[40];
// [etc]
// }
static byte[] MarshalPropagationToken(ref Guid transactionId,
IsolationLevel isoLevel,
IsolationFlags isoFlags,
string description)
{
const int offsetof_guidTx = 8;
const int offsetof_isoLevel = 24;
const int offsetof_isoFlags = 28;
const int offsetof_szDesc = 36;
const int MaxDescriptionLength = 39;
byte[] token = CreateFixedPropagationToken();
// Replace transaction id
byte[] transactionIdBytes = transactionId.ToByteArray();
Array.Copy(transactionIdBytes, 0, token, offsetof_guidTx, transactionIdBytes.Length);
// Replace isolation level
byte[] isoLevelBytes = BitConverter.GetBytes((int)ConvertIsolationLevel(isoLevel));
Array.Copy(isoLevelBytes, 0, token, offsetof_isoLevel, isoLevelBytes.Length);
// Replace isolation flags
byte[] isoFlagsBytes = BitConverter.GetBytes((int)isoFlags);
Array.Copy(isoFlagsBytes, 0, token, offsetof_isoFlags, isoFlagsBytes.Length);
// Replace description
if (!string.IsNullOrEmpty(description))
{
byte[] descriptionBytes = Encoding.UTF8.GetBytes(description);
int copyDescriptionBytes = Math.Min(descriptionBytes.Length, MaxDescriptionLength);
Array.Copy(descriptionBytes, 0, token, offsetof_szDesc, copyDescriptionBytes);
token[offsetof_szDesc + copyDescriptionBytes] = 0;
}
return token;
}
enum ProxyIsolationLevel : int
{
Unspecified = -1,
Chaos = 0x10,
ReadUncommitted = 0x100,
Browse = 0x100,
CursorStability = 0x1000,
ReadCommitted = 0x1000,
RepeatableRead = 0x10000,
Serializable = 0x100000,
Isolated = 0x100000
}
static ProxyIsolationLevel ConvertIsolationLevel(IsolationLevel IsolationLevel)
{
ProxyIsolationLevel retVal;
switch (IsolationLevel)
{
case IsolationLevel.Serializable:
retVal = ProxyIsolationLevel.Serializable;
break;
case IsolationLevel.RepeatableRead:
retVal = ProxyIsolationLevel.RepeatableRead;
break;
case IsolationLevel.ReadCommitted:
retVal = ProxyIsolationLevel.ReadCommitted;
break;
case IsolationLevel.ReadUncommitted:
retVal = ProxyIsolationLevel.ReadUncommitted;
break;
case IsolationLevel.Unspecified:
retVal = ProxyIsolationLevel.Unspecified;
break;
default:
retVal = ProxyIsolationLevel.Serializable;
break;
}
return retVal;
}
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. 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.
// */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
namespace Alachisoft.NosDB.Common.DataStructures.Clustered
{
public class RandomizedStringEqualityComparer : IEqualityComparer<string>, IEqualityComparer, IWellKnownStringEqualityComparer
{
private long _entropy;
public RandomizedStringEqualityComparer()
{
this._entropy = HashHelpers.GetEntropy();
}
public new bool Equals(object x, object y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
if (x is string && y is string)
{
return this.Equals((string)x, (string)y);
}
throw new ArgumentException(ResourceHelper.GetResourceString(GetResourceName(ExceptionResource.Argument_InvalidArgumentForComparison)));
return false;
}
[SecurityCritical, SuppressUnmanagedCodeSecurity]
[DllImport("QCall", CharSet = CharSet.Unicode)]
public static extern bool InternalUseRandomizedHashing();
internal static string GetResourceName(ExceptionResource resource)
{
string result;
switch (resource)
{
case ExceptionResource.Argument_ImplementIComparable:
result = "Argument_ImplementIComparable";
break;
case ExceptionResource.Argument_InvalidType:
result = "Argument_InvalidType";
break;
case ExceptionResource.Argument_InvalidArgumentForComparison:
result = "Argument_InvalidArgumentForComparison";
break;
case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck:
result = "Argument_InvalidRegistryKeyPermissionCheck";
break;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
result = "ArgumentOutOfRange_NeedNonNegNum";
break;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
result = "Arg_ArrayPlusOffTooSmall";
break;
case ExceptionResource.Arg_NonZeroLowerBound:
result = "Arg_NonZeroLowerBound";
break;
case ExceptionResource.Arg_RankMultiDimNotSupported:
result = "Arg_RankMultiDimNotSupported";
break;
case ExceptionResource.Arg_RegKeyDelHive:
result = "Arg_RegKeyDelHive";
break;
case ExceptionResource.Arg_RegKeyStrLenBug:
result = "Arg_RegKeyStrLenBug";
break;
case ExceptionResource.Arg_RegSetStrArrNull:
result = "Arg_RegSetStrArrNull";
break;
case ExceptionResource.Arg_RegSetMismatchedKind:
result = "Arg_RegSetMismatchedKind";
break;
case ExceptionResource.Arg_RegSubKeyAbsent:
result = "Arg_RegSubKeyAbsent";
break;
case ExceptionResource.Arg_RegSubKeyValueAbsent:
result = "Arg_RegSubKeyValueAbsent";
break;
case ExceptionResource.Argument_AddingDuplicate:
result = "Argument_AddingDuplicate";
break;
case ExceptionResource.Serialization_InvalidOnDeser:
result = "Serialization_InvalidOnDeser";
break;
case ExceptionResource.Serialization_MissingKeys:
result = "Serialization_MissingKeys";
break;
case ExceptionResource.Serialization_NullKey:
result = "Serialization_NullKey";
break;
case ExceptionResource.Argument_InvalidArrayType:
result = "Argument_InvalidArrayType";
break;
case ExceptionResource.NotSupported_KeyCollectionSet:
result = "NotSupported_KeyCollectionSet";
break;
case ExceptionResource.NotSupported_ValueCollectionSet:
result = "NotSupported_ValueCollectionSet";
break;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
result = "ArgumentOutOfRange_SmallCapacity";
break;
case ExceptionResource.ArgumentOutOfRange_Index:
result = "ArgumentOutOfRange_Index";
break;
case ExceptionResource.Argument_InvalidOffLen:
result = "Argument_InvalidOffLen";
break;
case ExceptionResource.Argument_ItemNotExist:
result = "Argument_ItemNotExist";
break;
case ExceptionResource.ArgumentOutOfRange_Count:
result = "ArgumentOutOfRange_Count";
break;
case ExceptionResource.ArgumentOutOfRange_InvalidThreshold:
result = "ArgumentOutOfRange_InvalidThreshold";
break;
case ExceptionResource.ArgumentOutOfRange_ListInsert:
result = "ArgumentOutOfRange_ListInsert";
break;
case ExceptionResource.NotSupported_ReadOnlyCollection:
result = "NotSupported_ReadOnlyCollection";
break;
case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:
result = "InvalidOperation_CannotRemoveFromStackOrQueue";
break;
case ExceptionResource.InvalidOperation_EmptyQueue:
result = "InvalidOperation_EmptyQueue";
break;
case ExceptionResource.InvalidOperation_EnumOpCantHappen:
result = "InvalidOperation_EnumOpCantHappen";
break;
case ExceptionResource.InvalidOperation_EnumFailedVersion:
result = "InvalidOperation_EnumFailedVersion";
break;
case ExceptionResource.InvalidOperation_EmptyStack:
result = "InvalidOperation_EmptyStack";
break;
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
result = "ArgumentOutOfRange_BiggerThanCollection";
break;
case ExceptionResource.InvalidOperation_EnumNotStarted:
result = "InvalidOperation_EnumNotStarted";
break;
case ExceptionResource.InvalidOperation_EnumEnded:
result = "InvalidOperation_EnumEnded";
break;
case ExceptionResource.NotSupported_SortedListNestedWrite:
result = "NotSupported_SortedListNestedWrite";
break;
case ExceptionResource.InvalidOperation_NoValue:
result = "InvalidOperation_NoValue";
break;
case ExceptionResource.InvalidOperation_RegRemoveSubKey:
result = "InvalidOperation_RegRemoveSubKey";
break;
case ExceptionResource.Security_RegistryPermission:
result = "Security_RegistryPermission";
break;
case ExceptionResource.UnauthorizedAccess_RegistryNoWrite:
result = "UnauthorizedAccess_RegistryNoWrite";
break;
case ExceptionResource.ObjectDisposed_RegKeyClosed:
result = "ObjectDisposed_RegKeyClosed";
break;
case ExceptionResource.NotSupported_InComparableType:
result = "NotSupported_InComparableType";
break;
case ExceptionResource.Argument_InvalidRegistryOptionsCheck:
result = "Argument_InvalidRegistryOptionsCheck";
break;
case ExceptionResource.Argument_InvalidRegistryViewCheck:
result = "Argument_InvalidRegistryViewCheck";
break;
default:
return string.Empty;
}
return result;
}
public bool Equals(string x, string y)
{
if (x != null)
{
return y != null && x.Equals(y);
}
return y == null;
}
[SecuritySafeCritical]
public int GetHashCode(string obj)
{
if (obj == null)
{
return 0;
}
return InternalMarvin32HashString(obj, obj.Length, this._entropy);
}
[DllImport("QCall", CharSet = CharSet.Unicode)]
internal static extern int InternalMarvin32HashString(string s, int sLen, long additionalEntropy);
[SecuritySafeCritical]
public int GetHashCode(object obj)
{
if (obj == null)
{
return 0;
}
string text = obj as string;
if (text != null)
{
return InternalMarvin32HashString(text, text.Length, this._entropy);
}
return obj.GetHashCode();
}
public override bool Equals(object obj)
{
RandomizedStringEqualityComparer randomizedStringEqualityComparer = obj as RandomizedStringEqualityComparer;
return randomizedStringEqualityComparer != null && this._entropy == randomizedStringEqualityComparer._entropy;
}
public override int GetHashCode()
{
return base.GetType().Name.GetHashCode() ^ (int)(this._entropy & 2147483647L);
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer()
{
return new RandomizedStringEqualityComparer();
}
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization()
{
return EqualityComparer<string>.Default;
}
}
}
| |
using System;
using System.Collections.Generic;
using OctoTorrent.BEncoding;
using OctoTorrent.Common;
namespace OctoTorrent
{
public abstract class EditableTorrent
{
static readonly BEncodedString AnnounceKey = "announce";
static readonly BEncodedString AnnounceListKey = "announce-list";
static readonly BEncodedString CommentKey = "comment";
static readonly BEncodedString CreatedByKey = "created by";
static readonly BEncodedString EncodingKey = "encoding";
static readonly BEncodedString InfoKey = "info";
static readonly BEncodedString PieceLengthKey = "piece length";
static readonly BEncodedString PrivateKey = "private";
static readonly BEncodedString PublisherKey = "publisher";
static readonly BEncodedString PublisherUrlKey = "publisher-url";
public string Announce {
get { return GetString (Metadata, AnnounceKey); }
set { SetString (Metadata, AnnounceKey, value); }
}
public IList<RawTrackerTier> Announces {
get; private set;
}
protected bool CanEditSecureMetadata {
get; set;
}
public string Comment {
get { return GetString (Metadata, CommentKey); }
set { SetString (Metadata, CommentKey, value); }
}
public string CreatedBy {
get { return GetString (Metadata, CreatedByKey); }
set { SetString (Metadata, CreatedByKey, value); }
}
public string Encoding {
get { return GetString (Metadata, EncodingKey); }
private set { SetString (Metadata, EncodingKey, value); }
}
protected BEncodedDictionary InfoDict {
get { return GetDictionary (Metadata, InfoKey); }
private set { SetDictionary (Metadata, InfoKey, value); }
}
protected BEncodedDictionary Metadata {
get; private set;
}
public long PieceLength {
get { return GetLong (InfoDict, PieceLengthKey); }
set { SetLong (InfoDict, PieceLengthKey, value); }
}
public bool Private {
get { return GetLong (InfoDict, PrivateKey) == 1; }
set { SetLong (InfoDict, PrivateKey, value ? 1 : 0); }
}
public string Publisher {
get { return GetString (InfoDict, PublisherKey); }
set { SetString (InfoDict, PublisherKey, value); }
}
public string PublisherUrl {
get { return GetString (InfoDict, PublisherUrlKey); }
set { SetString (InfoDict, PublisherUrlKey, value); }
}
public EditableTorrent ()
: this (new BEncodedDictionary ())
{
}
public EditableTorrent (Torrent torrent)
{
Check.Torrent (torrent);
Initialise (torrent.ToDictionary ());
}
public EditableTorrent (BEncodedDictionary metadata)
{
Check.Metadata (metadata);
Initialise (BEncodedValue.Clone (metadata));
}
void Initialise (BEncodedDictionary metadata)
{
Metadata = metadata;
BEncodedValue value;
if (!Metadata.TryGetValue (AnnounceListKey, out value)) {
value = new BEncodedList ();
Metadata.Add (AnnounceListKey, value);
}
Announces = new RawTrackerTiers ((BEncodedList) value);
if (string.IsNullOrEmpty (Encoding))
Encoding = "UTF-8";
if (InfoDict == null)
InfoDict = new BEncodedDictionary ();
}
protected void CheckCanEditSecure ()
{
if (!CanEditSecureMetadata)
throw new InvalidOperationException ("Cannot edit metadata which alters the infohash while CanEditSecureMetadata is false");
}
public BEncodedValue GetCustom (BEncodedString key)
{
BEncodedValue value;
if (Metadata.TryGetValue (key, out value))
return value;
return null;
}
public BEncodedValue GetCustomSecure (BEncodedString key)
{
CheckCanEditSecure ();
BEncodedValue value;
if (InfoDict.TryGetValue (key, out value))
return value;
return null;
}
public void SetCustom (BEncodedString key, BEncodedValue value)
{
Check.Key (key);
Check.Value (value);
if (InfoKey.Equals (key))
CheckCanEditSecure ();
Metadata [key] = value;
}
public void SetCustomSecure (BEncodedString key, BEncodedValue value)
{
CheckCanEditSecure ();
Check.Key (key);
Check.Value (value);
InfoDict [key] = value;
}
public void RemoveCustom (BEncodedString key)
{
Check.Key (key);
Metadata.Remove (key);
}
public void RemoveCustomSecure (BEncodedString key)
{
CheckCanEditSecure ();
Check.Key (key);
InfoDict.Remove (key);
}
public BEncodedDictionary ToDictionary ()
{
return BEncodedValue.Clone (Metadata);
}
public Torrent ToTorrent ()
{
return Torrent.Load (ToDictionary ());
}
protected BEncodedDictionary GetDictionary (BEncodedDictionary dictionary, BEncodedString key)
{
// // Required? Probably.
// if (dictionary == InfoDict)
// CheckCanEditSecure ();
BEncodedValue value;
if (dictionary.TryGetValue (key, out value))
return (BEncodedDictionary) value;
return null;
}
protected long GetLong (BEncodedDictionary dictionary, BEncodedString key)
{
BEncodedValue value;
if (dictionary.TryGetValue (key, out value))
return ((BEncodedNumber) value).Number;
throw new ArgumentException (string.Format ("The value for key {0} was not a BEncodedNumber", key));
}
protected string GetString (BEncodedDictionary dictionary, BEncodedString key)
{
BEncodedValue value;
if (dictionary.TryGetValue (key, out value))
return value.ToString ();
return "";
}
protected void SetDictionary (BEncodedDictionary dictionary, BEncodedString key, BEncodedDictionary value)
{
if (dictionary == InfoDict)
CheckCanEditSecure ();
dictionary [key] = value;
}
protected void SetLong (BEncodedDictionary dictionary, BEncodedString key, long value)
{
if (dictionary == InfoDict)
CheckCanEditSecure ();
dictionary [key] = new BEncodedNumber (value);
}
protected void SetString (BEncodedDictionary dictionary, BEncodedString key, string value)
{
if (dictionary == InfoDict)
CheckCanEditSecure ();
dictionary [key] = new BEncodedString (value);
}
}
}
| |
using System;
using UIKit;
using System.Collections.Generic;
using System.Linq;
using CoreGraphics;
using CoreAnimation;
using Foundation;
using ObjCRuntime;
namespace TicTacToe
{
public class TTTGameView : UIView
{
public Func <TTTGameView, TTTMovePlayer, UIImage> ImageForPlayer;
public Func <TTTGameView, TTTMovePlayer, UIColor> ColorForPlayer;
public Func <TTTGameView, TTTMoveXPosition, TTTMoveYPosition, bool> CanSelect;
public Action <TTTGameView, TTTMoveXPosition, TTTMoveYPosition> DidSelect;
TTTGame game;
public TTTGame Game {
get { return game; }
set {
game = value;
UpdateGameState ();
}
}
UIColor gridColor;
public UIColor GridColor {
get { return gridColor; }
set {
if (!gridColor.Equals (value))
gridColor = value;
updateGridColor ();
}
}
UIView[] horizontalLineViews;
UIView[] verticalLineViews;
List<UIImageView> moveImageViews;
List<UIImageView> moveImageViewReuseQueue;
TTTGameLineView lineView;
const float LineWidth = 4f;
public TTTGameView () : base ()
{
gridColor = UIColor.Black;
horizontalLineViews = new UIView[] {
newLineView (),
newLineView ()
};
verticalLineViews = new UIView[] {
newLineView (),
newLineView ()
};
updateGridColor ();
moveImageViews = new List <UIImageView> ();
moveImageViewReuseQueue = new List <UIImageView> ();
lineView = new TTTGameLineView ();
lineView.Alpha = 0f;
UITapGestureRecognizer gestureRecognizer = new UITapGestureRecognizer (tapGame);
AddGestureRecognizer (gestureRecognizer);
}
UIView newLineView ()
{
UIView view = new UIView ();
AddSubview (view);
return view;
}
void tapGame (UITapGestureRecognizer gestureRecognizer)
{
if (gestureRecognizer.State == UIGestureRecognizerState.Recognized &&
DidSelect != null) {
CGPoint point = gestureRecognizer.LocationInView (this);
CGRect bounds = Bounds;
CGPoint normalizedPoint = point;
normalizedPoint.X -= bounds.X + bounds.Size.Width / 2;
normalizedPoint.X *= 3 / bounds.Size.Width;
normalizedPoint.X = (float)Math.Round (normalizedPoint.X);
normalizedPoint.X = (float)Math.Max (normalizedPoint.X, -1);
normalizedPoint.X = (float)Math.Min (normalizedPoint.X, 1);
TTTMoveXPosition xPosition = (TTTMoveXPosition)(int)normalizedPoint.X;
normalizedPoint.Y -= bounds.Y + bounds.Size.Height / 2;
normalizedPoint.Y *= 3 / bounds.Size.Height;
normalizedPoint.Y = (float)Math.Round (normalizedPoint.Y);
normalizedPoint.Y = (float)Math.Max (normalizedPoint.Y, -1);
normalizedPoint.Y = (float)Math.Min (normalizedPoint.Y, 1);
TTTMoveYPosition yPosition = (TTTMoveYPosition)(int)normalizedPoint.Y;
if (CanSelect == null || CanSelect (this, xPosition, yPosition))
DidSelect (this, xPosition, yPosition);
}
}
UIImageView moveImageView ()
{
UIImageView moveView = moveImageViewReuseQueue.FirstOrDefault ();
if (moveView != null)
moveImageViewReuseQueue.Remove (moveView);
else {
moveView = new UIImageView ();
AddSubview (moveView);
}
moveImageViews.Add (moveView);
return moveView;
}
CGPoint pointForPosition (TTTMoveXPosition xPosition, TTTMoveYPosition yPosition)
{
CGRect bounds = Bounds;
CGPoint point = new CGPoint (bounds.X + bounds.Size.Width / 2,
bounds.Y + bounds.Size.Height / 2);
point.X += (int)xPosition * bounds.Size.Width / 3;
point.Y += (int)yPosition * bounds.Size.Height / 3;
return point;
}
void setMove (TTTMove move, UIImageView moveView)
{
moveView.Image = ImageForPlayer (this, move.Player);
moveView.Center = pointForPosition (move.XPosition, move.YPosition);
}
void setVisible (bool visible, UIImageView moveView)
{
if (visible) {
moveView.SizeToFit ();
moveView.Alpha = 1f;
} else {
moveView.Bounds = new CGRect (0, 0, 0, 0);
moveView.Alpha = 0f;
}
}
public void UpdateGameState ()
{
TTTMove[] moves = Game.Moves.ToArray ();
int moveCount = moves.Length;
UIImageView[] moveViews = new UIImageView[moveImageViews.Count];
moveImageViews.CopyTo (moveViews);
for (int i = 0; i < moveViews.Length; i++) {
UIImageView moveView = moveViews [i];
if (i < moveCount) {
TTTMove move = moves [i];
setMove (move, moveView);
setVisible (true, moveView);
} else {
setVisible (false, moveViews [i]);
moveImageViewReuseQueue.Add (moveView);
moveImageViews.Remove (moveView);
}
}
for (int moveIndex = moveImageViews.Count; moveIndex < moveCount; moveIndex++) {
TTTMove move = moves [moveIndex];
UIImageView moveView = moveImageView ();
UIView.PerformWithoutAnimation (delegate {
setMove (move, moveView);
setVisible (false, moveView);
});
setVisible (true, moveView);
}
TTTMovePlayer winningPlayer;
TTTMoveXPosition startXPosition, endXPosition;
TTTMoveYPosition startYPosition, endYPosition;
bool hasWinner = Game.GetWinningPlayer (out winningPlayer,
out startXPosition,
out startYPosition,
out endXPosition,
out endYPosition);
if (hasWinner) {
UIBezierPath path = new UIBezierPath ();
path.LineWidth = LineWidth;
path.MoveTo (pointForPosition (startXPosition, startYPosition));
path.AddLineTo (pointForPosition (endXPosition, endYPosition));
lineView.Path = path;
lineView.Color = ColorForPlayer (this, winningPlayer);
AddSubview (lineView);
}
lineView.Alpha = hasWinner ? 1f : 0f;
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
CGRect bounds = Bounds;
for (int i = 0; i < horizontalLineViews.Length; i++) {
UIView view = horizontalLineViews [i];
view.Bounds = new CGRect (0, 0, bounds.Size.Width, LineWidth);
view.Center = new CGPoint (bounds.X + bounds.Size.Width / 2,
(float)Math.Round (bounds.Size.Height * (i + 1) / 3));
}
for (int i = 0; i < verticalLineViews.Length; i++) {
UIView view = verticalLineViews [i];
view.Bounds = new CGRect (0, 0, LineWidth, bounds.Size.Height);
view.Center = new CGPoint ((float)Math.Round (bounds.Size.Width * (i + 1) / 3),
bounds.Y + bounds.Size.Height / 2);
}
UpdateGameState ();
}
void updateGridColor ()
{
foreach (var view in horizontalLineViews)
view.BackgroundColor = GridColor;
foreach (var view in verticalLineViews)
view.BackgroundColor = GridColor;
}
}
public class TTTGameLineView : UIView
{
UIBezierPath path;
public UIBezierPath Path {
get { return path; }
set {
path = value;
shapeLayer.Path = Path.CGPath;
}
}
UIColor color;
public UIColor Color {
get { return color; }
set {
color = value;
shapeLayer.StrokeColor = color.CGColor;
}
}
public TTTGameLineView ()
{
shapeLayer.LineWidth = 2f;
}
[ExportAttribute ("layerClass")]
public static Class LayerClass ()
{
return new Class (typeof(CAShapeLayer));
}
CAShapeLayer shapeLayer {
get {
return (CAShapeLayer)Layer;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Performance;
namespace osu.Framework.Tests.Graphics
{
[TestFixture]
public class LifetimeEntryManagerTest
{
private TestLifetimeEntryManager manager;
[SetUp]
public void Setup()
{
manager = new TestLifetimeEntryManager();
}
[Test]
public void TestBasic()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 3 });
checkCountAliveAt(0, 3);
checkCountAliveAt(1, 2);
checkCountAliveAt(2, 1);
checkCountAliveAt(0, 3);
checkCountAliveAt(3, 0);
}
[Test]
public void TestRemoveAndReAdd()
{
var entry = new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 };
manager.AddEntry(entry);
checkCountAliveAt(0, 1);
manager.RemoveEntry(entry);
checkCountAliveAt(0, 0);
manager.AddEntry(entry);
checkCountAliveAt(0, 1);
}
[Test]
public void TestDynamicChange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 0 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
checkCountAliveAt(0, 2);
manager.Entries[0].LifetimeEnd = 1;
manager.Entries[1].LifetimeStart = 1;
manager.Entries[2].LifetimeEnd = 0;
manager.Entries[3].LifetimeStart = 0;
checkCountAliveAt(0, 2);
foreach (var entry in manager.Entries)
{
entry.LifetimeEnd += 1;
entry.LifetimeStart += 1;
}
checkCountAliveAt(0, 1);
foreach (var entry in manager.Entries)
{
entry.LifetimeStart -= 1;
entry.LifetimeEnd -= 1;
}
checkCountAliveAt(0, 2);
}
[Test]
public void TestBoundaryCrossing()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 0 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
// No crossings for the first update.
manager.Update(0);
checkNoCrossing(manager.Entries[0]);
checkNoCrossing(manager.Entries[1]);
checkNoCrossing(manager.Entries[2]);
manager.Update(2);
checkNoCrossing(manager.Entries[0]);
checkCrossing(manager.Entries[1], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward);
checkCrossing(manager.Entries[2], 0, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Forward);
checkCrossing(manager.Entries[2], 1, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Forward);
manager.Update(1);
checkNoCrossing(manager.Entries[0]);
checkNoCrossing(manager.Entries[1]);
checkCrossing(manager.Entries[2], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward);
manager.Update(-1);
checkCrossing(manager.Entries[0], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward);
checkCrossing(manager.Entries[1], 0, LifetimeBoundaryKind.End, LifetimeBoundaryCrossingDirection.Backward);
checkCrossing(manager.Entries[1], 1, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward);
checkCrossing(manager.Entries[2], 0, LifetimeBoundaryKind.Start, LifetimeBoundaryCrossingDirection.Backward);
}
[Test]
public void TestLifetimeChangeOnCallback()
{
int updateTime = 0;
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.EntryCrossedBoundary += (entry, kind, direction) =>
{
switch (kind)
{
case LifetimeBoundaryKind.End when direction == LifetimeBoundaryCrossingDirection.Forward:
entry.LifetimeEnd = 2;
break;
case LifetimeBoundaryKind.Start when direction == LifetimeBoundaryCrossingDirection.Backward:
entry.LifetimeEnd = 1;
break;
case LifetimeBoundaryKind.Start when direction == LifetimeBoundaryCrossingDirection.Forward:
entry.LifetimeStart = entry.LifetimeStart == 0 ? 1 : 0;
break;
}
// Lifetime changes are applied in the _next_ update.
// ReSharper disable once AccessToModifiedClosure - intentional.
manager.Update(updateTime);
};
manager.Update(updateTime = 0);
checkCountAliveAt(updateTime = 1, 1);
checkCountAliveAt(updateTime = -1, 0);
checkCountAliveAt(updateTime = 0, 0);
checkCountAliveAt(updateTime = 1, 1);
}
[Test]
public void TestUpdateWithTimeRange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -1, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 1 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 0, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 2 });
manager.AddEntry(new LifetimeEntry { LifetimeStart = 2, LifetimeEnd = 3 });
checkCountAliveAt(-3, -2, 0);
checkCountAliveAt(-3, -1, 1);
checkCountAliveAt(-2, 4, 6);
checkCountAliveAt(-1, 4, 6);
checkCountAliveAt(0, 4, 6);
checkCountAliveAt(1, 4, 4);
checkCountAliveAt(2, 4, 1);
checkCountAliveAt(3, 4, 0);
checkCountAliveAt(4, 4, 0);
}
[Test]
public void TestRemoveFutureAfterLifetimeChange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = 1, LifetimeEnd = 2 });
checkCountAliveAt(0, 0);
manager.Entries[0].LifetimeEnd = 3;
manager.RemoveEntry(manager.Entries[0]);
checkCountAliveAt(1, 0);
}
[Test]
public void TestRemovePastAfterLifetimeChange()
{
manager.AddEntry(new LifetimeEntry { LifetimeStart = -2, LifetimeEnd = -1 });
checkCountAliveAt(0, 0);
manager.Entries[0].LifetimeStart = -3;
manager.RemoveEntry(manager.Entries[0]);
checkCountAliveAt(-2, 0);
}
[Test]
public void TestFuzz()
{
var rng = new Random(2222);
int currentTime = 0;
addEntry();
manager.EntryCrossedBoundary += (entry, kind, direction) => changeLifetime();
manager.Update(0);
int count = 1;
for (int i = 0; i < 1000; i++)
{
switch (rng.Next(3))
{
case 0:
if (count < 20)
{
addEntry();
count += 1;
}
else
{
removeEntry();
count -= 1;
}
break;
case 1:
changeLifetime();
break;
case 2:
changeTime();
break;
}
}
void randomLifetime(out double l, out double r)
{
l = rng.Next(5);
r = rng.Next(5);
if (l > r)
(l, r) = (r, l);
++r;
}
// ReSharper disable once AccessToModifiedClosure - intentional.
void checkAll() => checkAlivenessAt(currentTime);
void addEntry()
{
randomLifetime(out double l, out double r);
manager.AddEntry(new LifetimeEntry { LifetimeStart = l, LifetimeEnd = r });
checkAll();
}
void removeEntry()
{
var entry = manager.Entries[rng.Next(manager.Entries.Count)];
manager.RemoveEntry(entry);
checkAll();
}
void changeLifetime()
{
var entry = manager.Entries[rng.Next(manager.Entries.Count)];
randomLifetime(out double l, out double r);
entry.LifetimeStart = l;
entry.LifetimeEnd = r;
checkAll();
}
void changeTime()
{
int time = rng.Next(6);
currentTime = time;
checkAll();
}
}
private void checkCountAliveAt(int time, int expectedCount) => checkCountAliveAt(time, time, expectedCount);
private void checkCountAliveAt(int startTime, int endTime, int expectedCount)
{
checkAlivenessAt(startTime, endTime);
Assert.That(manager.Entries.Count(entry => entry.State == LifetimeEntryState.Current), Is.EqualTo(expectedCount));
}
private void checkAlivenessAt(int time) => checkAlivenessAt(time, time);
private void checkAlivenessAt(int startTime, int endTime)
{
manager.Update(startTime, endTime);
for (int i = 0; i < manager.Entries.Count; i++)
{
var entry = manager.Entries[i];
bool isAlive = entry.State == LifetimeEntryState.Current;
bool shouldBeAlive = endTime >= entry.LifetimeStart && startTime < entry.LifetimeEnd;
Assert.That(isAlive, Is.EqualTo(shouldBeAlive), $"Aliveness is invalid for entry {i}");
}
}
private void checkNoCrossing(LifetimeEntry entry) => Assert.That(manager.Crossings, Does.Not.Contain(entry));
private void checkCrossing(LifetimeEntry entry, int index, LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)
=> Assert.That(manager.Crossings[entry][index], Is.EqualTo((kind, direction)));
private class TestLifetimeEntryManager : LifetimeEntryManager
{
public IReadOnlyList<LifetimeEntry> Entries => entries;
private readonly List<LifetimeEntry> entries = new List<LifetimeEntry>();
public IReadOnlyDictionary<LifetimeEntry, List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>> Crossings => crossings;
private readonly Dictionary<LifetimeEntry, List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>> crossings =
new Dictionary<LifetimeEntry, List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>>();
public TestLifetimeEntryManager()
{
EntryCrossedBoundary += (entry, kind, direction) =>
{
if (!crossings.ContainsKey(entry))
crossings[entry] = new List<(LifetimeBoundaryKind kind, LifetimeBoundaryCrossingDirection direction)>();
crossings[entry].Add((kind, direction));
};
}
public new void AddEntry(LifetimeEntry entry)
{
entries.Add(entry);
base.AddEntry(entry);
}
public new bool RemoveEntry(LifetimeEntry entry)
{
if (base.RemoveEntry(entry))
{
entries.Remove(entry);
return true;
}
return false;
}
public new void ClearEntries()
{
entries.Clear();
base.ClearEntries();
}
public new bool Update(double time)
{
crossings.Clear();
return base.Update(time);
}
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Klaus Potzesny
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace PdfSharp.Drawing.BarCodes
{
/// <summary>
/// Imlpementation of the Code 3 of 9 bar code.
/// </summary>
// ReSharper disable once InconsistentNaming
public class Code3of9Standard : ThickThinBarCode
{
/// <summary>
/// Initializes a new instance of Standard3of9.
/// </summary>
public Code3of9Standard()
: base("", XSize.Empty, CodeDirection.LeftToRight)
{ }
/// <summary>
/// Initializes a new instance of Standard3of9.
/// </summary>
public Code3of9Standard(string code)
: base(code, XSize.Empty, CodeDirection.LeftToRight)
{ }
/// <summary>
/// Initializes a new instance of Standard3of9.
/// </summary>
public Code3of9Standard(string code, XSize size)
: base(code, size, CodeDirection.LeftToRight)
{ }
/// <summary>
/// Initializes a new instance of Standard3of9.
/// </summary>
public Code3of9Standard(string code, XSize size, CodeDirection direction)
: base(code, size, direction)
{ }
/// <summary>
/// Returns an array of size 9 that represents the thick (true) and thin (false) lines and spaces
/// representing the specified digit.
/// </summary>
/// <param name="ch">The character to represent.</param>
private static bool[] ThickThinLines(char ch)
{
return Lines["0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*".IndexOf(ch)];
}
static readonly bool[][] Lines =
{
// '0'
new bool[] {false, false, false, true, true, false, true, false, false},
// '1'
new bool[] {true, false, false, true, false, false, false, false, true},
// '2'
new bool[] {false, false, true, true, false, false, false, false, true},
// '3'
new bool[] {true, false, true, true, false, false, false, false, false},
// '4'
new bool[] {false, false, false, true, true, false, false, false, true},
// '5'
new bool[] {true, false, false, true, true, false, false, false, false},
// '6'
new bool[] {false, false, true, true, true, false, false, false, false},
// '7'
new bool[] {false, false, false, true, false, false, true, false, true},
// '8'
new bool[] {true, false, false, true, false, false, true, false, false},
// '9'
new bool[] {false, false, true, true, false, false, true, false, false},
// 'A'
new bool[] {true, false, false, false, false, true, false, false, true},
// 'B'
new bool[] {false, false, true, false, false, true, false, false, true},
// 'C'
new bool[] {true, false, true, false, false, true, false, false, false},
// 'D'
new bool[] {false, false, false, false, true, true, false, false, true},
// 'E'
new bool[] {true, false, false, false, true, true, false, false, false},
// 'F'
new bool[] {false, false, true, false, true, true, false, false, false},
// 'G'
new bool[] {false, false, false, false, false, true, true, false, true},
// 'H'
new bool[] {true, false, false, false, false, true, true, false, false},
// 'I'
new bool[] {false, false, true, false, false, true, true, false, false},
// 'J'
new bool[] {false, false, false, false, true, true, true, false, false},
// 'K'
new bool[] {true, false, false, false, false, false, false, true, true},
// 'L'
new bool[] {false, false, true, false, false, false, false, true, true},
// 'M'
new bool[] {true, false, true, false, false, false, false, true, false},
// 'N'
new bool[] {false, false, false, false, true, false, false, true, true},
// 'O'
new bool[] {true, false, false, false, true, false, false, true, false},
// 'P':
new bool[] {false, false, true, false, true, false, false, true, false},
// 'Q'
new bool[] {false, false, false, false, false, false, true, true, true},
// 'R'
new bool[] {true, false, false, false, false, false, true, true, false},
// 'S'
new bool[] {false, false, true, false, false, false, true, true, false},
// 'T'
new bool[] {false, false, false, false, true, false, true, true, false},
// 'U'
new bool[] {true, true, false, false, false, false, false, false, true},
// 'V'
new bool[] {false, true, true, false, false, false, false, false, true},
// 'W'
new bool[] {true, true, true, false, false, false, false, false, false},
// 'X'
new bool[] {false, true, false, false, true, false, false, false, true},
// 'Y'
new bool[] {true, true, false, false, true, false, false, false, false},
// 'Z'
new bool[] {false, true, true, false, true, false, false, false, false},
// '-'
new bool[] {false, true, false, false, false, false, true, false, true},
// '.'
new bool[] {true, true, false, false, false, false, true, false, false},
// ' '
new bool[] {false, true, true, false, false, false, true, false, false},
// '$'
new bool[] {false, true, false, true, false, true, false, false, false},
// '/'
new bool[] {false, true, false, true, false, false, false, true, false},
// '+'
new bool[] {false, true, false, false, false, true, false, true, false},
// '%'
new bool[] {false, false, false, true, false, true, false, true, false},
// '*'
new bool[] {false, true, false, false, true, false, true, false, false},
};
/// <summary>
/// Calculates the thick and thin line widths,
/// taking into account the required rendering size.
/// </summary>
internal override void CalcThinBarWidth(BarCodeRenderInfo info)
{
/*
* The total width is the sum of the following parts:
* Starting lines = 3 * thick + 7 * thin
* +
* Code Representation = (3 * thick + 7 * thin) * code.Length
* +
* Stopping lines = 3 * thick + 6 * thin
*
* with r = relation ( = thick / thin), this results in
*
* Total width = (13 + 6 * r + (3 * r + 7) * code.Length) * thin
*/
double thinLineAmount = 13 + 6 * WideNarrowRatio + (3 * WideNarrowRatio + 7) * Text.Length;
info.ThinBarWidth = Size.Width / thinLineAmount;
}
/// <summary>
/// Checks the code to be convertible into an standard 3 of 9 bar code.
/// </summary>
/// <param name="text">The code to be checked.</param>
protected override void CheckCode(string text)
{
if (text == null)
throw new ArgumentNullException("text");
if (text.Length == 0)
throw new ArgumentException(BcgSR.Invalid3Of9Code(text));
foreach (char ch in text)
{
if ("0123456789ABCDEFGHIJKLMNOP'QRSTUVWXYZ-. $/+%*".IndexOf(ch) < 0)
throw new ArgumentException(BcgSR.Invalid3Of9Code(text));
}
}
/// <summary>
/// Renders the bar code.
/// </summary>
protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position)
{
XGraphicsState state = gfx.Save();
BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position);
InitRendering(info);
info.CurrPosInString = 0;
//info.CurrPos = Center - Size / 2;
info.CurrPos = position - CalcDistance(AnchorType.TopLeft, Anchor, Size);
if (TurboBit)
RenderTurboBit(info, true);
RenderStart(info);
while (info.CurrPosInString < Text.Length)
{
RenderNextChar(info);
RenderGap(info, false);
}
RenderStop(info);
if (TurboBit)
RenderTurboBit(info, false);
if (TextLocation != TextLocation.None)
RenderText(info);
gfx.Restore(state);
}
private void RenderNextChar(BarCodeRenderInfo info)
{
RenderChar(info, Text[info.CurrPosInString]);
++info.CurrPosInString;
}
private void RenderChar(BarCodeRenderInfo info, char ch)
{
bool[] thickThinLines = ThickThinLines(ch);
int idx = 0;
while (idx < 9)
{
RenderBar(info, thickThinLines[idx]);
if (idx < 8)
RenderGap(info, thickThinLines[idx + 1]);
idx += 2;
}
}
private void RenderStart(BarCodeRenderInfo info)
{
RenderChar(info, '*');
RenderGap(info, false);
}
private void RenderStop(BarCodeRenderInfo info)
{
RenderChar(info, '*');
}
}
}
| |
/*
* 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.Impl.Portable
{
using System;
using System.Collections.Generic;
using System.IO;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Portable.IO;
using Apache.Ignite.Core.Impl.Portable.Metadata;
using Apache.Ignite.Core.Portable;
/// <summary>
/// Portable builder implementation.
/// </summary>
internal class PortableBuilderImpl : IPortableBuilder
{
/** Type IDs for metadata. */
private static readonly IDictionary<Type, int> TypeIds;
/** Cached dictionary with no values. */
private static readonly IDictionary<int, object> EmptyVals = new Dictionary<int, object>();
/** Offset: length. */
private const int OffsetLen = 10;
/** Portables. */
private readonly PortablesImpl _portables;
/** */
private readonly PortableBuilderImpl _parent;
/** Initial portable object. */
private readonly PortableUserObject _obj;
/** Type descriptor. */
private readonly IPortableTypeDescriptor _desc;
/** Values. */
private IDictionary<string, PortableBuilderField> _vals;
/** Contextual fields. */
private IDictionary<int, object> _cache;
/** Hash code. */
private int _hashCode;
/** Current context. */
private Context _ctx;
/// <summary>
/// Static initializer.
/// </summary>
static PortableBuilderImpl()
{
TypeIds = new Dictionary<Type, int>();
// 1. Primitives.
TypeIds[typeof(byte)] = PortableUtils.TypeByte;
TypeIds[typeof(bool)] = PortableUtils.TypeBool;
TypeIds[typeof(short)] = PortableUtils.TypeShort;
TypeIds[typeof(char)] = PortableUtils.TypeChar;
TypeIds[typeof(int)] = PortableUtils.TypeInt;
TypeIds[typeof(long)] = PortableUtils.TypeLong;
TypeIds[typeof(float)] = PortableUtils.TypeFloat;
TypeIds[typeof(double)] = PortableUtils.TypeDouble;
TypeIds[typeof(decimal)] = PortableUtils.TypeDecimal;
TypeIds[typeof(byte[])] = PortableUtils.TypeArrayByte;
TypeIds[typeof(bool[])] = PortableUtils.TypeArrayBool;
TypeIds[typeof(short[])] = PortableUtils.TypeArrayShort;
TypeIds[typeof(char[])] = PortableUtils.TypeArrayChar;
TypeIds[typeof(int[])] = PortableUtils.TypeArrayInt;
TypeIds[typeof(long[])] = PortableUtils.TypeArrayLong;
TypeIds[typeof(float[])] = PortableUtils.TypeArrayFloat;
TypeIds[typeof(double[])] = PortableUtils.TypeArrayDouble;
TypeIds[typeof(decimal[])] = PortableUtils.TypeArrayDecimal;
// 2. String.
TypeIds[typeof(string)] = PortableUtils.TypeString;
TypeIds[typeof(string[])] = PortableUtils.TypeArrayString;
// 3. Guid.
TypeIds[typeof(Guid)] = PortableUtils.TypeGuid;
TypeIds[typeof(Guid?)] = PortableUtils.TypeGuid;
TypeIds[typeof(Guid[])] = PortableUtils.TypeArrayGuid;
TypeIds[typeof(Guid?[])] = PortableUtils.TypeArrayGuid;
// 4. Date.
TypeIds[typeof(DateTime)] = PortableUtils.TypeDate;
TypeIds[typeof(DateTime?)] = PortableUtils.TypeDate;
TypeIds[typeof(DateTime[])] = PortableUtils.TypeArrayDate;
TypeIds[typeof(DateTime?[])] = PortableUtils.TypeArrayDate;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="portables">Portables.</param>
/// <param name="obj">Initial portable object.</param>
/// <param name="desc">Type descriptor.</param>
public PortableBuilderImpl(PortablesImpl portables, PortableUserObject obj,
IPortableTypeDescriptor desc) : this(portables, null, obj, desc)
{
// No-op.
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="portables">Portables.</param>
/// <param name="parent">Parent builder.</param>
/// <param name="obj">Initial portable object.</param>
/// <param name="desc">Type descriptor.</param>
public PortableBuilderImpl(PortablesImpl portables, PortableBuilderImpl parent,
PortableUserObject obj, IPortableTypeDescriptor desc)
{
_portables = portables;
_parent = parent ?? this;
_obj = obj;
_desc = desc;
_hashCode = obj.GetHashCode();
}
/** <inheritDoc /> */
public IPortableBuilder HashCode(int hashCode)
{
_hashCode = hashCode;
return this;
}
/** <inheritDoc /> */
public T GetField<T>(string name)
{
PortableBuilderField field;
if (_vals != null && _vals.TryGetValue(name, out field))
return field != PortableBuilderField.RmvMarker ? (T)field.Value : default(T);
T val = _obj.Field<T>(name, this);
if (_vals == null)
_vals = new Dictionary<string, PortableBuilderField>(2);
_vals[name] = new PortableBuilderField(typeof(T), val);
return val;
}
/** <inheritDoc /> */
public IPortableBuilder SetField<T>(string name, T val)
{
return SetField0(name, new PortableBuilderField(typeof(T), val));
}
/** <inheritDoc /> */
public IPortableBuilder RemoveField(string name)
{
return SetField0(name, PortableBuilderField.RmvMarker);
}
/** <inheritDoc /> */
public IPortableObject Build()
{
PortableHeapStream inStream = new PortableHeapStream(_obj.Data);
inStream.Seek(_obj.Offset, SeekOrigin.Begin);
// Assume that resulting length will be no less than header + [fields_cnt] * 12;
int len = PortableUtils.FullHdrLen + (_vals == null ? 0 : _vals.Count * 12);
PortableHeapStream outStream = new PortableHeapStream(len);
PortableWriterImpl writer = _portables.Marshaller.StartMarshal(outStream);
writer.Builder(this);
// All related builders will work in this context with this writer.
_parent._ctx = new Context(writer);
try
{
// Write.
writer.Write(this, null);
// Process metadata.
_portables.Marshaller.FinishMarshal(writer);
// Create portable object once metadata is processed.
return new PortableUserObject(_portables.Marshaller, outStream.InternalArray, 0,
_desc.TypeId, _hashCode);
}
finally
{
// Cleanup.
_parent._ctx.Closed = true;
}
}
/// <summary>
/// Create child builder.
/// </summary>
/// <param name="obj">Portable object.</param>
/// <returns>Child builder.</returns>
public PortableBuilderImpl Child(PortableUserObject obj)
{
return _portables.ChildBuilder(_parent, obj);
}
/// <summary>
/// Get cache field.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
/// <returns><c>true</c> if value is found in cache.</returns>
public bool CachedField<T>(int pos, out T val)
{
if (_parent._cache != null)
{
object res;
if (_parent._cache.TryGetValue(pos, out res))
{
val = res != null ? (T)res : default(T);
return true;
}
}
val = default(T);
return false;
}
/// <summary>
/// Add field to cache test.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
public void CacheField(int pos, object val)
{
if (_parent._cache == null)
_parent._cache = new Dictionary<int, object>(2);
_parent._cache[pos] = val;
}
/// <summary>
/// Internal set field routine.
/// </summary>
/// <param name="fieldName">Name.</param>
/// <param name="val">Value.</param>
/// <returns>This builder.</returns>
private IPortableBuilder SetField0(string fieldName, PortableBuilderField val)
{
if (_vals == null)
_vals = new Dictionary<string, PortableBuilderField>();
_vals[fieldName] = val;
return this;
}
/// <summary>
/// Mutate portable object.
/// </summary>
/// <param name="inStream">Input stream with initial object.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="desc">Portable type descriptor.</param>
/// <param name="hashCode">Hash code.</param>
/// <param name="vals">Values.</param>
internal void Mutate(
PortableHeapStream inStream,
PortableHeapStream outStream,
IPortableTypeDescriptor desc,
int hashCode,
IDictionary<string, PortableBuilderField> vals)
{
// Set correct builder to writer frame.
PortableBuilderImpl oldBuilder = _parent._ctx.Writer.Builder(_parent);
int streamPos = inStream.Position;
try
{
// Prepare fields.
IPortableMetadataHandler metaHnd = _portables.Marshaller.MetadataHandler(desc);
IDictionary<int, object> vals0;
if (vals == null || vals.Count == 0)
vals0 = EmptyVals;
else
{
vals0 = new Dictionary<int, object>(vals.Count);
foreach (KeyValuePair<string, PortableBuilderField> valEntry in vals)
{
int fieldId = PortableUtils.FieldId(desc.TypeId, valEntry.Key, desc.NameConverter, desc.Mapper);
if (vals0.ContainsKey(fieldId))
throw new IgniteException("Collision in field ID detected (change field name or " +
"define custom ID mapper) [fieldName=" + valEntry.Key + ", fieldId=" + fieldId + ']');
vals0[fieldId] = valEntry.Value.Value;
// Write metadata if: 1) it is enabled for type; 2) type is not null (i.e. it is neither
// remove marker, nor a field read through "GetField" method.
if (metaHnd != null && valEntry.Value.Type != null)
metaHnd.OnFieldWrite(fieldId, valEntry.Key, TypeId(valEntry.Value.Type));
}
}
// Actual processing.
Mutate0(_parent._ctx, inStream, outStream, true, hashCode, vals0);
// 3. Handle metadata.
if (metaHnd != null)
{
IDictionary<string, int> meta = metaHnd.OnObjectWriteFinished();
if (meta != null)
_parent._ctx.Writer.SaveMetadata(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName, meta);
}
}
finally
{
// Restore builder frame.
_parent._ctx.Writer.Builder(oldBuilder);
inStream.Seek(streamPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Internal mutation routine.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <param name="changeHash">WHether hash should be changed.</param>
/// <param name="hash">New hash.</param>
/// <param name="vals">Values to be replaced.</param>
/// <returns>Mutated object.</returns>
private void Mutate0(Context ctx, PortableHeapStream inStream, IPortableStream outStream,
bool changeHash, int hash, IDictionary<int, object> vals)
{
int inStartPos = inStream.Position;
int outStartPos = outStream.Position;
byte inHdr = inStream.ReadByte();
if (inHdr == PortableUtils.HdrNull)
outStream.WriteByte(PortableUtils.HdrNull);
else if (inHdr == PortableUtils.HdrHnd)
{
int inHnd = inStream.ReadInt();
int oldPos = inStartPos - inHnd;
int newPos;
if (ctx.OldToNew(oldPos, out newPos))
{
// Handle is still valid.
outStream.WriteByte(PortableUtils.HdrHnd);
outStream.WriteInt(outStartPos - newPos);
}
else
{
// Handle is invalid, write full object.
int inRetPos = inStream.Position;
inStream.Seek(oldPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
inStream.Seek(inRetPos, SeekOrigin.Begin);
}
}
else if (inHdr == PortableUtils.HdrFull)
{
byte inUsrFlag = inStream.ReadByte();
int inTypeId = inStream.ReadInt();
int inHash = inStream.ReadInt();
int inLen = inStream.ReadInt();
int inRawOff = inStream.ReadInt();
int hndPos;
if (ctx.AddOldToNew(inStartPos, outStartPos, out hndPos))
{
// Object could be cached in parent builder.
object cachedVal;
if (_parent._cache != null && _parent._cache.TryGetValue(inStartPos, out cachedVal)) {
ctx.Writer.Write(cachedVal, null);
}
else
{
// New object, write in full form.
outStream.WriteByte(PortableUtils.HdrFull);
outStream.WriteByte(inUsrFlag);
outStream.WriteInt(inTypeId);
outStream.WriteInt(changeHash ? hash : inHash);
// Skip length and raw offset as they are not known at this point.
outStream.Seek(8, SeekOrigin.Current);
// Write regular fields.
while (inStream.Position < inStartPos + inRawOff)
{
int inFieldId = inStream.ReadInt();
int inFieldLen = inStream.ReadInt();
int inFieldDataPos = inStream.Position;
object fieldVal;
bool fieldFound = vals.TryGetValue(inFieldId, out fieldVal);
if (!fieldFound || fieldVal != PortableBuilderField.RmvMarkerObj)
{
outStream.WriteInt(inFieldId);
int fieldLenPos = outStream.Position; // Here we will write length later.
outStream.Seek(4, SeekOrigin.Current);
if (fieldFound)
{
// Replace field with new value.
if (fieldVal != PortableBuilderField.RmvMarkerObj)
ctx.Writer.Write(fieldVal, null);
vals.Remove(inFieldId);
}
else
{
// If field was requested earlier, then we must write tracked value
if (_parent._cache != null && _parent._cache.TryGetValue(inFieldDataPos, out fieldVal))
ctx.Writer.Write(fieldVal, null);
else
// Filed is not tracked, re-write as is.
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
}
int fieldEndPos = outStream.Position;
outStream.Seek(fieldLenPos, SeekOrigin.Begin);
outStream.WriteInt(fieldEndPos - fieldLenPos - 4);
outStream.Seek(fieldEndPos, SeekOrigin.Begin);
}
// Position intput stream pointer after the field.
inStream.Seek(inFieldDataPos + inFieldLen, SeekOrigin.Begin);
}
// Write remaining new fields.
foreach (KeyValuePair<int, object> valEntry in vals)
{
if (valEntry.Value != PortableBuilderField.RmvMarkerObj)
{
outStream.WriteInt(valEntry.Key);
int fieldLenPos = outStream.Position; // Here we will write length later.
outStream.Seek(4, SeekOrigin.Current);
ctx.Writer.Write(valEntry.Value, null);
int fieldEndPos = outStream.Position;
outStream.Seek(fieldLenPos, SeekOrigin.Begin);
outStream.WriteInt(fieldEndPos - fieldLenPos - 4);
outStream.Seek(fieldEndPos, SeekOrigin.Begin);
}
}
// Write raw data.
int rawPos = outStream.Position;
outStream.Write(inStream.InternalArray, inStartPos + inRawOff, inLen - inRawOff);
// Write length and raw data offset.
int outResPos = outStream.Position;
outStream.Seek(outStartPos + OffsetLen, SeekOrigin.Begin);
outStream.WriteInt(outResPos - outStartPos); // Length.
outStream.WriteInt(rawPos - outStartPos); // Raw offset.
outStream.Seek(outResPos, SeekOrigin.Begin);
}
}
else
{
// Object has already been written, write as handle.
outStream.WriteByte(PortableUtils.HdrHnd);
outStream.WriteInt(outStartPos - hndPos);
}
// Synchronize input stream position.
inStream.Seek(inStartPos + inLen, SeekOrigin.Begin);
}
else
{
// Try writing as well-known type with fixed size.
outStream.WriteByte(inHdr);
if (!WriteAsPredefined(inHdr, inStream, outStream, ctx))
throw new IgniteException("Unexpected header [position=" + (inStream.Position - 1) +
", header=" + inHdr + ']');
}
}
/// <summary>
/// Process portable object inverting handles if needed.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="port">Portable.</param>
internal void ProcessPortable(IPortableStream outStream, PortableUserObject port)
{
// Special case: writing portable object with correct inversions.
PortableHeapStream inStream = new PortableHeapStream(port.Data);
inStream.Seek(port.Offset, SeekOrigin.Begin);
// Use fresh context to ensure correct portable inversion.
Mutate0(new Context(), inStream, outStream, false, 0, EmptyVals);
}
/// <summary>
/// Process child builder.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="builder">Builder.</param>
internal void ProcessBuilder(IPortableStream outStream, PortableBuilderImpl builder)
{
PortableHeapStream inStream = new PortableHeapStream(builder._obj.Data);
inStream.Seek(builder._obj.Offset, SeekOrigin.Begin);
// Builder parent context might be null only in one case: if we never met this group of
// builders before. In this case we set context to their parent and track it. Context
// cleanup will be performed at the very end of build process.
if (builder._parent._ctx == null || builder._parent._ctx.Closed)
builder._parent._ctx = new Context(_parent._ctx);
builder.Mutate(inStream, outStream as PortableHeapStream, builder._desc,
builder._hashCode, builder._vals);
}
/// <summary>
/// Write object as a predefined type if possible.
/// </summary>
/// <param name="hdr">Header.</param>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <returns><c>True</c> if was written.</returns>
private bool WriteAsPredefined(byte hdr, PortableHeapStream inStream, IPortableStream outStream,
Context ctx)
{
switch (hdr)
{
case PortableUtils.TypeByte:
TransferBytes(inStream, outStream, 1);
break;
case PortableUtils.TypeShort:
TransferBytes(inStream, outStream, 2);
break;
case PortableUtils.TypeInt:
TransferBytes(inStream, outStream, 4);
break;
case PortableUtils.TypeLong:
TransferBytes(inStream, outStream, 8);
break;
case PortableUtils.TypeFloat:
TransferBytes(inStream, outStream, 4);
break;
case PortableUtils.TypeDouble:
TransferBytes(inStream, outStream, 8);
break;
case PortableUtils.TypeChar:
TransferBytes(inStream, outStream, 2);
break;
case PortableUtils.TypeBool:
TransferBytes(inStream, outStream, 1);
break;
case PortableUtils.TypeDecimal:
TransferBytes(inStream, outStream, 4); // Transfer scale
int magLen = inStream.ReadInt(); // Transfer magnitude length.
outStream.WriteInt(magLen);
TransferBytes(inStream, outStream, magLen); // Transfer magnitude.
break;
case PortableUtils.TypeString:
PortableUtils.WriteString(PortableUtils.ReadString(inStream), outStream);
break;
case PortableUtils.TypeGuid:
TransferBytes(inStream, outStream, 16);
break;
case PortableUtils.TypeDate:
TransferBytes(inStream, outStream, 12);
break;
case PortableUtils.TypeArrayByte:
TransferArray(inStream, outStream, 1);
break;
case PortableUtils.TypeArrayShort:
TransferArray(inStream, outStream, 2);
break;
case PortableUtils.TypeArrayInt:
TransferArray(inStream, outStream, 4);
break;
case PortableUtils.TypeArrayLong:
TransferArray(inStream, outStream, 8);
break;
case PortableUtils.TypeArrayFloat:
TransferArray(inStream, outStream, 4);
break;
case PortableUtils.TypeArrayDouble:
TransferArray(inStream, outStream, 8);
break;
case PortableUtils.TypeArrayChar:
TransferArray(inStream, outStream, 2);
break;
case PortableUtils.TypeArrayBool:
TransferArray(inStream, outStream, 1);
break;
case PortableUtils.TypeArrayDecimal:
case PortableUtils.TypeArrayString:
case PortableUtils.TypeArrayGuid:
case PortableUtils.TypeArrayDate:
case PortableUtils.TypeArrayEnum:
case PortableUtils.TypeArray:
int arrLen = inStream.ReadInt();
outStream.WriteInt(arrLen);
for (int i = 0; i < arrLen; i++)
Mutate0(ctx, inStream, outStream, false, 0, null);
break;
case PortableUtils.TypeCollection:
int colLen = inStream.ReadInt();
outStream.WriteInt(colLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < colLen; i++)
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
break;
case PortableUtils.TypeDictionary:
int dictLen = inStream.ReadInt();
outStream.WriteInt(dictLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < dictLen; i++)
{
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
}
break;
case PortableUtils.TypeMapEntry:
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
break;
case PortableUtils.TypePortable:
TransferArray(inStream, outStream, 1); // Data array.
TransferBytes(inStream, outStream, 4); // Offset in array.
break;
case PortableUtils.TypeEnum:
TransferBytes(inStream, outStream, 4); // Integer ordinal.
break;
default:
return false;
}
return true;
}
/// <summary>
/// Get's metadata field type ID for the given type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Type ID.</returns>
private static int TypeId(Type type)
{
int typeId;
if (TypeIds.TryGetValue(type, out typeId))
return typeId;
if (type.IsEnum)
return PortableUtils.TypeEnum;
if (type.IsArray)
return type.GetElementType().IsEnum ? PortableUtils.TypeArrayEnum : PortableUtils.TypeArray;
PortableCollectionInfo colInfo = PortableCollectionInfo.Info(type);
return colInfo.IsAny ? colInfo.IsCollection || colInfo.IsGenericCollection ?
PortableUtils.TypeCollection : PortableUtils.TypeDictionary : PortableUtils.TypeObject;
}
/// <summary>
/// Transfer bytes from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="cnt">Bytes count.</param>
private static void TransferBytes(PortableHeapStream inStream, IPortableStream outStream, int cnt)
{
outStream.Write(inStream.InternalArray, inStream.Position, cnt);
inStream.Seek(cnt, SeekOrigin.Current);
}
/// <summary>
/// Transfer array of fixed-size elements from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="elemSize">Element size.</param>
private static void TransferArray(PortableHeapStream inStream, IPortableStream outStream,
int elemSize)
{
int len = inStream.ReadInt();
outStream.WriteInt(len);
TransferBytes(inStream, outStream, elemSize * len);
}
/// <summary>
/// Mutation ocntext.
/// </summary>
private class Context
{
/** Map from object position in old portable to position in new portable. */
private IDictionary<int, int> _oldToNew;
/** Parent context. */
private readonly Context _parent;
/** Portable writer. */
private readonly PortableWriterImpl _writer;
/** Children contexts. */
private ICollection<Context> _children;
/** Closed flag; if context is closed, it can no longer be used. */
private bool _closed;
/// <summary>
/// Constructor for parent context where writer invocation is not expected.
/// </summary>
public Context()
{
// No-op.
}
/// <summary>
/// Constructor for parent context.
/// </summary>
/// <param name="writer">Writer</param>
public Context(PortableWriterImpl writer)
{
_writer = writer;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="parent">Parent context.</param>
public Context(Context parent)
{
_parent = parent;
_writer = parent._writer;
if (parent._children == null)
parent._children = new List<Context>();
parent._children.Add(this);
}
/// <summary>
/// Add another old-to-new position mapping.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <param name="hndPos">Handle position.</param>
/// <returns><c>True</c> if ampping was added, <c>false</c> if mapping already existed and handle
/// position in the new object is returned.</returns>
public bool AddOldToNew(int oldPos, int newPos, out int hndPos)
{
if (_oldToNew == null)
_oldToNew = new Dictionary<int, int>();
if (_oldToNew.TryGetValue(oldPos, out hndPos))
return false;
_oldToNew[oldPos] = newPos;
return true;
}
/// <summary>
/// Get mapping of old position to the new one.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <returns><c>True</c> if mapping exists.</returns>
public bool OldToNew(int oldPos, out int newPos)
{
return _oldToNew.TryGetValue(oldPos, out newPos);
}
/// <summary>
/// Writer.
/// </summary>
public PortableWriterImpl Writer
{
get { return _writer; }
}
/// <summary>
/// Closed flag.
/// </summary>
public bool Closed
{
get
{
return _closed;
}
set
{
Context ctx = this;
while (ctx != null)
{
ctx._closed = value;
if (_children != null) {
foreach (Context child in _children)
child.Closed = value;
}
ctx = ctx._parent;
}
}
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using EnvDTE;
using Microsoft.VisualStudio.ExtensionsExplorer.UI;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.Dialog.PackageManagerUI;
using NuGet.Dialog.Providers;
using NuGet.VisualStudio;
namespace NuGet.Dialog
{
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public partial class PackageManagerWindow : DialogWindow
{
internal static PackageManagerWindow CurrentInstance;
private const string DialogUserAgentClient = "NuGet VS Packages Dialog";
private const string DialogForSolutionUserAgentClient = "NuGet VS Packages Dialog - Solution";
private readonly Lazy<string> _dialogUserAgent = new Lazy<string>(
() => HttpUtility.CreateUserAgentString(DialogUserAgentClient, VsVersionHelper.FullVsEdition));
private readonly Lazy<string> _dialogForSolutionUserAgent = new Lazy<string>(
() => HttpUtility.CreateUserAgentString(DialogForSolutionUserAgentClient, VsVersionHelper.FullVsEdition));
private static readonly string[] Providers = new string[] { "Installed", "Online", "Updates" };
private const string SearchInSwitch = "/searchin:";
private const string F1Keyword = "vs.ExtensionManager";
private readonly IHttpClientEvents _httpClientEvents;
private bool _hasOpenedOnlineProvider;
private ComboBox _prereleaseComboBox;
private readonly SmartOutputConsoleProvider _smartOutputConsoleProvider;
private readonly IProviderSettings _providerSettings;
private readonly IProductUpdateService _productUpdateService;
private readonly IOptionsPageActivator _optionsPageActivator;
private readonly IUpdateAllUIService _updateAllUIService;
private readonly Project _activeProject;
private readonly string _projectGuids;
private string _searchText;
private ProductUpdateBar _updateBar = null;
private PackageRestoreBar _restoreBar;
public PackageManagerWindow(Project project, string dialogParameters = null) :
this(project,
ServiceLocator.GetInstance<DTE>(),
ServiceLocator.GetInstance<IVsPackageManagerFactory>(),
ServiceLocator.GetInstance<IPackageRepositoryFactory>(),
ServiceLocator.GetInstance<IPackageSourceProvider>(),
ServiceLocator.GetInstance<IHttpClientEvents>(),
ServiceLocator.GetInstance<IProductUpdateService>(),
ServiceLocator.GetInstance<IPackageRestoreManager>(),
ServiceLocator.GetInstance<ISolutionManager>(),
ServiceLocator.GetInstance<IOptionsPageActivator>(),
ServiceLocator.GetInstance<IDeleteOnRestartManager>(),
ServiceLocator.GetGlobalService<SVsShell, IVsShell4>(),
dialogParameters)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
private PackageManagerWindow(Project project,
DTE dte,
IVsPackageManagerFactory packageManagerFactory,
IPackageRepositoryFactory repositoryFactory,
IPackageSourceProvider packageSourceProvider,
IHttpClientEvents httpClientEvents,
IProductUpdateService productUpdateService,
IPackageRestoreManager packageRestoreManager,
ISolutionManager solutionManager,
IOptionsPageActivator optionPageActivator,
IDeleteOnRestartManager deleteOnRestartManager,
IVsShell4 vsRestarter,
string dialogParameters)
: base(F1Keyword)
{
InitializeComponent();
#if !VS10
// set unique search guid for VS11
explorer.SearchCategory = new Guid("{85566D5F-E585-411F-B299-5BF006E9F11E}");
#endif
_httpClientEvents = httpClientEvents;
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest += OnSendingRequest;
}
_productUpdateService = productUpdateService;
_optionsPageActivator = optionPageActivator;
_activeProject = project;
// replace the ConsoleOutputProvider with SmartOutputConsoleProvider so that we can clear
// the console the first time an entry is written to it
var providerServices = new ProviderServices();
_smartOutputConsoleProvider = new SmartOutputConsoleProvider(providerServices.OutputConsoleProvider);
_smartOutputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false);
_smartOutputConsoleProvider.Clear();
providerServices.OutputConsoleProvider = _smartOutputConsoleProvider;
_providerSettings = providerServices.ProviderSettings;
_updateAllUIService = providerServices.UpdateAllUIService;
providerServices.ProgressWindow.UpgradeNuGetRequested += (_, __) =>
{
Close();
productUpdateService.Update();
};
_projectGuids = _activeProject == null ? null : _activeProject.GetAllProjectTypeGuid();
AddUpdateBar(productUpdateService);
AddRestoreBar(packageRestoreManager);
var restartRequestBar = AddRestartRequestBar(deleteOnRestartManager, vsRestarter);
InsertDisclaimerElement();
AdjustSortComboBoxWidth();
PreparePrereleaseComboBox();
InsertUpdateAllButton(providerServices.UpdateAllUIService);
SetupProviders(
project,
dte,
packageManagerFactory,
repositoryFactory,
packageSourceProvider,
providerServices,
httpClientEvents,
solutionManager,
packageRestoreManager,
restartRequestBar);
ProcessDialogParameters(dialogParameters);
}
/// <summary>
/// Project.ManageNuGetPackages supports 1 optional argument and 1 optional switch /searchin. /searchin Switch has to be provided at the end
/// If the provider specified in the optional switch is not valid, then the provider entered is ignored
/// </summary>
/// <param name="dialogParameters"></param>
private void ProcessDialogParameters(string dialogParameters)
{
bool providerSet = false;
if (dialogParameters != null)
{
dialogParameters = dialogParameters.Trim();
int lastIndexOfSearchInSwitch = dialogParameters.LastIndexOf(SearchInSwitch, StringComparison.OrdinalIgnoreCase);
if (lastIndexOfSearchInSwitch == -1)
{
_searchText = dialogParameters;
}
else
{
_searchText = dialogParameters.Substring(0, lastIndexOfSearchInSwitch);
// At this point, we know that /searchin: exists in the string.
// Check if there is content following the switch
if (dialogParameters.Length > (lastIndexOfSearchInSwitch + SearchInSwitch.Length))
{
// At this point, we know that there is some content following the /searchin: switch
// Check if it represents a valid provider. Otherwise, don't set the provider here
// Note that at the end of the method the provider from the settings will be used if no valid provider was determined
string provider = dialogParameters.Substring(lastIndexOfSearchInSwitch + SearchInSwitch.Length);
for (int i = 0; i < Providers.Length; i++)
{
// Case insensitive comparisons with the strings
if (String.Equals(Providers[i], provider, StringComparison.OrdinalIgnoreCase))
{
UpdateSelectedProvider(i);
providerSet = true;
break;
}
}
}
}
}
if (!providerSet)
{
// retrieve the selected provider from the settings
UpdateSelectedProvider(_providerSettings.SelectedProvider);
}
if (!String.IsNullOrEmpty(_searchText))
{
var selectedProvider = explorer.SelectedProvider as PackagesProviderBase;
selectedProvider.SuppressLoad = true;
}
}
private void AddUpdateBar(IProductUpdateService productUpdateService)
{
_updateBar = new ProductUpdateBar(productUpdateService);
_updateBar.UpdateStarting += ExecutedClose;
LayoutRoot.Children.Add(_updateBar);
_updateBar.SizeChanged += OnHeaderBarSizeChanged;
}
private void RemoveUpdateBar()
{
if (_updateBar != null)
{
LayoutRoot.Children.Remove(_updateBar);
_updateBar.CleanUp();
_updateBar.UpdateStarting -= ExecutedClose;
_updateBar.SizeChanged -= OnHeaderBarSizeChanged;
_updateBar = null;
}
}
private void AddRestoreBar(IPackageRestoreManager packageRestoreManager)
{
_restoreBar = new PackageRestoreBar(packageRestoreManager);
LayoutRoot.Children.Add(_restoreBar);
_restoreBar.SizeChanged += OnHeaderBarSizeChanged;
}
private void RemoveRestoreBar()
{
if (_restoreBar != null)
{
LayoutRoot.Children.Remove(_restoreBar);
_restoreBar.CleanUp();
_restoreBar.SizeChanged -= OnHeaderBarSizeChanged;
_restoreBar = null;
}
}
private RestartRequestBar AddRestartRequestBar(IDeleteOnRestartManager deleteOnRestartManager, IVsShell4 vsRestarter)
{
var restartRequestBar = new RestartRequestBar(deleteOnRestartManager, vsRestarter);
Grid.SetColumn(restartRequestBar, 1);
BottomBar.Children.Insert(1, restartRequestBar);
return restartRequestBar;
}
private void OnHeaderBarSizeChanged(object sender, SizeChangedEventArgs e)
{
// when the update bar appears, we adjust the window position
// so that it doesn't push the main content area down
if (e.HeightChanged && e.PreviousSize.Height < 0.5)
{
Top = Math.Max(0, Top - e.NewSize.Height);
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope"), SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
private void SetupProviders(Project activeProject,
DTE dte,
IVsPackageManagerFactory packageManagerFactory,
IPackageRepositoryFactory packageRepositoryFactory,
IPackageSourceProvider packageSourceProvider,
ProviderServices providerServices,
IHttpClientEvents httpClientEvents,
ISolutionManager solutionManager,
IPackageRestoreManager packageRestoreManager,
RestartRequestBar restartRequestBar)
{
IVsPackageManager packageManager = packageManagerFactory.CreatePackageManagerToManageInstalledPackages();
IPackageRepository localRepository;
// we need different sets of providers depending on whether the dialog is open for solution or a project
OnlineProvider onlineProvider;
InstalledProvider installedProvider;
UpdatesProvider updatesProvider;
if (activeProject == null)
{
Title = String.Format(
CultureInfo.CurrentUICulture,
NuGet.Dialog.Resources.Dialog_Title,
dte.Solution.GetName() + ".sln");
localRepository = packageManager.LocalRepository;
onlineProvider = new SolutionOnlineProvider(
localRepository,
Resources,
packageRepositoryFactory,
packageSourceProvider,
packageManagerFactory,
providerServices,
httpClientEvents,
solutionManager);
installedProvider = new SolutionInstalledProvider(
packageManager,
localRepository,
Resources,
providerServices,
httpClientEvents,
solutionManager,
packageRestoreManager);
updatesProvider = new SolutionUpdatesProvider(
localRepository,
Resources,
packageRepositoryFactory,
packageSourceProvider,
packageManagerFactory,
providerServices,
httpClientEvents,
solutionManager);
}
else
{
IProjectManager projectManager = packageManager.GetProjectManager(activeProject);
localRepository = projectManager.LocalRepository;
Title = String.Format(
CultureInfo.CurrentUICulture,
NuGet.Dialog.Resources.Dialog_Title,
activeProject.GetDisplayName());
onlineProvider = new OnlineProvider(
activeProject,
localRepository,
Resources,
packageRepositoryFactory,
packageSourceProvider,
packageManagerFactory,
providerServices,
httpClientEvents,
solutionManager);
installedProvider = new InstalledProvider(
packageManager,
activeProject,
localRepository,
Resources,
providerServices,
httpClientEvents,
solutionManager,
packageRestoreManager);
updatesProvider = new UpdatesProvider(
activeProject,
localRepository,
Resources,
packageRepositoryFactory,
packageSourceProvider,
packageManagerFactory,
providerServices,
httpClientEvents,
solutionManager);
}
explorer.Providers.Add(installedProvider);
explorer.Providers.Add(onlineProvider);
explorer.Providers.Add(updatesProvider);
installedProvider.IncludePrerelease =
onlineProvider.IncludePrerelease =
updatesProvider.IncludePrerelease = _providerSettings.IncludePrereleasePackages;
installedProvider.ExecuteCompletedCallback =
onlineProvider.ExecuteCompletedCallback =
updatesProvider.ExecuteCompletedCallback = restartRequestBar.CheckForUnsuccessfulUninstall;
Loaded += (o, e) => restartRequestBar.CheckForUnsuccessfulUninstall();
}
private void UpdateSelectedProvider(int selectedProvider)
{
// update the selected provider
selectedProvider = Math.Min(explorer.Providers.Count - 1, selectedProvider);
selectedProvider = Math.Max(selectedProvider, 0);
explorer.SelectedProvider = explorer.Providers[selectedProvider];
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")]
private void CanExecuteCommandOnPackage(object sender, CanExecuteRoutedEventArgs e)
{
if (OperationCoordinator.IsBusy)
{
e.CanExecute = false;
return;
}
VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl;
if (control == null)
{
e.CanExecute = false;
return;
}
PackageItem selectedItem = control.SelectedExtension as PackageItem;
if (selectedItem == null)
{
e.CanExecute = false;
return;
}
try
{
e.CanExecute = selectedItem.IsEnabled;
}
catch (Exception)
{
e.CanExecute = false;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")]
private void ExecutedPackageCommand(object sender, ExecutedRoutedEventArgs e)
{
if (OperationCoordinator.IsBusy)
{
return;
}
VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl;
if (control == null)
{
return;
}
PackageItem selectedItem = control.SelectedExtension as PackageItem;
if (selectedItem == null)
{
return;
}
PackagesProviderBase provider = control.SelectedProvider as PackagesProviderBase;
if (provider != null)
{
try
{
provider.Execute(selectedItem);
}
catch (Exception exception)
{
MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle);
provider.CloseProgressWindow();
ExceptionHelper.WriteToActivityLog(exception);
}
}
}
private void ExecutedClose(object sender, EventArgs e)
{
Close();
}
private void ExecutedShowOptionsPage(object sender, ExecutedRoutedEventArgs e)
{
Close();
_optionsPageActivator.ActivatePage(
OptionsPage.PackageSources,
() => OnActivated(_activeProject));
}
/// <summary>
/// Called when coming back from the Options dialog
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void OnActivated(Project project)
{
var window = new PackageManagerWindow(project);
try
{
window.ShowModal();
}
catch (Exception exception)
{
MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle);
ExceptionHelper.WriteToActivityLog(exception);
}
}
private void ExecuteOpenLicenseLink(object sender, ExecutedRoutedEventArgs e)
{
Hyperlink hyperlink = e.OriginalSource as Hyperlink;
if (hyperlink != null && hyperlink.NavigateUri != null)
{
UriHelper.OpenExternalLink(hyperlink.NavigateUri);
e.Handled = true;
}
}
private void ExecuteSetFocusOnSearchBox(object sender, ExecutedRoutedEventArgs e)
{
explorer.SetFocusOnSearchBox();
}
private void OnCategorySelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
PackagesTreeNodeBase oldNode = e.OldValue as PackagesTreeNodeBase;
if (oldNode != null)
{
// notify the previously selected node that it was closed.
oldNode.OnClosed();
}
PackagesTreeNodeBase newNode = e.NewValue as PackagesTreeNodeBase;
if (newNode != null)
{
// notify the selected node that it is opened.
newNode.OnOpened();
}
}
private void OnDialogWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
// don't allow the dialog to be closed if an operation is pending
if (OperationCoordinator.IsBusy)
{
e.Cancel = true;
}
}
private void OnDialogWindowClosed(object sender, EventArgs e)
{
foreach (PackagesProviderBase provider in explorer.Providers)
{
// give each provider a chance to clean up itself
provider.Dispose();
}
explorer.Providers.Clear();
// flush output messages to the Output console at once when the dialog is closed.
_smartOutputConsoleProvider.Flush();
_updateAllUIService.DisposeElement();
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest -= OnSendingRequest;
}
RemoveUpdateBar();
RemoveRestoreBar();
CurrentInstance = null;
}
/// <summary>
/// HACK HACK: Insert the disclaimer element into the correct place inside the Explorer control.
/// We don't want to bring in the whole control template of the extension explorer control.
/// </summary>
private void InsertDisclaimerElement()
{
Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid;
if (grid != null)
{
// m_Providers is the name of the expander provider control (the one on the leftmost column)
UIElement providerExpander = FindChildElementByNameOrType(grid, "m_Providers", typeof(ProviderExpander));
if (providerExpander != null)
{
// remove disclaimer text and provider expander from their current parents
grid.Children.Remove(providerExpander);
LayoutRoot.Children.Remove(DisclaimerText);
// create the inner grid which will host disclaimer text and the provider extender
Grid innerGrid = new Grid();
innerGrid.RowDefinitions.Add(new RowDefinition());
innerGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Auto) });
innerGrid.Children.Add(providerExpander);
Grid.SetRow(DisclaimerText, 1);
innerGrid.Children.Add(DisclaimerText);
// add the inner grid to the first column of the original grid
grid.Children.Add(innerGrid);
}
}
}
private void InsertUpdateAllButton(IUpdateAllUIService updateAllUIService)
{
Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid;
if (grid != null && grid.Children.Count > 0)
{
ListView listView = grid.FindDescendant<ListView>();
if (listView != null)
{
Grid firstGrid = (Grid)listView.Parent;
firstGrid.Children.Remove(listView);
var newGrid = new Grid
{
Margin = listView.Margin
};
newGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
newGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
var updateAllContainer = updateAllUIService.CreateUIElement();
updateAllContainer.Margin = new Thickness(5, 2, 0, 5);
updateAllContainer.UpdateInvoked += OnUpdateButtonClick;
newGrid.Children.Add(updateAllContainer);
listView.Margin = new Thickness();
Grid.SetRow(listView, 1);
newGrid.Children.Add(listView);
firstGrid.Children.Insert(0, newGrid);
}
}
}
private void AdjustSortComboBoxWidth()
{
ComboBox sortCombo = FindComboBox("cmd_SortOrder");
if (sortCombo != null)
{
// The default style fixes the Sort combo control's width to 160, which is bad for localization.
// We fix it by setting Min width as 160, and let the control resize to content.
sortCombo.ClearValue(FrameworkElement.WidthProperty);
sortCombo.MinWidth = 160;
}
}
private void PreparePrereleaseComboBox()
{
// This ComboBox is actually used to display framework versions in various VS dialogs.
// We "repurpose" it here to show Prerelease option instead.
ComboBox fxCombo = FindComboBox("cmb_Fx");
if (fxCombo != null)
{
fxCombo.Items.Clear();
fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_StablePackages);
fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_IncludePrerelease);
fxCombo.SelectedIndex = _providerSettings.IncludePrereleasePackages ? 1 : 0;
fxCombo.SelectionChanged += OnFxComboBoxSelectionChanged;
_prereleaseComboBox = fxCombo;
}
}
private void OnFxComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combo = (ComboBox)sender;
if (combo.SelectedIndex == -1)
{
return;
}
bool includePrerelease = combo.SelectedIndex == 1;
// persist the option to VS settings store
_providerSettings.IncludePrereleasePackages = includePrerelease;
// set the flags on all providers
foreach (PackagesProviderBase provider in explorer.Providers)
{
provider.IncludePrerelease = includePrerelease;
}
var selectedTreeNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase;
if (selectedTreeNode != null)
{
selectedTreeNode.Refresh(resetQueryBeforeRefresh: true);
}
}
private ComboBox FindComboBox(string name)
{
Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid;
if (grid != null)
{
return FindChildElementByNameOrType(grid, name, typeof(SortCombo)) as ComboBox;
}
return null;
}
private static UIElement FindChildElementByNameOrType(Grid parent, string childName, Type childType)
{
UIElement element = parent.FindName(childName) as UIElement;
if (element != null)
{
return element;
}
else
{
foreach (UIElement child in parent.Children)
{
if (childType.IsInstanceOfType(child))
{
return child;
}
}
return null;
}
}
private void OnProviderSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var selectedProvider = explorer.SelectedProvider as PackagesProviderBase;
if (selectedProvider != null)
{
explorer.NoItemsMessage = selectedProvider.NoItemsMessage;
_prereleaseComboBox.Visibility = selectedProvider.ShowPrereleaseComboBox ? Visibility.Visible : Visibility.Collapsed;
// save the selected provider to user settings
_providerSettings.SelectedProvider = explorer.Providers.IndexOf(selectedProvider);
// if this is the first time online provider is opened, call to check for update
if (selectedProvider == explorer.Providers[1] && !_hasOpenedOnlineProvider)
{
_hasOpenedOnlineProvider = true;
_productUpdateService.CheckForAvailableUpdateAsync();
}
_updateAllUIService.Hide();
}
else
{
_prereleaseComboBox.Visibility = Visibility.Collapsed;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")]
private void OnUpdateButtonClick(object sender, RoutedEventArgs e)
{
var provider = explorer.SelectedProvider as PackagesProviderBase;
if (provider != null)
{
try
{
provider.Execute(item: null);
}
catch (Exception exception)
{
MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle);
provider.CloseProgressWindow();
ExceptionHelper.WriteToActivityLog(exception);
}
}
}
private void OnSendingRequest(object sender, WebRequestEventArgs e)
{
HttpUtility.SetUserAgent(
e.Request,
_activeProject == null ? _dialogForSolutionUserAgent.Value : _dialogUserAgent.Value,
_projectGuids);
}
private void CanExecuteClose(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = !OperationCoordinator.IsBusy;
e.Handled = true;
}
private void OnDialogWindowLoaded(object sender, RoutedEventArgs e)
{
// HACK: Keep track of the currently open instance of this class.
CurrentInstance = this;
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
#if !VS10
var searchControlParent = explorer.SearchControlParent as DependencyObject;
#else
var searchControlParent = explorer;
#endif
var element = (TextBox)searchControlParent.FindDescendant<TextBox>();
if (element != null && !String.IsNullOrEmpty(_searchText))
{
var selectedProvider = explorer.SelectedProvider as PackagesProviderBase;
selectedProvider.SuppressLoad = false;
element.Text = _searchText;
}
}
}
}
| |
#region License
/* Copyright (c) 2006 Leslie Sanford
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contact
/*
* Leslie Sanford
* Email: [email protected]
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Sanford.Collections.Generic
{
/// <summary>
/// Represents a simple double-ended-queue collection of objects.
/// </summary>
[Serializable()]
public partial class Deque<T> : ICollection, IEnumerable<T>, ICloneable
{
#region Deque Members
#region Fields
// The node at the front of the deque.
private Node front = null;
// The node at the back of the deque.
private Node back = null;
// The number of elements in the deque.
private int count = 0;
// The version of the deque.
private long version = 0;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the Deque class.
/// </summary>
public Deque()
{
}
/// <summary>
/// Initializes a new instance of the Deque class that contains
/// elements copied from the specified collection.
/// </summary>
/// <param name="collection">
/// The collection whose elements are copied to the new Deque.
/// </param>
public Deque(IEnumerable<T> collection)
{
#region Require
if(collection == null)
{
throw new ArgumentNullException("col");
}
#endregion
foreach(T item in collection)
{
PushBack(item);
}
}
#endregion
#region Methods
/// <summary>
/// Removes all objects from the Deque.
/// </summary>
public virtual void Clear()
{
count = 0;
front = back = null;
version++;
#region Invariant
AssertValid();
#endregion
}
/// <summary>
/// Determines whether or not an element is in the Deque.
/// </summary>
/// <param name="obj">
/// The Object to locate in the Deque.
/// </param>
/// <returns>
/// <b>true</b> if <i>obj</i> if found in the Deque; otherwise,
/// <b>false</b>.
/// </returns>
public virtual bool Contains(T obj)
{
foreach(T o in this)
{
if(EqualityComparer<T>.Default.Equals(o, obj))
{
return true;
}
}
return false;
}
/// <summary>
/// Inserts an object at the front of the Deque.
/// </summary>
/// <param name="item">
/// The object to push onto the deque;
/// </param>
public virtual void PushFront(T item)
{
// The new node to add to the front of the deque.
Node newNode = new Node(item);
// Link the new node to the front node. The current front node at
// the front of the deque is now the second node in the deque.
newNode.Next = front;
// If the deque isn't empty.
if(Count > 0)
{
// Link the current front to the new node.
front.Previous = newNode;
}
// Make the new node the front of the deque.
front = newNode;
// Keep track of the number of elements in the deque.
count++;
// If this is the first element in the deque.
if(Count == 1)
{
// The front and back nodes are the same.
back = front;
}
version++;
#region Invariant
AssertValid();
#endregion
}
/// <summary>
/// Inserts an object at the back of the Deque.
/// </summary>
/// <param name="item">
/// The object to push onto the deque;
/// </param>
public virtual void PushBack(T item)
{
// The new node to add to the back of the deque.
Node newNode = new Node(item);
// Link the new node to the back node. The current back node at
// the back of the deque is now the second to the last node in the
// deque.
newNode.Previous = back;
// If the deque is not empty.
if(Count > 0)
{
// Link the current back node to the new node.
back.Next = newNode;
}
// Make the new node the back of the deque.
back = newNode;
// Keep track of the number of elements in the deque.
count++;
// If this is the first element in the deque.
if(Count == 1)
{
// The front and back nodes are the same.
front = back;
}
version++;
#region Invariant
AssertValid();
#endregion
}
/// <summary>
/// Removes and returns the object at the front of the Deque.
/// </summary>
/// <returns>
/// The object at the front of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual T PopFront()
{
#region Require
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
// Get the object at the front of the deque.
T item = front.Value;
// Move the front back one node.
front = front.Next;
// Keep track of the number of nodes in the deque.
count--;
// If the deque is not empty.
if(Count > 0)
{
// Tie off the previous link in the front node.
front.Previous = null;
}
// Else the deque is empty.
else
{
// Indicate that there is no back node.
back = null;
}
version++;
#region Invariant
AssertValid();
#endregion
return item;
}
/// <summary>
/// Removes and returns the object at the back of the Deque.
/// </summary>
/// <returns>
/// The object at the back of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual T PopBack()
{
#region Require
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
// Get the object at the back of the deque.
T item = back.Value;
// Move back node forward one node.
back = back.Previous;
// Keep track of the number of nodes in the deque.
count--;
// If the deque is not empty.
if(Count > 0)
{
// Tie off the next link in the back node.
back.Next = null;
}
// Else the deque is empty.
else
{
// Indicate that there is no front node.
front = null;
}
version++;
#region Invariant
AssertValid();
#endregion
return item;
}
/// <summary>
/// Returns the object at the front of the Deque without removing it.
/// </summary>
/// <returns>
/// The object at the front of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual T PeekFront()
{
#region Require
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
return front.Value;
}
/// <summary>
/// Returns the object at the back of the Deque without removing it.
/// </summary>
/// <returns>
/// The object at the back of the Deque.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The Deque is empty.
/// </exception>
public virtual T PeekBack()
{
#region Require
if(Count == 0)
{
throw new InvalidOperationException("Deque is empty.");
}
#endregion
return back.Value;
}
/// <summary>
/// Copies the Deque to a new array.
/// </summary>
/// <returns>
/// A new array containing copies of the elements of the Deque.
/// </returns>
public virtual T[] ToArray()
{
T[] array = new T[Count];
int index = 0;
foreach(T item in this)
{
array[index] = item;
index++;
}
return array;
}
/// <summary>
/// Returns a synchronized (thread-safe) wrapper for the Deque.
/// </summary>
/// <param name="deque">
/// The Deque to synchronize.
/// </param>
/// <returns>
/// A synchronized wrapper around the Deque.
/// </returns>
public static Deque<T> Synchronized(Deque<T> deque)
{
#region Require
if(deque == null)
{
throw new ArgumentNullException("deque");
}
#endregion
return new SynchronizedDeque(deque);
}
[Conditional("DEBUG")]
private void AssertValid()
{
int n = 0;
Node current = front;
while(current != null)
{
n++;
current = current.Next;
}
Debug.Assert(n == Count);
if(Count > 0)
{
Debug.Assert(front != null && back != null, "Front/Back Null Test - Count > 0");
Node f = front;
Node b = back;
while(f.Next != null && b.Previous != null)
{
f = f.Next;
b = b.Previous;
}
Debug.Assert(f.Next == null && b.Previous == null, "Front/Back Termination Test");
Debug.Assert(f == back && b == front, "Front/Back Equality Test");
}
else
{
Debug.Assert(front == null && back == null, "Front/Back Null Test - Count == 0");
}
}
#endregion
#endregion
#region ICollection Members
/// <summary>
/// Gets a value indicating whether access to the Deque is synchronized
/// (thread-safe).
/// </summary>
public virtual bool IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// Gets the number of elements contained in the Deque.
/// </summary>
public virtual int Count
{
get
{
return count;
}
}
/// <summary>
/// Copies the Deque elements to an existing one-dimensional Array,
/// starting at the specified array index.
/// </summary>
/// <param name="array">
/// The one-dimensional Array that is the destination of the elements
/// copied from Deque. The Array must have zero-based indexing.
/// </param>
/// <param name="index">
/// The zero-based index in array at which copying begins.
/// </param>
public virtual void CopyTo(Array array, int index)
{
#region Require
if(array == null)
{
throw new ArgumentNullException("array");
}
else if(index < 0)
{
throw new ArgumentOutOfRangeException("index", index,
"Index is less than zero.");
}
else if(array.Rank > 1)
{
throw new ArgumentException("Array is multidimensional.");
}
else if(index >= array.Length)
{
throw new ArgumentException("Index is equal to or greater " +
"than the length of array.");
}
else if(Count > array.Length - index)
{
throw new ArgumentException(
"The number of elements in the source Deque is greater " +
"than the available space from index to the end of the " +
"destination array.");
}
#endregion
int i = index;
foreach(object obj in this)
{
array.SetValue(obj, i);
i++;
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to the Deque.
/// </summary>
public virtual object SyncRoot
{
get
{
return this;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through the Deque.
/// </summary>
/// <returns>
/// An IEnumerator for the Deque.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a shallow copy of the Deque.
/// </summary>
/// <returns>
/// A shallow copy of the Deque.
/// </returns>
public virtual object Clone()
{
Deque<T> clone = new Deque<T>(this);
clone.version = this.version;
return clone;
}
#endregion
#region IEnumerable<T> Members
public virtual IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 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;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using NUnit.Framework.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
using NUnit.Tests;
using NUnit.Tests.Assemblies;
namespace NUnit.Framework.Api
{
// Functional tests of the TestAssemblyRunner and all subordinate classes
public class TestAssemblyRunnerTests : ITestListener
{
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.exe";
private const string BAD_FILE = "mock-assembly.pdb";
private const string SLOW_TESTS_FILE = "slow-nunit-tests.dll";
private const string MISSING_FILE = "junk.dll";
#if SILVERLIGHT || PORTABLE
private static readonly string MOCK_ASSEMBLY_NAME = typeof(MockAssembly).GetTypeInfo().Assembly.FullName;
#endif
private static readonly IDictionary EMPTY_SETTINGS = new Dictionary<string, object>();
private ITestAssemblyRunner _runner;
private int _testStartedCount;
private int _testFinishedCount;
private int _successCount;
private int _failCount;
private int _skipCount;
private int _inconclusiveCount;
[SetUp]
public void CreateRunner()
{
_runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
_testStartedCount = 0;
_testFinishedCount = 0;
_successCount = 0;
_failCount = 0;
_skipCount = 0;
_inconclusiveCount = 0;
}
#region Load
[Test]
public void Load_GoodFile_ReturnsRunnableSuite()
{
var result = LoadMockAssembly();
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
#if SILVERLIGHT || PORTABLE
Assert.That(result.Name, Is.EqualTo(MOCK_ASSEMBLY_NAME));
#else
Assert.That(result.Name, Is.EqualTo(MOCK_ASSEMBLY_FILE));
#endif
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.Runnable));
Assert.That(result.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void Load_FileNotFound_ReturnsNonRunnableSuite()
{
var result = _runner.Load(MISSING_FILE, EMPTY_SETTINGS);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MISSING_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
#if NETCF
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("File or assembly name"));
#else
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Could not load"));
#endif
}
[Test]
public void Load_BadFile_ReturnsNonRunnableSuite()
{
var result = _runner.Load(BAD_FILE, EMPTY_SETTINGS);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(BAD_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
#if NETCF
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("File or assembly name").And.Contains(BAD_FILE));
#else
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Could not load").And.Contains(BAD_FILE));
#endif
}
#endregion
#region CountTestCases
[Test]
public void CountTestCases_AfterLoad_ReturnsCorrectCount()
{
LoadMockAssembly();
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void CountTestCases_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.CountTestCases(TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded"));
}
[Test]
public void CountTestCases_FileNotFound_ReturnsZero()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
[Test]
public void CountTestCases_BadFile_ReturnsZero()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
#endregion
#region Run
[Test]
public void Run_AfterLoad_ReturnsRunnableSuite()
{
LoadMockAssembly();
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(result.PassCount, Is.EqualTo(MockAssembly.Success));
Assert.That(result.FailCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_AfterLoad_SendsExpectedEvents()
{
LoadMockAssembly();
var result = _runner.Run(this, TestFilter.Empty);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Success));
Assert.That(_failCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.Run(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void Run_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(result.Message, Does.StartWith("File or assembly name"));
#else
Assert.That(result.Message, Does.StartWith("Could not load"));
#endif
}
[Test]
public void Run_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(result.Message, Does.StartWith("File or assembly name").And.Contains(BAD_FILE));
#else
Assert.That(result.Message, Does.StartWith("Could not load").And.Contains(BAD_FILE));
#endif
}
#endregion
#region RunAsync
[Test]
public void RunAsync_AfterLoad_ReturnsRunnableSuite()
{
LoadMockAssembly();
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(_runner.Result.PassCount, Is.EqualTo(MockAssembly.Success));
Assert.That(_runner.Result.FailCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(_runner.Result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_runner.Result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_AfterLoad_SendsExpectedEvents()
{
LoadMockAssembly();
_runner.RunAsync(this, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Success));
Assert.That(_failCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.RunAsync(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void RunAsync_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, EMPTY_SETTINGS);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(_runner.Result.Message, Does.StartWith("File or assembly name"));
#else
Assert.That(_runner.Result.Message, Does.StartWith("Could not load"));
#endif
}
[Test]
public void RunAsync_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, EMPTY_SETTINGS);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(_runner.Result.Message, Does.StartWith("File or assembly name").And.Contains(BAD_FILE));
#else
Assert.That(_runner.Result.Message, Does.StartWith("Could not load").And.Contains(BAD_FILE));
#endif
}
#endregion
#region StopRun
[Test]
public void StopRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(false);
}
[Test]
public void StopRun_WhenTestIsRunning_StopsTest()
{
var tests = LoadSlowTests();
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(false);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success) // Test may have finished before we stopped it
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region Cancel Run
[Test]
public void CancelRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(true);
}
[Test]
public void CancelRun_WhenTestIsRunning_StopsTest()
{
var tests = LoadSlowTests();
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(true);
// When cancelling, the completion event may not be signalled,
// so we only wait a short time before checking.
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success)
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region ITestListener Implementation
void ITestListener.TestStarted(ITest test)
{
if (!test.IsSuite)
_testStartedCount++;
}
void ITestListener.TestFinished(ITestResult result)
{
if (!result.Test.IsSuite)
{
_testFinishedCount++;
switch (result.ResultState.Status)
{
case TestStatus.Passed:
_successCount++;
break;
case TestStatus.Failed:
_failCount++;
break;
case TestStatus.Skipped:
_skipCount++;
break;
case TestStatus.Inconclusive:
_inconclusiveCount++;
break;
}
}
}
#endregion
#region Helper Methods
private ITest LoadMockAssembly()
{
#if PORTABLE
return _runner.Load(
typeof(MockAssembly).GetTypeInfo().Assembly,
EMPTY_SETTINGS);
#elif SILVERLIGHT
return _runner.Load(MOCK_ASSEMBLY_NAME, EMPTY_SETTINGS);
#else
return _runner.Load(
Path.Combine(TestContext.CurrentContext.TestDirectory, MOCK_ASSEMBLY_FILE),
EMPTY_SETTINGS);
#endif
}
private ITest LoadSlowTests()
{
#if PORTABLE
return _runner.Load(typeof(SlowTests).GetTypeInfo().Assembly, EMPTY_SETTINGS);
#elif SILVERLIGHT
return _runner.Load(typeof(SlowTests).GetTypeInfo().Assembly.FullName, EMPTY_SETTINGS);
#else
return _runner.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, SLOW_TESTS_FILE), EMPTY_SETTINGS);
#endif
}
#endregion
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.widget.AbsListView_))]
public abstract partial class AbsListView : android.widget.AdapterView, android.text.TextWatcher, android.view.ViewTreeObserver.OnGlobalLayoutListener, android.widget.Filter.FilterListener, android.view.ViewTreeObserver.OnTouchModeChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AbsListView()
{
InitJNI();
}
protected AbsListView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public new partial class LayoutParams : android.view.ViewGroup.LayoutParams
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static LayoutParams()
{
InitJNI();
}
protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _LayoutParams10697;
public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.LayoutParams.staticClass, global::android.widget.AbsListView.LayoutParams._LayoutParams10697, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams10698;
public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.LayoutParams.staticClass, global::android.widget.AbsListView.LayoutParams._LayoutParams10698, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams10699;
public LayoutParams(int arg0, int arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.LayoutParams.staticClass, global::android.widget.AbsListView.LayoutParams._LayoutParams10699, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _LayoutParams10700;
public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.LayoutParams.staticClass, global::android.widget.AbsListView.LayoutParams._LayoutParams10700, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AbsListView.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AbsListView$LayoutParams"));
global::android.widget.AbsListView.LayoutParams._LayoutParams10697 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.AbsListView.LayoutParams._LayoutParams10698 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.LayoutParams.staticClass, "<init>", "(II)V");
global::android.widget.AbsListView.LayoutParams._LayoutParams10699 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.LayoutParams.staticClass, "<init>", "(III)V");
global::android.widget.AbsListView.LayoutParams._LayoutParams10700 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AbsListView.OnScrollListener_))]
public interface OnScrollListener : global::MonoJavaBridge.IJavaObject
{
void onScroll(android.widget.AbsListView arg0, int arg1, int arg2, int arg3);
void onScrollStateChanged(android.widget.AbsListView arg0, int arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AbsListView.OnScrollListener))]
public sealed partial class OnScrollListener_ : java.lang.Object, OnScrollListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnScrollListener_()
{
InitJNI();
}
internal OnScrollListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onScroll10701;
void android.widget.AbsListView.OnScrollListener.onScroll(android.widget.AbsListView arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView.OnScrollListener_._onScroll10701, 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.widget.AbsListView.OnScrollListener_.staticClass, global::android.widget.AbsListView.OnScrollListener_._onScroll10701, 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 _onScrollStateChanged10702;
void android.widget.AbsListView.OnScrollListener.onScrollStateChanged(android.widget.AbsListView arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView.OnScrollListener_._onScrollStateChanged10702, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.OnScrollListener_.staticClass, global::android.widget.AbsListView.OnScrollListener_._onScrollStateChanged10702, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AbsListView.OnScrollListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AbsListView$OnScrollListener"));
global::android.widget.AbsListView.OnScrollListener_._onScroll10701 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.OnScrollListener_.staticClass, "onScroll", "(Landroid/widget/AbsListView;III)V");
global::android.widget.AbsListView.OnScrollListener_._onScrollStateChanged10702 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.OnScrollListener_.staticClass, "onScrollStateChanged", "(Landroid/widget/AbsListView;I)V");
}
}
[global::MonoJavaBridge.JavaClass()]
public static partial class OnScrollListenerConstants
{
public static int SCROLL_STATE_IDLE
{
get
{
return 0;
}
}
public static int SCROLL_STATE_TOUCH_SCROLL
{
get
{
return 1;
}
}
public static int SCROLL_STATE_FLING
{
get
{
return 2;
}
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.AbsListView.RecyclerListener_))]
public interface RecyclerListener : global::MonoJavaBridge.IJavaObject
{
void onMovedToScrapHeap(android.view.View arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AbsListView.RecyclerListener))]
public sealed partial class RecyclerListener_ : java.lang.Object, RecyclerListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static RecyclerListener_()
{
InitJNI();
}
internal RecyclerListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onMovedToScrapHeap10703;
void android.widget.AbsListView.RecyclerListener.onMovedToScrapHeap(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView.RecyclerListener_._onMovedToScrapHeap10703, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.RecyclerListener_.staticClass, global::android.widget.AbsListView.RecyclerListener_._onMovedToScrapHeap10703, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AbsListView.RecyclerListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AbsListView$RecyclerListener"));
global::android.widget.AbsListView.RecyclerListener_._onMovedToScrapHeap10703 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.RecyclerListener_.staticClass, "onMovedToScrapHeap", "(Landroid/view/View;)V");
}
}
internal static global::MonoJavaBridge.MethodId _draw10704;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._draw10704, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._draw10704, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onRestoreInstanceState10705;
public virtual new void onRestoreInstanceState(android.os.Parcelable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onRestoreInstanceState10705, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onRestoreInstanceState10705, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onSaveInstanceState10706;
public virtual new global::android.os.Parcelable onSaveInstanceState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._onSaveInstanceState10706)) as android.os.Parcelable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onSaveInstanceState10706)) as android.os.Parcelable;
}
internal static global::MonoJavaBridge.MethodId _onKeyDown10707;
public override bool onKeyDown(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._onKeyDown10707, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onKeyDown10707, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onKeyUp10708;
public override bool onKeyUp(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._onKeyUp10708, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onKeyUp10708, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onTouchEvent10709;
public override bool onTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._onTouchEvent10709, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onTouchEvent10709, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onWindowFocusChanged10710;
public override void onWindowFocusChanged(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onWindowFocusChanged10710, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onWindowFocusChanged10710, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onAttachedToWindow10711;
protected override void onAttachedToWindow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onAttachedToWindow10711);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onAttachedToWindow10711);
}
internal static global::MonoJavaBridge.MethodId _onDetachedFromWindow10712;
protected override void onDetachedFromWindow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onDetachedFromWindow10712);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onDetachedFromWindow10712);
}
internal static global::MonoJavaBridge.MethodId _onFocusChanged10713;
protected override void onFocusChanged(bool arg0, int arg1, android.graphics.Rect arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onFocusChanged10713, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onFocusChanged10713, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _dispatchSetPressed10714;
protected override void dispatchSetPressed(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._dispatchSetPressed10714, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._dispatchSetPressed10714, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addTouchables10715;
public override void addTouchables(java.util.ArrayList arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._addTouchables10715, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._addTouchables10715, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onDisplayHint10716;
protected override void onDisplayHint(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onDisplayHint10716, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onDisplayHint10716, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onCreateInputConnection10717;
public override global::android.view.inputmethod.InputConnection onCreateInputConnection(android.view.inputmethod.EditorInfo arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.inputmethod.InputConnection>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._onCreateInputConnection10717, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.inputmethod.InputConnection;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.inputmethod.InputConnection>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onCreateInputConnection10717, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.inputmethod.InputConnection;
}
internal static global::MonoJavaBridge.MethodId _checkInputConnectionProxy10718;
public override bool checkInputConnectionProxy(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._checkInputConnectionProxy10718, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._checkInputConnectionProxy10718, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getContextMenuInfo10719;
protected override global::android.view.ContextMenu_ContextMenuInfo getContextMenuInfo()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.ContextMenu_ContextMenuInfo>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._getContextMenuInfo10719)) as android.view.ContextMenu_ContextMenuInfo;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.ContextMenu_ContextMenuInfo>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getContextMenuInfo10719)) as android.view.ContextMenu_ContextMenuInfo;
}
internal static global::MonoJavaBridge.MethodId _onSizeChanged10720;
protected override void onSizeChanged(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onSizeChanged10720, 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.widget.AbsListView.staticClass, global::android.widget.AbsListView._onSizeChanged10720, 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 _dispatchDraw10721;
protected override void dispatchDraw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._dispatchDraw10721, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._dispatchDraw10721, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFocusedRect10722;
public override void getFocusedRect(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._getFocusedRect10722, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getFocusedRect10722, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getTopFadingEdgeStrength10723;
protected override float getTopFadingEdgeStrength()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.widget.AbsListView._getTopFadingEdgeStrength10723);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getTopFadingEdgeStrength10723);
}
internal static global::MonoJavaBridge.MethodId _getBottomFadingEdgeStrength10724;
protected override float getBottomFadingEdgeStrength()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.widget.AbsListView._getBottomFadingEdgeStrength10724);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getBottomFadingEdgeStrength10724);
}
internal static global::MonoJavaBridge.MethodId _computeVerticalScrollRange10725;
protected override int computeVerticalScrollRange()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._computeVerticalScrollRange10725);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._computeVerticalScrollRange10725);
}
internal static global::MonoJavaBridge.MethodId _computeVerticalScrollOffset10726;
protected override int computeVerticalScrollOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._computeVerticalScrollOffset10726);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._computeVerticalScrollOffset10726);
}
internal static global::MonoJavaBridge.MethodId _computeVerticalScrollExtent10727;
protected override int computeVerticalScrollExtent()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._computeVerticalScrollExtent10727);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._computeVerticalScrollExtent10727);
}
internal static global::MonoJavaBridge.MethodId _getSolidColor10728;
public override int getSolidColor()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getSolidColor10728);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getSolidColor10728);
}
internal static global::MonoJavaBridge.MethodId _onLayout10729;
protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onLayout10729, 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.widget.AbsListView.staticClass, global::android.widget.AbsListView._onLayout10729, 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 _verifyDrawable10730;
public virtual new bool verifyDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._verifyDrawable10730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._verifyDrawable10730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _drawableStateChanged10731;
protected override void drawableStateChanged()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._drawableStateChanged10731);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._drawableStateChanged10731);
}
internal static global::MonoJavaBridge.MethodId _onCreateDrawableState10732;
protected override int[] onCreateDrawableState(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._onCreateDrawableState10732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as int[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onCreateDrawableState10732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as int[];
}
internal static global::MonoJavaBridge.MethodId _requestLayout10733;
public override void requestLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._requestLayout10733);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._requestLayout10733);
}
internal static global::MonoJavaBridge.MethodId _onMeasure10734;
protected override void onMeasure(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onMeasure10734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onMeasure10734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _showContextMenuForChild10735;
public override bool showContextMenuForChild(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._showContextMenuForChild10735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._showContextMenuForChild10735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onInterceptTouchEvent10736;
public override bool onInterceptTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._onInterceptTouchEvent10736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onInterceptTouchEvent10736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _checkLayoutParams10737;
protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._checkLayoutParams10737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._checkLayoutParams10737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _generateLayoutParams10738;
public virtual new global::android.widget.AbsListView.LayoutParams generateLayoutParams(android.util.AttributeSet arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._generateLayoutParams10738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.AbsListView.LayoutParams;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._generateLayoutParams10738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.AbsListView.LayoutParams;
}
internal static global::MonoJavaBridge.MethodId _generateLayoutParams10739;
protected override global::android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._generateLayoutParams10739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._generateLayoutParams10739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams;
}
internal static global::MonoJavaBridge.MethodId _getSelectedView10740;
public override global::android.view.View getSelectedView()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._getSelectedView10740)) as android.view.View;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getSelectedView10740)) as android.view.View;
}
internal static global::MonoJavaBridge.MethodId _onTextChanged10741;
public virtual void onTextChanged(java.lang.CharSequence arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onTextChanged10741, 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.widget.AbsListView.staticClass, global::android.widget.AbsListView._onTextChanged10741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
public void onTextChanged(string arg0, int arg1, int arg2, int arg3)
{
onTextChanged((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2, arg3);
}
internal static global::MonoJavaBridge.MethodId _layoutChildren10742;
protected virtual void layoutChildren()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._layoutChildren10742);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._layoutChildren10742);
}
internal static global::MonoJavaBridge.MethodId _setCacheColorHint10743;
public virtual void setCacheColorHint(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setCacheColorHint10743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setCacheColorHint10743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFastScrollEnabled10744;
public virtual void setFastScrollEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setFastScrollEnabled10744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setFastScrollEnabled10744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isFastScrollEnabled10745;
public virtual bool isFastScrollEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._isFastScrollEnabled10745);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._isFastScrollEnabled10745);
}
internal static global::MonoJavaBridge.MethodId _setSmoothScrollbarEnabled10746;
public virtual void setSmoothScrollbarEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setSmoothScrollbarEnabled10746, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setSmoothScrollbarEnabled10746, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isSmoothScrollbarEnabled10747;
public virtual bool isSmoothScrollbarEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._isSmoothScrollbarEnabled10747);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._isSmoothScrollbarEnabled10747);
}
internal static global::MonoJavaBridge.MethodId _setOnScrollListener10748;
public virtual void setOnScrollListener(android.widget.AbsListView.OnScrollListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setOnScrollListener10748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setOnScrollListener10748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isScrollingCacheEnabled10749;
public virtual bool isScrollingCacheEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._isScrollingCacheEnabled10749);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._isScrollingCacheEnabled10749);
}
internal static global::MonoJavaBridge.MethodId _setScrollingCacheEnabled10750;
public virtual void setScrollingCacheEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setScrollingCacheEnabled10750, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setScrollingCacheEnabled10750, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setTextFilterEnabled10751;
public virtual void setTextFilterEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setTextFilterEnabled10751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setTextFilterEnabled10751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isTextFilterEnabled10752;
public virtual bool isTextFilterEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._isTextFilterEnabled10752);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._isTextFilterEnabled10752);
}
internal static global::MonoJavaBridge.MethodId _isStackFromBottom10753;
public virtual bool isStackFromBottom()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._isStackFromBottom10753);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._isStackFromBottom10753);
}
internal static global::MonoJavaBridge.MethodId _setStackFromBottom10754;
public virtual void setStackFromBottom(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setStackFromBottom10754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setStackFromBottom10754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFilterText10755;
public virtual void setFilterText(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setFilterText10755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setFilterText10755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getTextFilter10756;
public virtual global::java.lang.CharSequence getTextFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._getTextFilter10756)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getTextFilter10756)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getListPaddingTop10757;
public virtual int getListPaddingTop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getListPaddingTop10757);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getListPaddingTop10757);
}
internal static global::MonoJavaBridge.MethodId _getListPaddingBottom10758;
public virtual int getListPaddingBottom()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getListPaddingBottom10758);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getListPaddingBottom10758);
}
internal static global::MonoJavaBridge.MethodId _getListPaddingLeft10759;
public virtual int getListPaddingLeft()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getListPaddingLeft10759);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getListPaddingLeft10759);
}
internal static global::MonoJavaBridge.MethodId _getListPaddingRight10760;
public virtual int getListPaddingRight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getListPaddingRight10760);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getListPaddingRight10760);
}
internal static global::MonoJavaBridge.MethodId _setDrawSelectorOnTop10761;
public virtual void setDrawSelectorOnTop(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setDrawSelectorOnTop10761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setDrawSelectorOnTop10761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setSelector10762;
public virtual void setSelector(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setSelector10762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setSelector10762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setSelector10763;
public virtual void setSelector(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setSelector10763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setSelector10763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSelector10764;
public virtual global::android.graphics.drawable.Drawable getSelector()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView._getSelector10764)) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getSelector10764)) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _setScrollIndicators10765;
public virtual void setScrollIndicators(android.view.View arg0, android.view.View arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setScrollIndicators10765, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setScrollIndicators10765, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _pointToPosition10766;
public virtual int pointToPosition(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._pointToPosition10766, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._pointToPosition10766, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _pointToRowId10767;
public virtual long pointToRowId(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.widget.AbsListView._pointToRowId10767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._pointToRowId10767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onTouchModeChanged10768;
public virtual void onTouchModeChanged(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onTouchModeChanged10768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onTouchModeChanged10768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _smoothScrollToPosition10769;
public virtual void smoothScrollToPosition(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._smoothScrollToPosition10769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._smoothScrollToPosition10769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _smoothScrollToPosition10770;
public virtual void smoothScrollToPosition(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._smoothScrollToPosition10770, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._smoothScrollToPosition10770, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _smoothScrollBy10771;
public virtual void smoothScrollBy(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._smoothScrollBy10771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._smoothScrollBy10771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _invalidateViews10772;
public virtual void invalidateViews()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._invalidateViews10772);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._invalidateViews10772);
}
internal static global::MonoJavaBridge.MethodId _handleDataChanged10773;
protected virtual void handleDataChanged()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._handleDataChanged10773);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._handleDataChanged10773);
}
internal static global::MonoJavaBridge.MethodId _isInFilterMode10774;
protected virtual bool isInFilterMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._isInFilterMode10774);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._isInFilterMode10774);
}
internal static global::MonoJavaBridge.MethodId _clearTextFilter10775;
public virtual void clearTextFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._clearTextFilter10775);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._clearTextFilter10775);
}
internal static global::MonoJavaBridge.MethodId _hasTextFilter10776;
public virtual bool hasTextFilter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.AbsListView._hasTextFilter10776);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._hasTextFilter10776);
}
internal static global::MonoJavaBridge.MethodId _onGlobalLayout10777;
public virtual void onGlobalLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onGlobalLayout10777);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onGlobalLayout10777);
}
internal static global::MonoJavaBridge.MethodId _beforeTextChanged10778;
public virtual void beforeTextChanged(java.lang.CharSequence arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._beforeTextChanged10778, 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.widget.AbsListView.staticClass, global::android.widget.AbsListView._beforeTextChanged10778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
public void beforeTextChanged(string arg0, int arg1, int arg2, int arg3)
{
beforeTextChanged((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2, arg3);
}
internal static global::MonoJavaBridge.MethodId _afterTextChanged10779;
public virtual void afterTextChanged(android.text.Editable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._afterTextChanged10779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._afterTextChanged10779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onFilterComplete10780;
public virtual void onFilterComplete(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._onFilterComplete10780, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._onFilterComplete10780, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setTranscriptMode10781;
public virtual void setTranscriptMode(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setTranscriptMode10781, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setTranscriptMode10781, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getTranscriptMode10782;
public virtual int getTranscriptMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getTranscriptMode10782);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getTranscriptMode10782);
}
internal static global::MonoJavaBridge.MethodId _getCacheColorHint10783;
public virtual int getCacheColorHint()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.AbsListView._getCacheColorHint10783);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._getCacheColorHint10783);
}
internal static global::MonoJavaBridge.MethodId _reclaimViews10784;
public virtual void reclaimViews(java.util.List arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._reclaimViews10784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._reclaimViews10784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setRecyclerListener10785;
public virtual void setRecyclerListener(android.widget.AbsListView.RecyclerListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView._setRecyclerListener10785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView.staticClass, global::android.widget.AbsListView._setRecyclerListener10785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _AbsListView10786;
public AbsListView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.staticClass, global::android.widget.AbsListView._AbsListView10786, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _AbsListView10787;
public AbsListView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.staticClass, global::android.widget.AbsListView._AbsListView10787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _AbsListView10788;
public AbsListView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.AbsListView.staticClass, global::android.widget.AbsListView._AbsListView10788, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int TRANSCRIPT_MODE_DISABLED
{
get
{
return 0;
}
}
public static int TRANSCRIPT_MODE_NORMAL
{
get
{
return 1;
}
}
public static int TRANSCRIPT_MODE_ALWAYS_SCROLL
{
get
{
return 2;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AbsListView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AbsListView"));
global::android.widget.AbsListView._draw10704 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "draw", "(Landroid/graphics/Canvas;)V");
global::android.widget.AbsListView._onRestoreInstanceState10705 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V");
global::android.widget.AbsListView._onSaveInstanceState10706 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;");
global::android.widget.AbsListView._onKeyDown10707 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z");
global::android.widget.AbsListView._onKeyUp10708 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z");
global::android.widget.AbsListView._onTouchEvent10709 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.widget.AbsListView._onWindowFocusChanged10710 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onWindowFocusChanged", "(Z)V");
global::android.widget.AbsListView._onAttachedToWindow10711 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onAttachedToWindow", "()V");
global::android.widget.AbsListView._onDetachedFromWindow10712 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onDetachedFromWindow", "()V");
global::android.widget.AbsListView._onFocusChanged10713 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onFocusChanged", "(ZILandroid/graphics/Rect;)V");
global::android.widget.AbsListView._dispatchSetPressed10714 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "dispatchSetPressed", "(Z)V");
global::android.widget.AbsListView._addTouchables10715 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "addTouchables", "(Ljava/util/ArrayList;)V");
global::android.widget.AbsListView._onDisplayHint10716 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onDisplayHint", "(I)V");
global::android.widget.AbsListView._onCreateInputConnection10717 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onCreateInputConnection", "(Landroid/view/inputmethod/EditorInfo;)Landroid/view/inputmethod/InputConnection;");
global::android.widget.AbsListView._checkInputConnectionProxy10718 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "checkInputConnectionProxy", "(Landroid/view/View;)Z");
global::android.widget.AbsListView._getContextMenuInfo10719 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getContextMenuInfo", "()Landroid/view/ContextMenu$ContextMenuInfo;");
global::android.widget.AbsListView._onSizeChanged10720 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onSizeChanged", "(IIII)V");
global::android.widget.AbsListView._dispatchDraw10721 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "dispatchDraw", "(Landroid/graphics/Canvas;)V");
global::android.widget.AbsListView._getFocusedRect10722 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getFocusedRect", "(Landroid/graphics/Rect;)V");
global::android.widget.AbsListView._getTopFadingEdgeStrength10723 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getTopFadingEdgeStrength", "()F");
global::android.widget.AbsListView._getBottomFadingEdgeStrength10724 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getBottomFadingEdgeStrength", "()F");
global::android.widget.AbsListView._computeVerticalScrollRange10725 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "computeVerticalScrollRange", "()I");
global::android.widget.AbsListView._computeVerticalScrollOffset10726 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "computeVerticalScrollOffset", "()I");
global::android.widget.AbsListView._computeVerticalScrollExtent10727 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "computeVerticalScrollExtent", "()I");
global::android.widget.AbsListView._getSolidColor10728 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getSolidColor", "()I");
global::android.widget.AbsListView._onLayout10729 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onLayout", "(ZIIII)V");
global::android.widget.AbsListView._verifyDrawable10730 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "verifyDrawable", "(Landroid/graphics/drawable/Drawable;)Z");
global::android.widget.AbsListView._drawableStateChanged10731 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "drawableStateChanged", "()V");
global::android.widget.AbsListView._onCreateDrawableState10732 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onCreateDrawableState", "(I)[I");
global::android.widget.AbsListView._requestLayout10733 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "requestLayout", "()V");
global::android.widget.AbsListView._onMeasure10734 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onMeasure", "(II)V");
global::android.widget.AbsListView._showContextMenuForChild10735 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "showContextMenuForChild", "(Landroid/view/View;)Z");
global::android.widget.AbsListView._onInterceptTouchEvent10736 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onInterceptTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.widget.AbsListView._checkLayoutParams10737 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z");
global::android.widget.AbsListView._generateLayoutParams10738 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/AbsListView$LayoutParams;");
global::android.widget.AbsListView._generateLayoutParams10739 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/view/ViewGroup$LayoutParams;");
global::android.widget.AbsListView._getSelectedView10740 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getSelectedView", "()Landroid/view/View;");
global::android.widget.AbsListView._onTextChanged10741 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onTextChanged", "(Ljava/lang/CharSequence;III)V");
global::android.widget.AbsListView._layoutChildren10742 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "layoutChildren", "()V");
global::android.widget.AbsListView._setCacheColorHint10743 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setCacheColorHint", "(I)V");
global::android.widget.AbsListView._setFastScrollEnabled10744 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setFastScrollEnabled", "(Z)V");
global::android.widget.AbsListView._isFastScrollEnabled10745 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "isFastScrollEnabled", "()Z");
global::android.widget.AbsListView._setSmoothScrollbarEnabled10746 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setSmoothScrollbarEnabled", "(Z)V");
global::android.widget.AbsListView._isSmoothScrollbarEnabled10747 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "isSmoothScrollbarEnabled", "()Z");
global::android.widget.AbsListView._setOnScrollListener10748 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setOnScrollListener", "(Landroid/widget/AbsListView$OnScrollListener;)V");
global::android.widget.AbsListView._isScrollingCacheEnabled10749 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "isScrollingCacheEnabled", "()Z");
global::android.widget.AbsListView._setScrollingCacheEnabled10750 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setScrollingCacheEnabled", "(Z)V");
global::android.widget.AbsListView._setTextFilterEnabled10751 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setTextFilterEnabled", "(Z)V");
global::android.widget.AbsListView._isTextFilterEnabled10752 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "isTextFilterEnabled", "()Z");
global::android.widget.AbsListView._isStackFromBottom10753 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "isStackFromBottom", "()Z");
global::android.widget.AbsListView._setStackFromBottom10754 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setStackFromBottom", "(Z)V");
global::android.widget.AbsListView._setFilterText10755 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setFilterText", "(Ljava/lang/String;)V");
global::android.widget.AbsListView._getTextFilter10756 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getTextFilter", "()Ljava/lang/CharSequence;");
global::android.widget.AbsListView._getListPaddingTop10757 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getListPaddingTop", "()I");
global::android.widget.AbsListView._getListPaddingBottom10758 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getListPaddingBottom", "()I");
global::android.widget.AbsListView._getListPaddingLeft10759 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getListPaddingLeft", "()I");
global::android.widget.AbsListView._getListPaddingRight10760 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getListPaddingRight", "()I");
global::android.widget.AbsListView._setDrawSelectorOnTop10761 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setDrawSelectorOnTop", "(Z)V");
global::android.widget.AbsListView._setSelector10762 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setSelector", "(Landroid/graphics/drawable/Drawable;)V");
global::android.widget.AbsListView._setSelector10763 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setSelector", "(I)V");
global::android.widget.AbsListView._getSelector10764 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getSelector", "()Landroid/graphics/drawable/Drawable;");
global::android.widget.AbsListView._setScrollIndicators10765 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setScrollIndicators", "(Landroid/view/View;Landroid/view/View;)V");
global::android.widget.AbsListView._pointToPosition10766 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "pointToPosition", "(II)I");
global::android.widget.AbsListView._pointToRowId10767 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "pointToRowId", "(II)J");
global::android.widget.AbsListView._onTouchModeChanged10768 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onTouchModeChanged", "(Z)V");
global::android.widget.AbsListView._smoothScrollToPosition10769 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "smoothScrollToPosition", "(I)V");
global::android.widget.AbsListView._smoothScrollToPosition10770 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "smoothScrollToPosition", "(II)V");
global::android.widget.AbsListView._smoothScrollBy10771 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "smoothScrollBy", "(II)V");
global::android.widget.AbsListView._invalidateViews10772 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "invalidateViews", "()V");
global::android.widget.AbsListView._handleDataChanged10773 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "handleDataChanged", "()V");
global::android.widget.AbsListView._isInFilterMode10774 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "isInFilterMode", "()Z");
global::android.widget.AbsListView._clearTextFilter10775 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "clearTextFilter", "()V");
global::android.widget.AbsListView._hasTextFilter10776 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "hasTextFilter", "()Z");
global::android.widget.AbsListView._onGlobalLayout10777 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onGlobalLayout", "()V");
global::android.widget.AbsListView._beforeTextChanged10778 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "beforeTextChanged", "(Ljava/lang/CharSequence;III)V");
global::android.widget.AbsListView._afterTextChanged10779 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "afterTextChanged", "(Landroid/text/Editable;)V");
global::android.widget.AbsListView._onFilterComplete10780 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "onFilterComplete", "(I)V");
global::android.widget.AbsListView._setTranscriptMode10781 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setTranscriptMode", "(I)V");
global::android.widget.AbsListView._getTranscriptMode10782 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getTranscriptMode", "()I");
global::android.widget.AbsListView._getCacheColorHint10783 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "getCacheColorHint", "()I");
global::android.widget.AbsListView._reclaimViews10784 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "reclaimViews", "(Ljava/util/List;)V");
global::android.widget.AbsListView._setRecyclerListener10785 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "setRecyclerListener", "(Landroid/widget/AbsListView$RecyclerListener;)V");
global::android.widget.AbsListView._AbsListView10786 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.AbsListView._AbsListView10787 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::android.widget.AbsListView._AbsListView10788 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView.staticClass, "<init>", "(Landroid/content/Context;)V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.AbsListView))]
public sealed partial class AbsListView_ : android.widget.AbsListView
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AbsListView_()
{
InitJNI();
}
internal AbsListView_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _setAdapter10789;
public override void setAdapter(android.widget.Adapter arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView_._setAdapter10789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView_.staticClass, global::android.widget.AbsListView_._setAdapter10789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getAdapter10790;
public override global::android.widget.Adapter getAdapter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.Adapter>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.AbsListView_._getAdapter10790)) as android.widget.Adapter;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.Adapter>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.AbsListView_.staticClass, global::android.widget.AbsListView_._getAdapter10790)) as android.widget.Adapter;
}
internal static global::MonoJavaBridge.MethodId _setSelection10791;
public override void setSelection(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.AbsListView_._setSelection10791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.AbsListView_.staticClass, global::android.widget.AbsListView_._setSelection10791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.AbsListView_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/AbsListView"));
global::android.widget.AbsListView_._setAdapter10789 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView_.staticClass, "setAdapter", "(Landroid/widget/Adapter;)V");
global::android.widget.AbsListView_._getAdapter10790 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView_.staticClass, "getAdapter", "()Landroid/widget/Adapter;");
global::android.widget.AbsListView_._setSelection10791 = @__env.GetMethodIDNoThrow(global::android.widget.AbsListView_.staticClass, "setSelection", "(I)V");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
// Low level abstraction for a socket/pipe
public interface IConnection
{
byte[] AsyncReadBuffer { get; }
int AsyncReadBufferSize { get; }
void Abort();
void Close(TimeSpan timeout, bool asyncAndLinger);
AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
Action<object> callback, object state);
void EndWrite();
void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout);
void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager);
int Read(byte[] buffer, int offset, int size, TimeSpan timeout);
AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action<object> callback, object state);
int EndRead();
object GetCoreTransport();
}
// Low level abstraction for connecting a socket/pipe
public interface IConnectionInitiator
{
IConnection Connect(Uri uri, TimeSpan timeout);
Task<IConnection> ConnectAsync(Uri uri, TimeSpan timeout);
}
internal abstract class DelegatingConnection : IConnection
{
private IConnection _connection;
protected DelegatingConnection(IConnection connection)
{
_connection = connection;
}
public virtual byte[] AsyncReadBuffer
{
get { return _connection.AsyncReadBuffer; }
}
public virtual int AsyncReadBufferSize
{
get { return _connection.AsyncReadBufferSize; }
}
protected IConnection Connection
{
get { return _connection; }
}
public virtual void Abort()
{
_connection.Abort();
}
public virtual void Close(TimeSpan timeout, bool asyncAndLinger)
{
_connection.Close(timeout, asyncAndLinger);
}
public virtual AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
Action<object> callback, object state)
{
return _connection.BeginWrite(buffer, offset, size, immediate, timeout, callback, state);
}
public virtual void EndWrite()
{
_connection.EndWrite();
}
public virtual void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
{
_connection.Write(buffer, offset, size, immediate, timeout);
}
public virtual void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager)
{
_connection.Write(buffer, offset, size, immediate, timeout, bufferManager);
}
public virtual int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
{
return _connection.Read(buffer, offset, size, timeout);
}
public virtual AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout,
Action<object> callback, object state)
{
return _connection.BeginRead(offset, size, timeout, callback, state);
}
public virtual int EndRead()
{
return _connection.EndRead();
}
public virtual object GetCoreTransport()
{
return _connection.GetCoreTransport();
}
}
internal class PreReadConnection : DelegatingConnection
{
private int _asyncBytesRead;
private byte[] _preReadData;
private int _preReadOffset;
private int _preReadCount;
public PreReadConnection(IConnection innerConnection, byte[] initialData)
: this(innerConnection, initialData, 0, initialData.Length)
{
}
public PreReadConnection(IConnection innerConnection, byte[] initialData, int initialOffset, int initialSize)
: base(innerConnection)
{
_preReadData = initialData;
_preReadOffset = initialOffset;
_preReadCount = initialSize;
}
public void AddPreReadData(byte[] initialData, int initialOffset, int initialSize)
{
if (_preReadCount > 0)
{
byte[] tempBuffer = _preReadData;
_preReadData = Fx.AllocateByteArray(initialSize + _preReadCount);
Buffer.BlockCopy(tempBuffer, _preReadOffset, _preReadData, 0, _preReadCount);
Buffer.BlockCopy(initialData, initialOffset, _preReadData, _preReadCount, initialSize);
_preReadOffset = 0;
_preReadCount += initialSize;
}
else
{
_preReadData = initialData;
_preReadOffset = initialOffset;
_preReadCount = initialSize;
}
}
public override int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
{
ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
if (_preReadCount > 0)
{
int bytesToCopy = Math.Min(size, _preReadCount);
Buffer.BlockCopy(_preReadData, _preReadOffset, buffer, offset, bytesToCopy);
_preReadOffset += bytesToCopy;
_preReadCount -= bytesToCopy;
return bytesToCopy;
}
return base.Read(buffer, offset, size, timeout);
}
public override AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action<object> callback, object state)
{
ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size);
if (_preReadCount > 0)
{
int bytesToCopy = Math.Min(size, _preReadCount);
Buffer.BlockCopy(_preReadData, _preReadOffset, AsyncReadBuffer, offset, bytesToCopy);
_preReadOffset += bytesToCopy;
_preReadCount -= bytesToCopy;
_asyncBytesRead = bytesToCopy;
return AsyncCompletionResult.Completed;
}
return base.BeginRead(offset, size, timeout, callback, state);
}
public override int EndRead()
{
if (_asyncBytesRead > 0)
{
int retValue = _asyncBytesRead;
_asyncBytesRead = 0;
return retValue;
}
return base.EndRead();
}
}
internal class ConnectionStream : Stream
{
private TimeSpan _closeTimeout;
private int _readTimeout;
private int _writeTimeout;
private IConnection _connection;
private bool _immediate;
private static Action<object> s_onWriteComplete = new Action<object>(OnWriteComplete);
private static Action<object> s_onReadComplete = new Action<object>(OnReadComplete);
public ConnectionStream(IConnection connection, IDefaultCommunicationTimeouts defaultTimeouts)
{
_connection = connection;
_closeTimeout = defaultTimeouts.CloseTimeout;
ReadTimeout = TimeoutHelper.ToMilliseconds(defaultTimeouts.ReceiveTimeout);
WriteTimeout = TimeoutHelper.ToMilliseconds(defaultTimeouts.SendTimeout);
_immediate = true;
}
public IConnection Connection
{
get { return _connection; }
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanTimeout
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public TimeSpan CloseTimeout
{
get { return _closeTimeout; }
set { _closeTimeout = value; }
}
public override int ReadTimeout
{
get { return _readTimeout; }
set
{
if (value < -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.Format(SR.ValueMustBeInRange, -1, int.MaxValue)));
}
_readTimeout = value;
}
}
public override int WriteTimeout
{
get { return _writeTimeout; }
set
{
if (value < -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.Format(SR.ValueMustBeInRange, -1, int.MaxValue)));
}
_writeTimeout = value;
}
}
public bool Immediate
{
get { return _immediate; }
set { _immediate = value; }
}
public override long Length
{
get
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SPS_SeekNotSupported));
}
}
public override long Position
{
get
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SPS_SeekNotSupported));
}
set
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SPS_SeekNotSupported));
}
}
public void Abort()
{
_connection.Abort();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_connection.Close(CloseTimeout, false);
}
}
public override void Flush()
{
// NOP
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// There's room for improvement here to avoid allocation in the synchronous completion case. We could store
// the tcs in ConnectionStream and only allocate if the result is Queued. We would need to return a cached
// completed Task in the success case to also avoid allocation. The race condition of completing async but
// running the callback before the tcs has been allocated would need to be accounted for.
var tcs = new TaskCompletionSource<bool>(this);
var asyncCompletionResult = _connection.BeginWrite(buffer, offset, count, Immediate,
TimeoutHelper.FromMilliseconds(WriteTimeout), s_onWriteComplete, tcs);
if (asyncCompletionResult == AsyncCompletionResult.Completed)
{
_connection.EndWrite();
tcs.TrySetResult(true);
}
return tcs.Task;
}
private static void OnWriteComplete(object state)
{
if (state == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state");
}
var tcs = state as TaskCompletionSource<bool>;
if (tcs == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult);
}
var thisPtr = tcs.Task.AsyncState as ConnectionStream;
if (thisPtr == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult);
}
try
{
thisPtr._connection.EndWrite();
tcs.TrySetResult(true);
}
catch (Exception e)
{
tcs.TrySetException(e);
}
}
public override void Write(byte[] buffer, int offset, int count)
{
_connection.Write(buffer, offset, count, Immediate, TimeoutHelper.FromMilliseconds(WriteTimeout));
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<int>(this);
AsyncCompletionResult asyncCompletionResult = _connection.BeginRead(0, Math.Min(count, _connection.AsyncReadBufferSize),
TimeoutHelper.FromMilliseconds(ReadTimeout), s_onReadComplete, tcs);
if (asyncCompletionResult == AsyncCompletionResult.Completed)
{
tcs.TrySetResult(_connection.EndRead());
}
int bytesRead = await tcs.Task;
Buffer.BlockCopy(_connection.AsyncReadBuffer, 0, buffer, offset, bytesRead);
return bytesRead;
}
private static void OnReadComplete(object state)
{
if (state == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state");
}
var tcs = state as TaskCompletionSource<int>;
if (tcs == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult);
}
var thisPtr = tcs.Task.AsyncState as ConnectionStream;
if (thisPtr == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult);
}
try
{
tcs.TrySetResult(thisPtr._connection.EndRead());
}
catch (Exception e)
{
tcs.TrySetException(e);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return Read(buffer, offset, count, TimeoutHelper.FromMilliseconds(ReadTimeout));
}
protected int Read(byte[] buffer, int offset, int count, TimeSpan timeout)
{
return _connection.Read(buffer, offset, count, timeout);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SPS_SeekNotSupported));
}
public override void SetLength(long value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SPS_SeekNotSupported));
}
}
internal class StreamConnection : IConnection
{
private byte[] _asyncReadBuffer;
private int _bytesRead;
private ConnectionStream _innerStream;
private Action<Task<int>, object> _onRead;
private Action<Task, object> _onWrite;
private Task<int> _readResult;
private Task _writeResult;
private Action<object> _readCallback;
private Action<object> _writeCallback;
private Stream _stream;
public StreamConnection(Stream stream, ConnectionStream innerStream)
{
Contract.Assert(stream != null, "StreamConnection: Stream cannot be null.");
Contract.Assert(innerStream != null, "StreamConnection: Inner stream cannot be null.");
_stream = stream;
_innerStream = innerStream;
_onRead = new Action<Task<int>, object>(OnRead);
_onWrite = new Action<Task, object>(OnWrite);
}
public byte[] AsyncReadBuffer
{
get
{
if (_asyncReadBuffer == null)
{
lock (ThisLock)
{
if (_asyncReadBuffer == null)
{
_asyncReadBuffer = Fx.AllocateByteArray(_innerStream.Connection.AsyncReadBufferSize);
}
}
}
return _asyncReadBuffer;
}
}
public int AsyncReadBufferSize
{
get { return _innerStream.Connection.AsyncReadBufferSize; }
}
public Stream Stream
{
get { return _stream; }
}
public object ThisLock
{
get { return this; }
}
public IPEndPoint RemoteIPEndPoint
{
get
{
throw ExceptionHelper.PlatformNotSupported();
}
}
public void Abort()
{
_innerStream.Abort();
}
private Exception ConvertIOException(IOException ioException)
{
if (ioException.InnerException is TimeoutException)
{
return new TimeoutException(ioException.InnerException.Message, ioException);
}
else if (ioException.InnerException is CommunicationObjectAbortedException)
{
return new CommunicationObjectAbortedException(ioException.InnerException.Message, ioException);
}
else if (ioException.InnerException is CommunicationException)
{
return new CommunicationException(ioException.InnerException.Message, ioException);
}
else
{
return new CommunicationException(SR.StreamError, ioException);
}
}
public void Close(TimeSpan timeout, bool asyncAndLinger)
{
_innerStream.CloseTimeout = timeout;
try
{
_stream.Dispose();
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
public AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
Action<object> callback, object state)
{
Contract.Requires(callback != null, "Cannot call BeginWrite without a callback");
Contract.Requires(_writeCallback == null, "BeginWrite cannot be called twice");
_writeCallback = callback;
bool throwing = true;
try
{
_innerStream.Immediate = immediate;
SetWriteTimeout(timeout);
Task localTask = _stream.WriteAsync(buffer, offset, size);
throwing = false;
if (!localTask.IsCompleted)
{
localTask.ContinueWith(_onWrite, state);
return AsyncCompletionResult.Queued;
}
localTask.GetAwaiter().GetResult();
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
finally
{
if (throwing)
{
_writeCallback = null;
}
}
return AsyncCompletionResult.Completed;
}
public void EndWrite()
{
Task localResult = _writeResult;
_writeResult = null;
_writeCallback = null;
if (localResult != null)
{
try
{
localResult.GetAwaiter().GetResult();
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
}
private void OnWrite(Task antecedent, Object state)
{
Contract.Requires(_writeResult == null, "StreamConnection: OnWrite called twice.");
_writeResult = antecedent;
_writeCallback(state);
}
public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
{
try
{
_innerStream.Immediate = immediate;
SetWriteTimeout(timeout);
_stream.Write(buffer, offset, size);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager)
{
Write(buffer, offset, size, immediate, timeout);
bufferManager.ReturnBuffer(buffer);
}
private void SetReadTimeout(TimeSpan timeout)
{
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
if (_stream.CanTimeout)
{
_stream.ReadTimeout = timeoutInMilliseconds;
}
_innerStream.ReadTimeout = timeoutInMilliseconds;
}
private void SetWriteTimeout(TimeSpan timeout)
{
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
if (_stream.CanTimeout)
{
_stream.WriteTimeout = timeoutInMilliseconds;
}
_innerStream.WriteTimeout = timeoutInMilliseconds;
}
public int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
{
try
{
SetReadTimeout(timeout);
return _stream.Read(buffer, offset, size);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
public AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action<object> callback, object state)
{
ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size);
_readCallback = callback;
try
{
SetReadTimeout(timeout);
Task<int> localTask = _stream.ReadAsync(AsyncReadBuffer, offset, size);
//IAsyncResult localResult = stream.BeginRead(AsyncReadBuffer, offset, size, onRead, state);
if (!localTask.IsCompleted)
{
localTask.ContinueWith(_onRead, state);
return AsyncCompletionResult.Queued;
}
_bytesRead = localTask.GetAwaiter().GetResult();
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
return AsyncCompletionResult.Completed;
}
public int EndRead()
{
Task<int> localResult = _readResult;
_readResult = null;
if (localResult != null)
{
try
{
_bytesRead = localResult.GetAwaiter().GetResult();
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
return _bytesRead;
}
private void OnRead(Task<int> antecedent, object state)
{
Contract.Requires(_readResult == null, "StreamConnection: OnRead called twice.");
_readResult = antecedent;
_readCallback(state);
}
public virtual object GetCoreTransport()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
internal class ConnectionMessageProperty
{
private IConnection _connection;
public ConnectionMessageProperty(IConnection connection)
{
_connection = connection;
}
public static string Name
{
get { return "iconnection"; }
}
public IConnection Connection
{
get { return _connection; }
}
}
internal static class ConnectionUtilities
{
internal static void CloseNoThrow(IConnection connection, TimeSpan timeout)
{
bool success = false;
try
{
connection.Close(timeout, false);
success = true;
}
catch (TimeoutException)
{
}
catch (CommunicationException)
{
}
finally
{
if (!success)
{
connection.Abort();
}
}
}
internal static void ValidateBufferBounds(ArraySegment<byte> buffer)
{
ValidateBufferBounds(buffer.Array, buffer.Offset, buffer.Count);
}
internal static void ValidateBufferBounds(byte[] buffer, int offset, int size)
{
if (buffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
}
ValidateBufferBounds(buffer.Length, offset, size);
}
internal static void ValidateBufferBounds(int bufferSize, int offset, int size)
{
if (offset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.ValueMustBeNonNegative));
}
if (offset > bufferSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.Format(SR.OffsetExceedsBufferSize, bufferSize)));
}
if (size <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size, SR.ValueMustBePositive));
}
int remainingBufferSpace = bufferSize - offset;
if (size > remainingBufferSpace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size, SR.Format(
SR.SizeExceedsRemainingBufferSpace, remainingBufferSpace)));
}
}
}
}
namespace System.ServiceModel.Channels.ConnectionHelpers
{
internal static class IConnectionExtensions
{
// This method is a convenience method for the open/close code paths and shouldn't be used on message send/receive.
internal static async Task WriteAsync(this IConnection connection, byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
{
var tcs = new TaskCompletionSource<bool>();
var result = connection.BeginWrite(buffer, offset, size, immediate, timeout, OnIoComplete, tcs);
if (result == AsyncCompletionResult.Completed)
{
tcs.SetResult(true);
}
await tcs.Task;
connection.EndWrite();
}
// This method is a convenience method for the open/close code paths and shouldn't be used on message send/receive.
internal static async Task<int> ReadAsync(this IConnection connection, int offset, int size, TimeSpan timeout)
{
// read ACK
var tcs = new TaskCompletionSource<bool>();
//ackBuffer
var result = connection.BeginRead(offset, size, timeout, OnIoComplete, tcs);
if (result == AsyncCompletionResult.Completed)
{
tcs.SetResult(true);
}
await tcs.Task;
int ackBytesRead = connection.EndRead();
return ackBytesRead;
}
// This method is a convenience method for the open/close code paths and shouldn't be used on message send/receive.
internal static async Task<int> ReadAsync(this IConnection connection, byte[] buffer, int offset, int size, TimeSpan timeout)
{
int ackBytesRead = await connection.ReadAsync(0, size, timeout);
Buffer.BlockCopy(connection.AsyncReadBuffer, 0, buffer, offset, ackBytesRead);
return ackBytesRead;
}
private static void OnIoComplete(object state)
{
if (state == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state");
}
var tcs = state as TaskCompletionSource<bool>;
if (tcs == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult);
}
tcs.TrySetResult(true);
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="Persisting.cs" company="Appccelerate">
// Copyright (c) 2008-2019 Appccelerate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Specs.Async
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsyncMachine;
using FakeItEasy;
using FluentAssertions;
using Infrastructure;
using Persistence;
using Specs;
using Xbehave;
using ExceptionMessages = Machine.ExceptionMessages;
public class Persisting
{
#pragma warning disable SA1602 // Enumeration items should be documented
public enum State
{
A, B, S, S1, S2
}
public enum Event
{
B, X, S2, S
}
#pragma warning restore SA1602 // Enumeration items should be documented
[Scenario]
public void Loading(
StateMachineSaver<State, Event> saver,
StateMachineLoader<State, Event> loader,
FakeExtension extension,
State sourceState,
State targetState)
{
"establish a saved state machine with history".x(async () =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<State, Event>();
SetupStates(stateMachineDefinitionBuilder);
var machine = stateMachineDefinitionBuilder
.WithInitialState(State.A)
.Build()
.CreatePassiveStateMachine();
await machine.Start();
await machine.Fire(Event.S2); // set history of super state S
await machine.Fire(Event.B); // set current state to B
saver = new StateMachineSaver<State, Event>();
loader = new StateMachineLoader<State, Event>();
await machine.Save(saver);
});
"when state machine is loaded".x(async () =>
{
loader.SetCurrentState(saver.CurrentStateId);
loader.SetHistoryStates(saver.HistoryStates);
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<State, Event>();
SetupStates(stateMachineDefinitionBuilder);
var loadedMachine = stateMachineDefinitionBuilder
.WithInitialState(State.A)
.Build()
.CreatePassiveStateMachine();
extension = new FakeExtension();
loadedMachine.AddExtension(extension);
await loadedMachine.Load(loader);
loadedMachine.TransitionCompleted += (sender, args) =>
{
sourceState = args.StateId;
targetState = args.NewStateId;
};
await loadedMachine.Start();
await loadedMachine.Fire(Event.S);
});
"it should reset current state".x(() =>
sourceState.Should().Be(State.B));
"it should reset all history states of super states".x(() =>
targetState.Should().Be(State.S2));
"it should notify extensions".x(()
=> extension
.LoadedCurrentState
.Should()
.BeEquivalentTo(Initializable<State>.Initialized(State.B)));
}
[Scenario]
public void LoadingNonInitializedStateMachine(
AsyncPassiveStateMachine<State, Event> loadedMachine)
{
"when a non-initialized state machine is loaded".x(async () =>
{
var loader = new StateMachineLoader<State, Event>();
loader.SetCurrentState(Initializable<State>.UnInitialized());
loader.SetHistoryStates(new Dictionary<State, State>());
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<State, Event>();
SetupStates(stateMachineDefinitionBuilder);
loadedMachine = stateMachineDefinitionBuilder
.WithInitialState(State.A)
.Build()
.CreatePassiveStateMachine();
await loadedMachine.Load(loader);
});
"it should not be initialized already".x(async () =>
{
var stateMachineSaver = new StateMachineSaver<State, Event>();
await loadedMachine.Save(stateMachineSaver);
stateMachineSaver
.CurrentStateId
.IsInitialized
.Should()
.BeFalse();
});
}
[Scenario]
public void LoadingAnInitializedStateMachine(
IAsyncStateMachine<string, int> machine,
Exception receivedException)
{
"establish an started state machine".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<string, int>();
stateMachineDefinitionBuilder.In("initial");
machine = stateMachineDefinitionBuilder
.WithInitialState("initial")
.Build()
.CreatePassiveStateMachine();
machine.Start();
});
"when state machine is loaded".x(async () =>
receivedException = await Catch.Exception(async () =>
await machine.Load(A.Fake<IAsyncStateMachineLoader<string, int>>())));
"it should throw invalid operation exception".x(() =>
{
receivedException.Should().BeOfType<InvalidOperationException>();
receivedException.Message.Should().Be(ExceptionMessages.StateMachineIsAlreadyInitialized);
});
}
[Scenario]
public void SavingEventsForPassiveStateMachine(
AsyncPassiveStateMachine<string, int> machine,
StateMachineSaver<string, int> saver)
{
"establish a state machine".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<string, int>();
stateMachineDefinitionBuilder
.In("A")
.On(1)
.Goto("B");
stateMachineDefinitionBuilder
.In("B")
.On(2)
.Goto("C");
stateMachineDefinitionBuilder
.In("C")
.On(3)
.Goto("A");
machine = stateMachineDefinitionBuilder
.WithInitialState("A")
.Build()
.CreatePassiveStateMachine();
});
"when events are fired".x(async () =>
{
await machine.Fire(1);
await machine.Fire(2);
await machine.FirePriority(3);
await machine.FirePriority(4);
});
"and it is saved".x(async () =>
{
saver = new StateMachineSaver<string, int>();
await machine.Save(saver);
});
"it should save those events".x(() =>
{
saver
.Events
.Select(x => x.EventId)
.Should()
.HaveCount(2)
.And
.ContainInOrder(1, 2);
saver
.PriorityEvents
.Select(x => x.EventId)
.Should()
.HaveCount(2)
.And
.ContainInOrder(4, 3);
});
}
[Scenario]
public void LoadingEventsForPassiveStateMachine(
AsyncPassiveStateMachine<string, int> machine)
{
"establish a passive state machine".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<string, int>();
stateMachineDefinitionBuilder
.In("A")
.On(1)
.Goto("B");
stateMachineDefinitionBuilder
.In("B")
.On(2)
.Goto("C");
stateMachineDefinitionBuilder
.In("C")
.On(3)
.Goto("A");
machine = stateMachineDefinitionBuilder
.WithInitialState("A")
.Build()
.CreatePassiveStateMachine();
});
"when it is loaded with Events".x(async () =>
{
var firstEvent = new EventInformation<int>(2, null);
var secondEvent = new EventInformation<int>(3, null);
var priorityEvent = new EventInformation<int>(1, null);
var loader = new StateMachineLoader<string, int>();
loader.SetEvents(new List<EventInformation<int>>
{
firstEvent,
secondEvent,
});
loader.SetPriorityEvents(new List<EventInformation<int>>
{
priorityEvent
});
var extension = A.Fake<IExtension<string, int>>();
machine.AddExtension(extension);
await machine.Load(loader);
A.CallTo(() => extension.Loaded(
A<IStateMachineInformation<string, int>>.Ignored,
A<Initializable<string>>.Ignored,
A<IReadOnlyDictionary<string, string>>.Ignored,
A<IReadOnlyCollection<EventInformation<int>>>
.That
.Matches(c =>
c.Count == 2
&& c.Contains(firstEvent)
&& c.Contains(secondEvent)),
A<IReadOnlyCollection<EventInformation<int>>>
.That
.Matches(c =>
c.Count == 1
&& c.Contains(priorityEvent))))
.MustHaveHappenedOnceExactly();
});
"it should process those events".x(async () =>
{
var transitionRecords = new List<TransitionRecord>();
machine.TransitionCompleted += (sender, args) =>
transitionRecords.Add(
new TransitionRecord(args.EventId, args.StateId, args.NewStateId));
await machine.Start();
transitionRecords
.Should()
.HaveCount(3)
.And
.IsEquivalentInOrder(new List<TransitionRecord>
{
new TransitionRecord(1, "A", "B"),
new TransitionRecord(2, "B", "C"),
new TransitionRecord(3, "C", "A")
});
});
}
[Scenario]
public void SavingEventsForActiveStateMachine(
AsyncActiveStateMachine<string, int> machine,
StateMachineSaver<string, int> saver)
{
"establish a state machine".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<string, int>();
stateMachineDefinitionBuilder
.In("A")
.On(1)
.Goto("B");
stateMachineDefinitionBuilder
.In("B")
.On(2)
.Goto("C");
stateMachineDefinitionBuilder
.In("C")
.On(3)
.Goto("A");
machine = stateMachineDefinitionBuilder
.WithInitialState("A")
.Build()
.CreateActiveStateMachine();
});
"when events are fired".x(async () =>
{
await machine.Fire(1);
await machine.Fire(2);
await machine.FirePriority(3);
await machine.FirePriority(4);
});
"and it is saved".x(async () =>
{
saver = new StateMachineSaver<string, int>();
await machine.Save(saver);
});
"it should save those events".x(() =>
{
saver
.Events
.Select(x => x.EventId)
.Should()
.HaveCount(2)
.And
.ContainInOrder(1, 2);
saver
.PriorityEvents
.Select(x => x.EventId)
.Should()
.HaveCount(2)
.And
.ContainInOrder(4, 3);
});
}
[Scenario]
public void LoadingEventsForActiveStateMachine(
AsyncActiveStateMachine<string, int> machine)
{
"establish a passive state machine".x(() =>
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<string, int>();
stateMachineDefinitionBuilder
.In("A")
.On(1)
.Goto("B");
stateMachineDefinitionBuilder
.In("B")
.On(2)
.Goto("C");
stateMachineDefinitionBuilder
.In("C")
.On(3)
.Goto("A");
machine = stateMachineDefinitionBuilder
.WithInitialState("A")
.Build()
.CreateActiveStateMachine();
});
"when it is loaded with Events".x(async () =>
{
var firstEvent = new EventInformation<int>(2, null);
var secondEvent = new EventInformation<int>(3, null);
var priorityEvent = new EventInformation<int>(1, null);
var loader = new StateMachineLoader<string, int>();
loader.SetEvents(new List<EventInformation<int>>
{
firstEvent,
secondEvent,
});
loader.SetPriorityEvents(new List<EventInformation<int>>
{
priorityEvent
});
var extension = A.Fake<IExtension<string, int>>();
machine.AddExtension(extension);
await machine.Load(loader);
A.CallTo(() => extension.Loaded(
A<IStateMachineInformation<string, int>>.Ignored,
A<Initializable<string>>.Ignored,
A<IReadOnlyDictionary<string, string>>.Ignored,
A<IReadOnlyCollection<EventInformation<int>>>
.That
.Matches(c =>
c.Count == 2
&& c.Contains(firstEvent)
&& c.Contains(secondEvent)),
A<IReadOnlyCollection<EventInformation<int>>>
.That
.Matches(c =>
c.Count == 1
&& c.Contains(priorityEvent))))
.MustHaveHappenedOnceExactly();
});
"it should process those events".x(async () =>
{
var transitionRecords = new List<TransitionRecord>();
machine.TransitionCompleted += (sender, args) =>
transitionRecords.Add(
new TransitionRecord(args.EventId, args.StateId, args.NewStateId));
var signal = SetUpWaitForAllTransitions(machine, 3);
await machine.Start();
WaitForAllTransitions(signal);
transitionRecords
.Should()
.HaveCount(3)
.And
.IsEquivalentInOrder(new List<TransitionRecord>
{
new TransitionRecord(1, "A", "B"),
new TransitionRecord(2, "B", "C"),
new TransitionRecord(3, "C", "A")
});
});
}
private static void SetupStates(StateMachineDefinitionBuilder<State, Event> builder)
{
builder
.In(State.A)
.On(Event.S2).Goto(State.S2)
.On(Event.X);
builder
.In(State.B)
.On(Event.S).Goto(State.S)
.On(Event.X);
builder
.DefineHierarchyOn(State.S)
.WithHistoryType(HistoryType.Deep)
.WithInitialSubState(State.S1)
.WithSubState(State.S2);
builder
.In(State.S)
.On(Event.B).Goto(State.B);
}
private static AutoResetEvent SetUpWaitForAllTransitions<TState, TEvent>(IAsyncStateMachine<TState, TEvent> testee, int numberOfTransitionCompletedMessages)
where TState : IComparable
where TEvent : IComparable
{
var numberOfTransitionCompletedMessagesReceived = 0;
var allTransitionsCompleted = new AutoResetEvent(false);
testee.TransitionCompleted += (sender, e) =>
{
numberOfTransitionCompletedMessagesReceived++;
if (numberOfTransitionCompletedMessagesReceived == numberOfTransitionCompletedMessages)
{
allTransitionsCompleted.Set();
}
};
return allTransitionsCompleted;
}
private static void WaitForAllTransitions(AutoResetEvent allTransitionsCompleted)
{
allTransitionsCompleted.WaitOne(1000)
.Should().BeTrue("not enough transition completed events received within time-out.");
}
public class TransitionRecord
{
public int EventId { get; }
public string Source { get; }
public string Destination { get; }
public TransitionRecord(int eventId, string source, string destination)
{
this.EventId = eventId;
this.Source = source;
this.Destination = destination;
}
}
public class FakeExtension : AsyncExtensionBase<State, Event>
{
public List<IInitializable<State>> LoadedCurrentState { get; } = new List<IInitializable<State>>();
public override Task Loaded(
IStateMachineInformation<State, Event> stateMachineInformation,
IInitializable<State> loadedCurrentState,
IReadOnlyDictionary<State, State> loadedHistoryStates,
IReadOnlyCollection<EventInformation<Event>> events,
IReadOnlyCollection<EventInformation<Event>> priorityEvents)
{
this.LoadedCurrentState.Add(loadedCurrentState);
return Task.CompletedTask;
}
}
public class StateMachineSaver<TState, TEvent> : IAsyncStateMachineSaver<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
public IInitializable<TState> CurrentStateId { get; private set; }
public IReadOnlyDictionary<TState, TState> HistoryStates { get; private set; }
public IReadOnlyCollection<EventInformation<TEvent>> Events { get; private set; }
public IReadOnlyCollection<EventInformation<TEvent>> PriorityEvents { get; private set; }
public Task SaveCurrentState(IInitializable<TState> currentState)
{
this.CurrentStateId = currentState;
return Task.CompletedTask;
}
public Task SaveHistoryStates(IReadOnlyDictionary<TState, TState> historyStates)
{
this.HistoryStates = historyStates;
return Task.CompletedTask;
}
public Task SaveEvents(IReadOnlyCollection<EventInformation<TEvent>> events)
{
this.Events = events;
return Task.CompletedTask;
}
public Task SavePriorityEvents(IReadOnlyCollection<EventInformation<TEvent>> priorityEvents)
{
this.PriorityEvents = priorityEvents;
return Task.CompletedTask;
}
}
public class StateMachineLoader<TState, TEvent> : IAsyncStateMachineLoader<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private IInitializable<TState> currentState = Initializable<TState>.UnInitialized();
private IReadOnlyDictionary<TState, TState> historyStates = new Dictionary<TState, TState>();
private IReadOnlyCollection<EventInformation<TEvent>> events = new List<EventInformation<TEvent>>();
private IReadOnlyCollection<EventInformation<TEvent>> priorityEvents = new List<EventInformation<TEvent>>();
public void SetCurrentState(IInitializable<TState> state)
{
this.currentState = state;
}
public void SetHistoryStates(IReadOnlyDictionary<TState, TState> states)
{
this.historyStates = states;
}
public Task<IReadOnlyDictionary<TState, TState>> LoadHistoryStates()
{
return Task.FromResult(this.historyStates);
}
public Task<IInitializable<TState>> LoadCurrentState()
{
return Task.FromResult(this.currentState);
}
public Task<IReadOnlyCollection<EventInformation<TEvent>>> LoadEvents()
{
return Task.FromResult(this.events);
}
public Task<IReadOnlyCollection<EventInformation<TEvent>>> LoadPriorityEvents()
{
return Task.FromResult(this.priorityEvents);
}
public void SetEvents(IReadOnlyCollection<EventInformation<TEvent>> events)
{
this.events = events;
}
public void SetPriorityEvents(IReadOnlyCollection<EventInformation<TEvent>> priorityEvents)
{
this.priorityEvents = priorityEvents;
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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 System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.MultiverseInterfaceStudio.FrameXml.Controls;
using Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization;
using Microsoft.MultiverseInterfaceStudio.Services;
namespace Microsoft.MultiverseInterfaceStudio.FrameXml
{
public partial class FrameXmlDesignerLoader : BasicDesignerLoader
{
#region members
private const string hostedBaseClassName = "UserControl";
/// <summary>
/// Publishes the loader host
/// </summary>
/// <value>The loader host.</value>
public IDesignerLoaderHost Host
{
get { return this.LoaderHost; }
}
public string DocumentMoniker { get; private set; }
private IVsTextLines textLines;
private uint ItemID { get; set; }
#endregion
#region construction and dispose
/// <summary>
/// Holds a reference for every designer loader opened. This map is indexed by itemId.
/// </summary>
private static SortedDictionary<uint, FrameXmlDesignerLoader> designerLoaders = new SortedDictionary<uint, FrameXmlDesignerLoader>();
/// <summary>
/// Represents the ItemID of the active designer. It is set by the SelectionEventsMonitor
/// </summary>
/// <value>The active designer's itemID.</value>
public static uint ActiveItemID { get; set; }
/// <summary>
/// Gets the active designer loader.
/// </summary>
/// <value>The active designer loader.</value>
public static FrameXmlDesignerLoader ActiveDesignerLoader
{
get
{
if (designerLoaders.ContainsKey(ActiveItemID))
return designerLoaders[ActiveItemID];
return null;
}
}
public FrameXmlDesignerLoader(IVsTextLines textLines, string documentMoniker, uint itemid)
{
this.textLines = textLines;
this.DocumentMoniker = documentMoniker;
this.ItemID = itemid;
if (designerLoaders.Remove(itemid))
{
Trace.WriteLine(String.Format("A designer loader with the id {0} already existsed and has been removed.", itemid));
}
designerLoaders.Add(itemid, this);
ActiveItemID = itemid;
this.IsSerializing = true;
}
public override void Dispose()
{
this.IsLoading = true;
try
{
designerLoaders.Remove(this.ItemID);
DestroyControls();
}
finally
{
this.IsLoading = false;
base.Dispose();
}
}
#endregion
#region serialization
private static void ValidateOnWrite(string xml)
{
XmlReaderSettings readerSettings = Serialization.XmlSettings.CreateReaderSettings();
using (StringReader stringReader = new StringReader(xml))
using (XmlReader reader = XmlReader.Create(stringReader, readerSettings))
{
while (reader.Read()) ;
}
}
public string VirtualControlName { get; set; }
public bool IsSerializing { get; set; }
private string SerializeFrameXml(Serialization.SerializationObject ui)
{
const string xmlIndentChars = "\t";
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = xmlIndentChars;
settings.OmitXmlDeclaration = true;
this.IsSerializing = true;
try
{
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
XmlSerializer serializer = new XmlSerializer(typeof(Serialization.Ui));
serializer.Serialize(writer, ui);
}
}
finally
{
this.IsSerializing = false;
}
return sb.ToString();
}
private Serialization.Ui DeserializeFrameXml(string buffer)
{
var useSchema = true;
return DeserializeFrameXml(buffer, useSchema);
}
private Serialization.Ui DeserializeFrameXml(string buffer, bool useSchema)
{
XmlReaderSettings readerSettings = Serialization.XmlSettings.CreateReaderSettings(ref useSchema);
this.IsSerializing = true;
try
{
using (StringReader stringReader = new StringReader(buffer))
using (XmlReader xmlReader = XmlReader.Create(stringReader, readerSettings))
{
XmlSerializer serializer = new XmlSerializer(typeof(Serialization.Ui));
var ui = (Serialization.Ui)serializer.Deserialize(xmlReader);
PostProcessSerializationHierarchy(ui);
return ui;
}
}
catch (InvalidOperationException exception)
{
if (useSchema)
{
var message = exception.InnerException == null ?
exception.Message :
exception.InnerException.Message;
message = String.Format(VSPackage.DISABLE_SCHEMA, message);
bool tryWithoutSchema = MessageBox.Show(message, null, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
if (tryWithoutSchema)
return DeserializeFrameXml(buffer, false);
}
if (exception.InnerException != null)
throw exception.InnerException;
throw;
}
finally
{
this.IsSerializing = false;
}
}
private void PostProcessSerializationHierarchy(Serialization.Ui ui)
{
foreach (var layoutFrame in ui.Controls.OfType<LayoutFrameType>())
{
PostProcessSerializationHierarchy(layoutFrame, null);
}
}
private void PostProcessSerializationHierarchy(LayoutFrameType layoutFrame, LayoutFrameType parent)
{
layoutFrame.Parent = parent;
foreach (var child in layoutFrame.Children)
{
PostProcessSerializationHierarchy(child, layoutFrame);
}
}
/// <summary>
/// Retrieves the serialization object hierarchy from the controls
/// </summary>
/// <returns></returns>
private static SerializationObject GetSerializationObject(Controls.ISerializableControl serializableControl)
{
SerializationObject serializableObject = serializableControl.SerializationObject;
serializableObject.Controls.Clear();
Controls.IFrameControl parentFrame = serializableControl as Controls.IFrameControl;
if (parentFrame != null)
{
if (parentFrame.Frames.Count<Controls.IFrameControl>() > 0)
{
FrameTypeFrames frames = new FrameTypeFrames();
serializableObject.Controls.Add(frames);
foreach (var childFrame in parentFrame.Frames)
{
SerializationObject childObject = GetSerializationObject(childFrame);
frames.Controls.Add(childObject);
}
}
Serialization.FrameType frameType = serializableObject as Serialization.FrameType;
if (frameType != null)
{
Dictionary<DRAWLAYER, FrameTypeLayersLayer> layerDictionary = new Dictionary<DRAWLAYER, FrameTypeLayersLayer>();
foreach (Controls.ILayerable layerable in parentFrame.Layerables)
{
if (!layerDictionary.ContainsKey(layerable.LayerLevel))
layerDictionary.Add(layerable.LayerLevel, new FrameTypeLayersLayer());
FrameTypeLayersLayer layer = layerDictionary[layerable.LayerLevel];
layer.level = layerable.LayerLevel;
layer.Layerables.Add(layerable.SerializationObject);
}
frameType.LayersList.Clear();
if (layerDictionary.Count > 0)
{
FrameTypeLayers layers = new FrameTypeLayers();
layers.Layer.AddRange(layerDictionary.Values);
frameType.LayersList.Add(layers);
}
}
}
return serializableObject;
}
/// <summary>
/// Retrieves the serialization object hierarchy of the root control.
/// </summary>
/// <returns></returns>
private Serialization.Ui GetSerializationObject()
{
Controls.Ui rootControl = this.RootControl;
Serialization.Ui rootObject = rootControl.TypedSerializationObject;
// remove objects that are shown in the view - they will be serialized
rootObject.Controls.RemoveAll(obj => objectsInView.Contains(obj));
List<SerializationObject> objects = new List<SerializationObject>(rootObject.Controls);
foreach (Controls.ISerializableControl childControl in rootControl.BaseControls)
{
Serialization.SerializationObject childObject = GetSerializationObject(childControl);
objects.Add(childObject);
// add eventual new controls to the view
if (!objectsInView.Contains(childObject))
objectsInView.Add(childObject);
}
rootObject.Controls.Clear();
rootObject.Controls.AddRange(objects.SortRootObjects());
return rootObject;
}
#endregion
#region document handling
private string GetText()
{
int line, index;
string buffer;
if (textLines.GetLastLineIndex(out line, out index) != VSConstants.S_OK)
return String.Empty;
if (textLines.GetLineText(0, 0, line, index, out buffer) != VSConstants.S_OK)
return String.Empty;
return buffer;
}
private void SetText(string text)
{
try
{
FrameXmlDesignerLoader.ValidateOnWrite(text);
}
catch (Exception ex)
{
// TODO: show error in the Error List
Trace.WriteLine(ex);
}
int endLine, endCol;
textLines.GetLastLineIndex(out endLine, out endCol);
int len = (text == null) ? 0 : text.Length;
//fix location of the string
IntPtr pText = Marshal.StringToCoTaskMemAuto(text);
try
{
textLines.ReplaceLines(0, 0, endLine, endCol, pText, len, null);
}
finally
{
Marshal.FreeCoTaskMem(pText);
}
}
private string Buffer
{
get { return GetText(); }
set
{
SetText(value);
}
}
private Serialization.Ui frameXmlHierarchy = null;
/// <summary>
/// Loads a designer from persistence.
/// </summary>
/// <param name="serializationManager">An <see cref="T:System.ComponentModel.Design.Serialization.IDesignerSerializationManager"/> to use for loading state for the designers.</param>
protected override void PerformLoad(IDesignerSerializationManager serializationManager)
{
// The loader will put error messages in here.
ICollection errors = new ArrayList();
bool successful = true;
Trace.WriteLine("PerformLoad");
frameXmlHierarchy = DeserializeFrameXml(this.Buffer);
this.LayoutFrames = new LayoutFrameCollection(frameXmlHierarchy);
this.CreateRootControl(frameXmlHierarchy);
// Query for the settings service and get the background image setting
IInterfaceStudioSettings settings = GetService(typeof(IInterfaceStudioSettings)) as IInterfaceStudioSettings;
if (settings != null)
this.RootControl.BackgroundImagePath = settings.BackgroundImageFile;
// Add PropertyValueUIHandler to PropertyValueUIService
this.AddPropertyValueUIHandler();
// Let the host know we are done loading.
Host.EndLoad(FrameXmlDesignerLoader.hostedBaseClassName, successful, errors);
}
private void AddPropertyValueUIHandler()
{
IPropertyValueUIService uiService = (IPropertyValueUIService)Host.GetService(typeof(IPropertyValueUIService));
if (uiService != null)
uiService.AddPropertyValueUIHandler(new PropertyValueUIHandler(this.InheritedPropertyValueUIHandler));
}
private FrameXmlPane frameXmlPane = null;
public void InitializeFrameXmlPane(FrameXmlPane frameXmlPane)
{
this.frameXmlPane = frameXmlPane;
ReloadControls();
if (frameXmlPane != null)
{
frameXmlPane.SelectedPaneChanged += new EventHandler(frameXmlPane_SelectedPaneChanged);
}
}
void frameXmlPane_SelectedPaneChanged(object sender, EventArgs e)
{
this.VirtualControlName = frameXmlPane.SelectedPane;
ReloadControls();
}
/// <summary>
/// Flushes all changes to the designer.
/// </summary>
/// <param name="serializationManager">An <see cref="T:System.ComponentModel.Design.Serialization.IDesignerSerializationManager"/> to use for persisting the state of loaded designers.</param>
protected override void PerformFlush(IDesignerSerializationManager serializationManager)
{
bool success = true;
ArrayList errors = new ArrayList();
IDesignerHost idh = (IDesignerHost)this.Host.GetService(typeof(IDesignerHost));
Controls.ISerializableControl serializable = (LoaderHost.RootComponent as Controls.ISerializableControl);
if (serializable == null)
{
throw new ApplicationException("Invalid root control type in designer.");
}
Serialization.SerializationObject serializationObject = this.GetSerializationObject();
try
{
this.Buffer = this.SerializeFrameXml(serializationObject);
}
catch (Exception exception)
{
Debug.WriteLine(exception);
success = false;
errors.Add(exception);
}
IDesignerLoaderHost host = this.LoaderHost;
host.EndLoad(FrameXmlDesignerLoader.hostedBaseClassName, success, errors);
Trace.WriteLine("PerformFlush");
}
#endregion
#region inherits support
public LayoutFrameCollection LayoutFrames { get; private set; }
#endregion
public void NotifyControlRemoval(Control control)
{
if (!IsLoading)
{
OnPropertyChanged(control, new PropertyChangedEventArgs("deleted"));
}
}
#region property change handling
public void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "virtual":
OnVirtualChanged(sender);
break;
case "name":
OnNameChanged(sender);
break;
}
Serialization.SerializationObject ui = GetSerializationObject();
this.Buffer = this.SerializeFrameXml(ui);
// Refresh the property browser
this.RefreshPropertyBrowser();
}
public void RefreshPropertyBrowser()
{
IVsUIShell shell = this.GetService(typeof(SVsUIShell)) as IVsUIShell;
if (shell != null)
shell.RefreshPropertyBrowser(0);
}
private void OnNameChanged(object sender)
{
BaseControl baseControl = sender as BaseControl;
if (baseControl == null)
return;
if (baseControl.LayoutFrameType.@virtual)
{
VirtualControlName = baseControl.LayoutFrameType.name;
RecreateFrameXmlPanes();
}
}
private void OnVirtualChanged(object sender)
{
BaseControl baseControl = sender as BaseControl;
if (baseControl == null)
return;
var paneName = baseControl.LayoutFrameType.@virtual ?
baseControl.Name : null;
VirtualControlName = paneName;
ReloadControls();
}
#endregion
private void InheritedPropertyValueUIHandler(ITypeDescriptorContext context, PropertyDescriptor propertyDescriptor, ArrayList itemList)
{
if (propertyDescriptor.Attributes.Cast<Attribute>().Any(attribute => attribute is InheritedAttribute))
{
Bitmap bitmap = VSPackage.InheritedGlyph;
bitmap.MakeTransparent();
// Add glyph, no click event handler for now
itemList.Add(new PropertyValueUIItem(bitmap, delegate { }, "Inherited Property"));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.Serialization
{
public static class __SerializationInfo
{
public static IObservable<System.Reactive.Unit> SetType(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.Type> type)
{
return ObservableExt.ZipExecute(SerializationInfoValue, type,
(SerializationInfoValueLambda, typeLambda) => SerializationInfoValueLambda.SetType(typeLambda));
}
public static IObservable<System.Runtime.Serialization.SerializationInfoEnumerator> GetEnumerator(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.GetEnumerator());
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Object> value, IObservable<System.Type> type)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value, type,
(SerializationInfoValueLambda, nameLambda, valueLambda, typeLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda, typeLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Object> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Char> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.SByte> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Byte> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Int16> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.UInt16> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Int32> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.UInt32> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Int64> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.UInt64> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Single> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Double> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Decimal> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Reactive.Unit> AddValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.DateTime> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, name, value,
(SerializationInfoValueLambda, nameLambda, valueLambda) =>
SerializationInfoValueLambda.AddValue(nameLambda, valueLambda));
}
public static IObservable<System.Object> GetValue(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name, IObservable<System.Type> type)
{
return Observable.Zip(SerializationInfoValue, name, type,
(SerializationInfoValueLambda, nameLambda, typeLambda) =>
SerializationInfoValueLambda.GetValue(nameLambda, typeLambda));
}
public static IObservable<System.Boolean> GetBoolean(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetBoolean(nameLambda));
}
public static IObservable<System.Char> GetChar(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetChar(nameLambda));
}
public static IObservable<System.SByte> GetSByte(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetSByte(nameLambda));
}
public static IObservable<System.Byte> GetByte(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetByte(nameLambda));
}
public static IObservable<System.Int16> GetInt16(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetInt16(nameLambda));
}
public static IObservable<System.UInt16> GetUInt16(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetUInt16(nameLambda));
}
public static IObservable<System.Int32> GetInt32(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetInt32(nameLambda));
}
public static IObservable<System.UInt32> GetUInt32(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetUInt32(nameLambda));
}
public static IObservable<System.Int64> GetInt64(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetInt64(nameLambda));
}
public static IObservable<System.UInt64> GetUInt64(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetUInt64(nameLambda));
}
public static IObservable<System.Single> GetSingle(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetSingle(nameLambda));
}
public static IObservable<System.Double> GetDouble(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetDouble(nameLambda));
}
public static IObservable<System.Decimal> GetDecimal(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetDecimal(nameLambda));
}
public static IObservable<System.DateTime> GetDateTime(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetDateTime(nameLambda));
}
public static IObservable<System.String> GetString(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> name)
{
return Observable.Zip(SerializationInfoValue, name,
(SerializationInfoValueLambda, nameLambda) => SerializationInfoValueLambda.GetString(nameLambda));
}
public static IObservable<System.String> get_FullTypeName(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.FullTypeName);
}
public static IObservable<System.String> get_AssemblyName(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.AssemblyName);
}
public static IObservable<System.Int32> get_MemberCount(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.MemberCount);
}
public static IObservable<System.Type> get_ObjectType(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.ObjectType);
}
public static IObservable<System.Boolean> get_IsFullTypeNameSetExplicit(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.IsFullTypeNameSetExplicit);
}
public static IObservable<System.Boolean> get_IsAssemblyNameSetExplicit(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue)
{
return Observable.Select(SerializationInfoValue,
(SerializationInfoValueLambda) => SerializationInfoValueLambda.IsAssemblyNameSetExplicit);
}
public static IObservable<System.Reactive.Unit> set_FullTypeName(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, value,
(SerializationInfoValueLambda, valueLambda) => SerializationInfoValueLambda.FullTypeName = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_AssemblyName(
this IObservable<System.Runtime.Serialization.SerializationInfo> SerializationInfoValue,
IObservable<System.String> value)
{
return ObservableExt.ZipExecute(SerializationInfoValue, value,
(SerializationInfoValueLambda, valueLambda) => SerializationInfoValueLambda.AssemblyName = valueLambda);
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.IO;
using Xunit;
public class File_Create_str_i
{
public static String s_strActiveBugNums = "";
public static String s_strDtTmVer = "2009/02/18";
public static String s_strClassMethod = "File.Create(String,Int32)";
public static String s_strTFName = "Create_str_i.cs";
public static String s_strTFPath = Directory.GetCurrentDirectory();
[Fact]
public static void runTest()
{
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
try
{
Stream fs2;
// [] ArgumentNullException for null argument
//----------------------------------------------------------------
strLoc = "Loc_89y8b";
iCountTestcases++;
try
{
fs2 = File.Create(null, 1);
iCountErrors++;
printerr("Error_298yr! Expected exception not thrown");
fs2.Dispose();
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_987b7! Incorrect exception thrown, exc==" + exc.ToString());
}
//----------------------------------------------------------------
// [] AccessException if passing in currentdirectory
//----------------------------------------------------------------
strLoc = "Loc_t7y84";
iCountTestcases++;
try
{
fs2 = File.Create(".", 1);
iCountErrors++;
printerr("Error_7858c! Expected exception not thrown");
fs2.Dispose();
}
catch (UnauthorizedAccessException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_958vy! Incorrect exception thrown, ex==" + exc.ToString());
}
//----------------------------------------------------------------
// [] ArgumentException if zero length string is passed in
//----------------------------------------------------------------
strLoc = "Loc_8t87b";
iCountTestcases++;
try
{
fs2 = File.Create(String.Empty, 1);
iCountErrors++;
printerr("Error_598yb! Expected exception not thrown");
fs2.Dispose();
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_9t5y! Incorrect exception thrown, exc==" + exc.ToString());
}
// [] ArgumentOutOfRangeException if buffer is negative
strLoc = "Loc_t98x9";
iCountTestcases++;
try
{
fs2 = File.Create(filName, -10);
iCountErrors++;
printerr("Error_598cy! Expected exception not thrown");
fs2.Dispose();
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_928xy! Incorrect exception thrown, exc==" + exc.ToString());
}
// [] Create a file
strLoc = "Loc_887th";
fs2 = File.Create(filName, 1000);
iCountTestcases++;
if (!File.Exists(filName))
{
iCountErrors++;
printerr("Error_2876g! File not created, file==" + filName);
}
iCountTestcases++;
if (fs2.Length != 0)
{
iCountErrors++;
printerr("Error_t598v! Incorrect file length==" + fs2.Length);
}
if (fs2.Position != 0)
{
iCountErrors++;
printerr("Error_958bh! Incorrect file position==" + fs2.Position);
}
fs2.Dispose();
// [] Create a file in root
/* Test disabled because it modifies state outside the current working directory
strLoc = "Loc_89ytb";
iCountTestcases++;
bool expectSuccess = true;
#if TEST_WINRT
expectSuccess = false; // We will not have access to root
#endif
String currentdir = TestInfo.CurrentDirectory;
filName = currentdir.Substring(0, currentdir.IndexOf('\\') + 1) + Path.GetFileName(filName);
try
{
fs2 = File.Create(filName, 1000);
if (expectSuccess)
{
if (!File.Exists(filName))
{
iCountErrors++;
printerr("Error_t78g7! File not created, file==" + filName);
}
}
else
{
iCountErrors++;
printerr("Error_254d! User is not Administrator but no exception thrown, file==" + filName);
}
fs2.Dispose();
if (File.Exists(filName))
File.Delete(filName);
}
catch (UnauthorizedAccessException ex)
{
if (expectSuccess)
{
iCountErrors++;
printerr("Error_409t! User is Administrator but exception was thrown:" + ex.ToString());
}
}
*/
// [] Create file in current dir by giving full directory check casing as well
strLoc = "loc_89tbh";
filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
fs2 = File.Create(filName, 100);
iCountTestcases++;
if (!File.Exists(filName))
{
iCountErrors++;
printerr("Error_t87gy! File not created, file==" + filName);
}
fs2.Dispose();
strLoc = "loc_89tbh_1";
//see VSWhidbey bug 103341
filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
if (File.Exists(filName))
File.Delete(filName);
fs2 = File.Create(String.Format(" {0}", filName), 100);
iCountTestcases++;
if (!File.Exists(filName))
{
iCountErrors++;
printerr("Error_t87gy_1! File not created, file==" + filName);
}
fs2.Dispose();
strLoc = "loc_89tbh_3";
//see VSWhidbey bug 103341
filName = Path.Combine(" " + TestInfo.CurrentDirectory, " " + Path.GetRandomFileName());
if (File.Exists(filName))
File.Delete(filName);
fs2 = File.Create(filName, 100);
iCountTestcases++;
if (!File.Exists(filName))
{
iCountErrors++;
printerr("Error_t87gy_3! File not created, file==" + filName);
}
fs2.Dispose();
if (File.Exists(filName))
File.Delete(filName);
#if !TEST_WINRT // Leading spaces in a relative path: relative path will not actually go through WinRT & we'll get access denied
strLoc = "loc_89tbh_2";
filName = String.Format(" {0}", Path.GetRandomFileName());
if (File.Exists(filName))
File.Delete(filName);
fs2 = File.Create(filName, 100);
iCountTestcases++;
filName = Path.Combine(Directory.GetCurrentDirectory(), filName);
if (!File.Exists(filName))
{
iCountErrors++;
Console.WriteLine("Error_t87gy_2! File not created, file==<{0}>", filName);
}
fs2.Dispose();
if (File.Exists(filName))
File.Delete(filName);
#endif
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors != 0)
{
Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString());
}
Assert.Equal(0, iCountErrors);
}
public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err);
}
}
| |
/*
* 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;
using OpenSim.Tests.Common.Mock;
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, 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");
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArgumentParser.cs" company="CatenaLogic">
// Copyright (c) 2014 - 2014 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace GitLink
{
using System;
using System.Collections.Generic;
using System.Linq;
using Catel.Collections;
using Catel.Logging;
using GitLink.Providers;
using GitTools;
using GitTools.Git;
using LibGit2Sharp;
public static class ArgumentParser
{
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
public static Context ParseArguments(string commandLineArguments)
{
return ParseArguments(commandLineArguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
new ProviderManager());
}
public static Context ParseArguments(params string[] commandLineArguments)
{
return ParseArguments(commandLineArguments.ToList(), new ProviderManager());
}
public static Context ParseArguments(List<string> commandLineArguments, IProviderManager providerManager)
{
var context = new Context(providerManager);
if (commandLineArguments.Count == 0)
{
context.IsHelp = true;
return context;
}
var firstArgument = commandLineArguments.First();
if (IsHelp(firstArgument))
{
context.IsHelp = true;
return context;
}
if (commandLineArguments.Count < 3 && commandLineArguments.Count != 1)
{
throw Log.ErrorAndCreateException<GitLinkException>("Invalid number of arguments");
}
context.SolutionDirectory = firstArgument;
var namedArguments = commandLineArguments.Skip(1).ToList();
for (var index = 0; index < namedArguments.Count; index++)
{
var name = namedArguments[index];
// First check everything without values
if (IsSwitch("debug", name))
{
context.IsDebug = true;
continue;
}
if (IsSwitch("errorsaswarnings", name))
{
context.ErrorsAsWarnings = true;
continue;
}
if (IsSwitch("skipverify", name))
{
context.SkipVerify = true;
continue;
}
// After this point, all arguments should have a value
index++;
var valueInfo = GetValue(namedArguments, index);
var value = valueInfo.Key;
index = index + (valueInfo.Value - 1);
if (IsSwitch("l", name))
{
context.LogFile = value;
continue;
}
if (IsSwitch("c", name))
{
context.ConfigurationName = value;
continue;
}
if (IsSwitch("p", name))
{
context.PlatformName = value;
continue;
}
if (IsSwitch("u", name))
{
context.TargetUrl = value;
continue;
}
if (IsSwitch("b", name))
{
context.TargetBranch = value;
continue;
}
if (IsSwitch("s", name))
{
context.ShaHash = value;
continue;
}
if (IsSwitch("f", name))
{
context.SolutionFile = value;
continue;
}
if (IsSwitch("d", name))
{
context.PdbFilesDirectory = value;
continue;
}
if (IsSwitch("ignore", name))
{
context.IgnoredProjects.AddRange(value.Split(new []{ ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()));
continue;
}
throw Log.ErrorAndCreateException<GitLinkException>("Could not parse command line parameter '{0}'.", name);
}
if (string.IsNullOrEmpty(context.TargetUrl))
{
Log.Info("No target url was specified, trying to determine the target url automatically");
var gitDir = GitDirFinder.TreeWalkForGitDir(context.SolutionDirectory);
if (gitDir != null)
{
using (var repo = RepositoryLoader.GetRepo(gitDir))
{
var currentBranch = repo.Head;
if (string.IsNullOrEmpty(context.ShaHash))
{
context.ShaHash = currentBranch.Tip.Sha;
}
if (currentBranch.Remote == null || currentBranch.IsDetachedHead())
{
currentBranch = repo.GetBranchesContainingCommit(context.ShaHash).FirstOrDefault(b => b.Remote != null);
}
if (currentBranch != null && currentBranch.Remote != null)
{
var url = currentBranch.Remote.Url;
if (url.StartsWith("https://"))
{
context.TargetUrl = url.OptimizeUrl();
Log.Info("Automatically determine target url '{0}'", context.TargetUrl);
}
}
}
}
}
if (!string.IsNullOrEmpty(context.TargetUrl))
{
context.Provider = providerManager.GetProvider(context.TargetUrl);
}
return context;
}
private static KeyValuePair<string, int> GetValue(List<string> arguments, int index)
{
var totalCounter = 1;
var value = arguments[index];
while (value.StartsWith("\""))
{
if (value.EndsWith("\""))
{
break;
}
index++;
value += " " + arguments[index];
totalCounter++;
}
value = value.Trim('\"');
return new KeyValuePair<string, int>(value, totalCounter);
}
private static bool IsSwitch(string switchName, string value)
{
if (value.StartsWith("-"))
{
value = value.Remove(0, 1);
}
if (value.StartsWith("/"))
{
value = value.Remove(0, 1);
}
return (string.Equals(switchName, value));
}
private static bool IsHelp(string singleArgument)
{
return (singleArgument == "?") ||
IsSwitch("h", singleArgument) ||
IsSwitch("help", singleArgument) ||
IsSwitch("?", singleArgument);
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Text;
namespace OpenMetaverse
{
public static partial class Utils
{
/// <summary>
/// Operating system
/// </summary>
public enum Platform
{
/// <summary>Unknown</summary>
Unknown,
/// <summary>Microsoft Windows</summary>
Windows,
/// <summary>Microsoft Windows CE</summary>
WindowsCE,
/// <summary>Linux</summary>
Linux,
/// <summary>Apple OSX</summary>
OSX
}
/// <summary>
/// Runtime platform
/// </summary>
public enum Runtime
{
/// <summary>.NET runtime</summary>
Windows,
/// <summary>Mono runtime: http://www.mono-project.com/</summary>
Mono
}
public const float E = (float)Math.E;
public const float LOG10E = 0.4342945f;
public const float LOG2E = 1.442695f;
public const float PI = (float)Math.PI;
public const float TWO_PI = (float)(Math.PI * 2.0d);
public const float PI_OVER_TWO = (float)(Math.PI / 2.0d);
public const float PI_OVER_FOUR = (float)(Math.PI / 4.0d);
/// <summary>Used for converting degrees to radians</summary>
public const float DEG_TO_RAD = (float)(Math.PI / 180.0d);
/// <summary>Used for converting radians to degrees</summary>
public const float RAD_TO_DEG = (float)(180.0d / Math.PI);
/// <summary>Provide a single instance of the CultureInfo class to
/// help parsing in situations where the grid assumes an en-us
/// culture</summary>
public static readonly System.Globalization.CultureInfo EnUsCulture =
new System.Globalization.CultureInfo("en-us");
/// <summary>UNIX epoch in DateTime format</summary>
public static readonly DateTime Epoch = new DateTime(1970, 1, 1);
/// <summary>Provide a single instance of the MD5 class to avoid making
/// duplicate copies</summary>
private static readonly System.Security.Cryptography.MD5 MD5Builder =
new System.Security.Cryptography.MD5CryptoServiceProvider();
#region Math
/// <summary>
/// Clamp a given value between a range
/// </summary>
/// <param name="value">Value to clamp</param>
/// <param name="min">Minimum allowable value</param>
/// <param name="max">Maximum allowable value</param>
/// <returns>A value inclusively between lower and upper</returns>
public static float Clamp(float value, float min, float max)
{
// First we check to see if we're greater than the max
value = (value > max) ? max : value;
// Then we check to see if we're less than the min.
value = (value < min) ? min : value;
// There's no check to see if min > max.
return value;
}
/// <summary>
/// Clamp a given value between a range
/// </summary>
/// <param name="value">Value to clamp</param>
/// <param name="min">Minimum allowable value</param>
/// <param name="max">Maximum allowable value</param>
/// <returns>A value inclusively between lower and upper</returns>
public static double Clamp(double value, double min, double max)
{
// First we check to see if we're greater than the max
value = (value > max) ? max : value;
// Then we check to see if we're less than the min.
value = (value < min) ? min : value;
// There's no check to see if min > max.
return value;
}
/// <summary>
/// Clamp a given value between a range
/// </summary>
/// <param name="value">Value to clamp</param>
/// <param name="min">Minimum allowable value</param>
/// <param name="max">Maximum allowable value</param>
/// <returns>A value inclusively between lower and upper</returns>
public static int Clamp(int value, int min, int max)
{
// First we check to see if we're greater than the max
value = (value > max) ? max : value;
// Then we check to see if we're less than the min.
value = (value < min) ? min : value;
// There's no check to see if min > max.
return value;
}
/// <summary>
/// Round a floating-point value to the nearest integer
/// </summary>
/// <param name="val">Floating point number to round</param>
/// <returns>Integer</returns>
public static int Round(float val)
{
return (int)Math.Floor(val + 0.5f);
}
/// <summary>
/// Test if a single precision float is a finite number
/// </summary>
public static bool IsFinite(float value)
{
return !(Single.IsNaN(value) || Single.IsInfinity(value));
}
/// <summary>
/// Test if a double precision float is a finite number
/// </summary>
public static bool IsFinite(double value)
{
return !(Double.IsNaN(value) || Double.IsInfinity(value));
}
/// <summary>
/// Get the distance between two floating-point values
/// </summary>
/// <param name="value1">First value</param>
/// <param name="value2">Second value</param>
/// <returns>The distance between the two values</returns>
public static float Distance(float value1, float value2)
{
return Math.Abs(value1 - value2);
}
public static float Hermite(float value1, float tangent1, float value2, float tangent2, float amount)
{
// All transformed to double not to lose precission
// Otherwise, for high numbers of param:amount the result is NaN instead of Infinity
double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result;
double sCubed = s * s * s;
double sSquared = s * s;
if (amount == 0f)
result = value1;
else if (amount == 1f)
result = value2;
else
result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed +
(3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared +
t1 * s + v1;
return (float)result;
}
public static double Hermite(double value1, double tangent1, double value2, double tangent2, double amount)
{
// All transformed to double not to lose precission
// Otherwise, for high numbers of param:amount the result is NaN instead of Infinity
double v1 = value1, v2 = value2, t1 = tangent1, t2 = tangent2, s = amount, result;
double sCubed = s * s * s;
double sSquared = s * s;
if (amount == 0d)
result = value1;
else if (amount == 1f)
result = value2;
else
result = (2d * v1 - 2d * v2 + t2 + t1) * sCubed +
(3d * v2 - 3d * v1 - 2d * t1 - t2) * sSquared +
t1 * s + v1;
return result;
}
public static float Lerp(float value1, float value2, float amount)
{
return value1 + (value2 - value1) * amount;
}
public static double Lerp(double value1, double value2, double amount)
{
return value1 + (value2 - value1) * amount;
}
public static float SmoothStep(float value1, float value2, float amount)
{
// It is expected that 0 < amount < 1
// If amount < 0, return value1
// If amount > 1, return value2
float result = Utils.Clamp(amount, 0f, 1f);
return Utils.Hermite(value1, 0f, value2, 0f, result);
}
public static double SmoothStep(double value1, double value2, double amount)
{
// It is expected that 0 < amount < 1
// If amount < 0, return value1
// If amount > 1, return value2
double result = Utils.Clamp(amount, 0f, 1f);
return Utils.Hermite(value1, 0f, value2, 0f, result);
}
public static float ToDegrees(float radians)
{
// This method uses double precission internally,
// though it returns single float
// Factor = 180 / pi
return (float)(radians * 57.295779513082320876798154814105);
}
public static float ToRadians(float degrees)
{
// This method uses double precission internally,
// though it returns single float
// Factor = pi / 180
return (float)(degrees * 0.017453292519943295769236907684886);
}
/// <summary>
/// Compute the MD5 hash for a byte array
/// </summary>
/// <param name="data">Byte array to compute the hash for</param>
/// <returns>MD5 hash of the input data</returns>
public static byte[] MD5(byte[] data)
{
lock (MD5Builder)
return MD5Builder.ComputeHash(data);
}
/// <summary>
/// Calculate the MD5 hash of a given string
/// </summary>
/// <param name="password">The password to hash</param>
/// <returns>An MD5 hash in string format, with $1$ prepended</returns>
public static string MD5(string password)
{
StringBuilder digest = new StringBuilder();
byte[] hash = MD5(ASCIIEncoding.Default.GetBytes(password));
// Convert the hash to a hex string
foreach (byte b in hash)
{
digest.AppendFormat(Utils.EnUsCulture, "{0:x2}", b);
}
return "$1$" + digest.ToString();
}
#endregion Math
#region Platform
/// <summary>
/// Get the current running platform
/// </summary>
/// <returns>Enumeration of the current platform we are running on</returns>
public static Platform GetRunningPlatform()
{
const string OSX_CHECK_FILE = "/Library/Extensions.kextcache";
if (Environment.OSVersion.Platform == PlatformID.WinCE)
{
return Platform.WindowsCE;
}
else
{
int plat = (int)Environment.OSVersion.Platform;
if ((plat != 4) && (plat != 128))
{
return Platform.Windows;
}
else
{
if (System.IO.File.Exists(OSX_CHECK_FILE))
return Platform.OSX;
else
return Platform.Linux;
}
}
}
/// <summary>
/// Get the current running runtime
/// </summary>
/// <returns>Enumeration of the current runtime we are running on</returns>
public static Runtime GetRunningRuntime()
{
Type t = Type.GetType("Mono.Runtime");
if (t != null)
return Runtime.Mono;
else
return Runtime.Windows;
}
#endregion Platform
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Kironer.Shop.Areas.HelpPage.ModelDescriptions;
using Kironer.Shop.Areas.HelpPage.Models;
namespace Kironer.Shop.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Anlab.Core.Domain;
using AnlabMvc.Extensions;
using AnlabMvc.Models;
using AnlabMvc.Models.AccountViewModels;
using AnlabMvc.Services;
using Ietws;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Serilog;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace AnlabMvc.Controllers
{
[Authorize]
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IEmailSender _emailSender;
private readonly IDirectorySearchService _directorySearchService;
private readonly ILogger _logger;
private readonly ILabworksService _labworksService;
private readonly AppSettings _appSettings;
public AccountController(
UserManager<User> userManager,
SignInManager<User> signInManager,
IEmailSender emailSender,
IDirectorySearchService directorySearchService,
ILogger<AccountController> logger,
ILabworksService labworksService,
IOptions<AppSettings> appSettings)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_directorySearchService = directorySearchService;
_logger = logger;
_labworksService = labworksService;
_appSettings = appSettings.Value;
}
[TempData]
public string ErrorMessage { get; set; }
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToAction(nameof(Lockout));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
var model = new LoginWith2faViewModel { RememberMe = rememberMe };
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWith2fa(LoginWith2faViewModel model, bool rememberMe, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);
if (result.Succeeded)
{
_logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id);
return RedirectToLocal(returnUrl);
}
else if (result.IsLockedOut)
{
_logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
return RedirectToAction(nameof(Lockout));
}
else
{
_logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id);
ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
return View();
}
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);
var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
if (result.Succeeded)
{
_logger.LogInformation("User with ID {UserId} logged in with a recovery code.", user.Id);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
return RedirectToAction(nameof(Lockout));
}
else
{
_logger.LogWarning("Invalid recovery code entered for user with ID {UserId}", user.Id);
ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
return View();
}
}
[HttpGet]
[AllowAnonymous]
public IActionResult Lockout()
{
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new User { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
var provider = User.FindFirst(ClaimTypes.AuthenticationMethod)?.Value;
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (string.IsNullOrWhiteSpace(provider))
{
//This should never happen.
return RedirectToAction(nameof(HomeController.Index), "Home");
}
if (provider.Equals("Google", StringComparison.OrdinalIgnoreCase))
{
var returnUrl = Url.Action("Index", "Home", null, Request.Scheme);
var url = $"https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue={returnUrl}";
return Redirect(url);
}
//CAS logout does not support a redirect. They thought it was a security risk
return Redirect($"{_appSettings.CasBaseUrl}logout"); //Replace with the appSettings if we do it this way.
}
public async Task<IActionResult> LogoutDirect()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
Log.Error($"Error from external provider: {remoteError}");
return RedirectToAction("LoginError", "Error", new { id = 102 });
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
if (info.LoginProvider.Equals("Google", StringComparison.OrdinalIgnoreCase))
{
var emailClaim = info.Principal.FindFirstValue(ClaimTypes.Email);
if (emailClaim.Contains("@ucdavis"))
{
return RedirectToAction("LoginError", "Error", new{id=101});
}
}
// setup claims properly to deal with how CAS represents things
if (info.LoginProvider.Equals("UCDavis", StringComparison.OrdinalIgnoreCase))
{
// kerberos comes across in both name and nameidentifier
var kerb = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
var ucdPerson = await _directorySearchService.GetByKerberos(kerb);
if (ucdPerson.IsInvalid)
{
Log.Error($"Error from IAM: {ucdPerson.ErrorMessage}");
return RedirectToAction("LoginError", "Error", new { id = 103 });
}
var identity = (ClaimsIdentity)info.Principal.Identity;
identity.AddClaim(new Claim(ClaimTypes.Email, ucdPerson.Person.Mail));
identity.AddClaim(new Claim(ClaimTypes.GivenName, ucdPerson.Person.GivenName));
identity.AddClaim(new Claim(ClaimTypes.Surname, ucdPerson.Person.Surname));
// name and identifier come back as kerb, let's replace them with our found values.
identity.RemoveClaim(identity.FindFirst(ClaimTypes.NameIdentifier));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, ucdPerson.Person.Kerberos));
info.ProviderKey = ucdPerson.Person.Kerberos;
identity.RemoveClaim(identity.FindFirst(ClaimTypes.Name));
identity.AddClaim(new Claim(ClaimTypes.Name, ucdPerson.Person.FullName));
}
// return Json(info.Principal.Claims.Select(x=>new { x.Type, x.Value}));
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToAction(nameof(Lockout));
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
// user placeholder, to be filled by provider
var user = new User
{
Email = info.Principal.FindFirstValue(ClaimTypes.Email),
UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
FirstName = info.Principal.FindFirstValue(ClaimTypes.GivenName),
LastName = info.Principal.FindFirstValue(ClaimTypes.Surname),
Name = info.Principal.FindFirstValue(ClaimTypes.Name)
};
var defaults = await _labworksService.GetClientDetails(user.Email);
if (defaults != null)
{
user.ClientId = defaults.ClientId;
user.Account = defaults.DefaultAccount;
}
if (string.IsNullOrWhiteSpace(user.Name))
{
user.Name = user.Email;
}
var createResult = await _userManager.CreateAsync(user);
if (createResult.Succeeded)
{
createResult = await _userManager.AddLoginAsync(user, info);
if (createResult.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
//return RedirectToLocal(returnUrl);
TempData["Message"] = "Please update you profile before continuing.";
return this.RedirectToAction("Edit", "Profile");
}
}
// TODO: add in error message explaining why login failed
ErrorMessage = "There was a problem logging you in";
throw new Exception(createResult.Errors.First().Description);
}
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userId}'.");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
// For more information on how to enable account confirmation and password reset please
// visit https://go.microsoft.com/fwlink/?LinkID=532713
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Reset Password",
$"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
if (code == null)
{
throw new ApplicationException("A code must be supplied for password reset.");
}
var model = new ResetPasswordViewModel { Code = code };
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
AddErrors(result);
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>FeedItemTarget</c> resource.</summary>
public sealed partial class FeedItemTargetName : gax::IResourceName, sys::IEquatable<FeedItemTargetName>
{
/// <summary>The possible contents of <see cref="FeedItemTargetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// .
/// </summary>
CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget = 1,
}
private static gax::PathTemplate s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget = new gax::PathTemplate("customers/{customer_id}/feedItemTargets/{feed_id_feed_item_id_feed_item_target_type_feed_item_target_id}");
/// <summary>Creates a <see cref="FeedItemTargetName"/> 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="FeedItemTargetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static FeedItemTargetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new FeedItemTargetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="FeedItemTargetName"/> with the pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemTargetTypeId">
/// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FeedItemTargetName"/> constructed from the provided ids.</returns>
public static FeedItemTargetName FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) =>
new FeedItemTargetName(ResourceNameType.CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)), feedItemTargetTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetTypeId, nameof(feedItemTargetTypeId)), feedItemTargetId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetId, nameof(feedItemTargetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FeedItemTargetName"/> with pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemTargetTypeId">
/// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FeedItemTargetName"/> with pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// .
/// </returns>
public static string Format(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) =>
FormatCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(customerId, feedId, feedItemId, feedItemTargetTypeId, feedItemTargetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FeedItemTargetName"/> with pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemTargetTypeId">
/// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FeedItemTargetName"/> with pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// .
/// </returns>
public static string FormatCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) =>
s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetTypeId, nameof(feedItemTargetTypeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetId, nameof(feedItemTargetId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="FeedItemTargetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="feedItemTargetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="FeedItemTargetName"/> if successful.</returns>
public static FeedItemTargetName Parse(string feedItemTargetName) => Parse(feedItemTargetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="FeedItemTargetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="feedItemTargetName">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="FeedItemTargetName"/> if successful.</returns>
public static FeedItemTargetName Parse(string feedItemTargetName, bool allowUnparsed) =>
TryParse(feedItemTargetName, allowUnparsed, out FeedItemTargetName 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="FeedItemTargetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="feedItemTargetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FeedItemTargetName"/>, 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 feedItemTargetName, out FeedItemTargetName result) =>
TryParse(feedItemTargetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FeedItemTargetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="feedItemTargetName">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="FeedItemTargetName"/>, 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 feedItemTargetName, bool allowUnparsed, out FeedItemTargetName result)
{
gax::GaxPreconditions.CheckNotNull(feedItemTargetName, nameof(feedItemTargetName));
gax::TemplatedResourceName resourceName;
if (s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget.TryParseName(feedItemTargetName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget(resourceName[0], split1[0], split1[1], split1[2], split1[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(feedItemTargetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private FeedItemTargetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null, string feedItemId = null, string feedItemTargetId = null, string feedItemTargetTypeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
FeedId = feedId;
FeedItemId = feedItemId;
FeedItemTargetId = feedItemTargetId;
FeedItemTargetTypeId = feedItemTargetTypeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="FeedItemTargetName"/> class from the component parts of pattern
/// <c>
/// customers/{customer_id}/feedItemTargets/{feed_id}~{feed_item_id}~{feed_item_target_type}~{feed_item_target_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedItemTargetTypeId">
/// The <c>FeedItemTargetType</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="feedItemTargetId">The <c>FeedItemTarget</c> ID. Must not be <c>null</c> or empty.</param>
public FeedItemTargetName(string customerId, string feedId, string feedItemId, string feedItemTargetTypeId, string feedItemTargetId) : this(ResourceNameType.CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)), feedItemTargetTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetTypeId, nameof(feedItemTargetTypeId)), feedItemTargetId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemTargetId, nameof(feedItemTargetId)))
{
}
/// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FeedId { get; }
/// <summary>
/// The <c>FeedItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FeedItemId { get; }
/// <summary>
/// The <c>FeedItemTarget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string FeedItemTargetId { get; }
/// <summary>
/// The <c>FeedItemTargetType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string FeedItemTargetTypeId { 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.CustomerFeedFeedItemFeedItemTargetTypeFeedItemTarget: return s_customerFeedFeedItemFeedItemTargetTypeFeedItemTarget.Expand(CustomerId, $"{FeedId}~{FeedItemId}~{FeedItemTargetTypeId}~{FeedItemTargetId}");
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 FeedItemTargetName);
/// <inheritdoc/>
public bool Equals(FeedItemTargetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(FeedItemTargetName a, FeedItemTargetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(FeedItemTargetName a, FeedItemTargetName b) => !(a == b);
}
public partial class FeedItemTarget
{
/// <summary>
/// <see cref="FeedItemTargetName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal FeedItemTargetName ResourceNameAsFeedItemTargetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : FeedItemTargetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="FeedItemName"/>-typed view over the <see cref="FeedItem"/> resource name property.
/// </summary>
internal FeedItemName FeedItemAsFeedItemName
{
get => string.IsNullOrEmpty(FeedItem) ? null : FeedItemName.Parse(FeedItem, allowUnparsed: true);
set => FeedItem = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="GeoTargetConstantName"/>-typed view over the <see cref="GeoTargetConstant"/> resource name
/// property.
/// </summary>
internal GeoTargetConstantName GeoTargetConstantAsGeoTargetConstantName
{
get => string.IsNullOrEmpty(GeoTargetConstant) ? null : GeoTargetConstantName.Parse(GeoTargetConstant, allowUnparsed: true);
set => GeoTargetConstant = value?.ToString() ?? "";
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: WorkingTime.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Serialization;
using Ecng.Collections;
using StockSharp.Localization;
/// <summary>
/// Work schedule (time, holidays etc.).
/// </summary>
[Serializable]
[System.Runtime.Serialization.DataContract]
[DisplayNameLoc(LocalizedStrings.Str184Key)]
[DescriptionLoc(LocalizedStrings.Str408Key)]
public class WorkingTime : IPersistable
{
/// <summary>
/// Initializes a new instance of the <see cref="WorkingTime"/>.
/// </summary>
public WorkingTime()
{
}
/// <summary>
/// Is enabled.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str2229Key,
Description = LocalizedStrings.Str2230Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 0)]
public bool IsEnabled { get; set; }
private List<WorkingTimePeriod> _periods = new();
/// <summary>
/// Schedule validity periods.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str409Key,
Description = LocalizedStrings.Str410Key,
GroupName = LocalizedStrings.GeneralKey,
Order = 1)]
public List<WorkingTimePeriod> Periods
{
get => _periods;
set => _periods = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Working days, falling on Saturday and Sunday.
/// </summary>
//[Display(
// ResourceType = typeof(LocalizedStrings),
// Name = LocalizedStrings.Str411Key,
// Description = LocalizedStrings.Str412Key,
// GroupName = LocalizedStrings.GeneralKey,
// Order = 2)]
//[DataMember]
[XmlIgnore]
[Browsable(false)]
public DateTime[] SpecialWorkingDays
{
get => _specialDays.Where(p => p.Value.Length > 0).Select(p => p.Key).ToArray();
set
{
//_specialWorkingDays = CheckDates(value);
foreach (var day in CheckDates(value))
{
var period = this.GetPeriod(day);
_specialDays[day] = period?.Times.ToArray() ?? new[] { new Range<TimeSpan>(new TimeSpan(9, 0, 0), new TimeSpan(16, 0, 0)) };
}
}
}
/// <summary>
/// Holidays that fall on workdays.
/// </summary>
//[DataMember]
//[Display(
// ResourceType = typeof(LocalizedStrings),
// Name = LocalizedStrings.Str413Key,
// Description = LocalizedStrings.Str414Key,
// GroupName = LocalizedStrings.GeneralKey,
// Order = 3)]
[XmlIgnore]
[Browsable(false)]
public DateTime[] SpecialHolidays
{
get => _specialDays.Where(p => p.Value.Length == 0).Select(p => p.Key).ToArray();
set
{
foreach (var day in CheckDates(value))
_specialDays[day] = Array.Empty<Range<TimeSpan>>();
}
}
private IDictionary<DateTime, Range<TimeSpan>[]> _specialDays = new Dictionary<DateTime, Range<TimeSpan>[]>();
/// <summary>
/// Special working days and holidays.
/// </summary>
[DataMember]
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.SpecialDaysKey,
Description = LocalizedStrings.SpecialDaysDescKey,
GroupName = LocalizedStrings.GeneralKey,
Order = 2)]
[XmlIgnore]
public IDictionary<DateTime, Range<TimeSpan>[]> SpecialDays
{
get => _specialDays;
set => _specialDays = value ?? throw new ArgumentNullException(nameof(value));
}
private bool _checkDates = true;
private DateTime[] CheckDates(DateTime[] dates)
{
if (!_checkDates)
return dates;
if (dates is null)
throw new ArgumentNullException(nameof(dates));
var dupDate = dates.GroupBy(d => d).FirstOrDefault(g => g.Count() > 1);
if (dupDate != null)
throw new ArgumentException(LocalizedStrings.Str415Params.Put(dupDate.Key), nameof(dates));
return dates;
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Load(SettingsStorage storage)
{
_checkDates = false;
try
{
IsEnabled = storage.GetValue(nameof(IsEnabled), IsEnabled);
Periods = storage.GetValue<IEnumerable<SettingsStorage>>(nameof(Periods)).Select(s => s.Load<WorkingTimePeriod>()).ToList();
if (storage.ContainsKey(nameof(SpecialDays)))
{
SpecialDays.Clear();
SpecialDays.AddRange(storage
.GetValue<IEnumerable<SettingsStorage>>(nameof(SpecialDays))
.Select(s => new KeyValuePair<DateTime, Range<TimeSpan>[]>
(
s.GetValue<DateTime>("Day"),
s.GetValue<IEnumerable<SettingsStorage>>("Periods").Select(s1 => s1.ToRange<TimeSpan>()).ToArray()
))
);
}
else
{
SpecialWorkingDays = storage.GetValue<List<DateTime>>(nameof(SpecialWorkingDays)).ToArray();
SpecialHolidays = storage.GetValue<List<DateTime>>(nameof(SpecialHolidays)).ToArray();
}
}
finally
{
_checkDates = true;
}
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Save(SettingsStorage storage)
{
storage.SetValue(nameof(IsEnabled), IsEnabled);
storage.SetValue(nameof(Periods), Periods.Select(p => p.Save()).ToArray());
storage.SetValue(nameof(SpecialDays), SpecialDays.Select(p => new SettingsStorage()
.Set("Day", p.Key)
.Set("Periods", p.Value.Select(p1 => p1.ToStorage()).ToArray())
).ToArray());
}
/// <inheritdoc />
public override string ToString() => Periods.Select(p => p.ToString()).JoinComma();
}
}
| |
using System;
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Tsum
/// </summary>
public sealed partial class Tsum : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<decimal?>? _aboveOrBelowRatePercent;
private DirtyValue<string?>? _adjustorCoverage;
private DirtyValue<string?>? _ausRecommendation;
private DirtyValue<int?>? _bedroomsUnit1;
private DirtyValue<int?>? _bedroomsUnit2;
private DirtyValue<int?>? _bedroomsUnit3;
private DirtyValue<int?>? _bedroomsUnit4;
private DirtyValue<string?>? _certificateNumber;
private DirtyValue<string?>? _commitmentNumber;
private DirtyValue<bool?>? _communityLendingAfordableHousingInitiative;
private DirtyValue<string?>? _contactTitle;
private DirtyValue<string?>? _contractNumber;
private DirtyValue<string?>? _cpmProjectId;
private DirtyValue<string?>? _duCaseIdLpAusKey;
private DirtyValue<string?>? _formNumber;
private DirtyValue<int?>? _grossRentUnit1;
private DirtyValue<int?>? _grossRentUnit2;
private DirtyValue<int?>? _grossRentUnit3;
private DirtyValue<int?>? _grossRentUnit4;
private DirtyValue<StringEnumValue<HomeBuyersOwnershipEducationCertificateInFile>>? _homeBuyersOwnershipEducationCertificateInFile;
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _insurerCode;
private DirtyValue<decimal?>? _interestedPartyContributions;
private DirtyValue<string?>? _investorLoanNumber;
private DirtyValue<StringEnumValue<LevelOfPropertyReviewType>>? _levelOfPropertyReviewType;
private DirtyValue<string?>? _lpDocClass;
private DirtyValue<StringEnumValue<TsumMortgageOriginator>>? _mortgageOriginator;
private DirtyValue<DateTime?>? _noteDate;
private DirtyValue<StringEnumValue<NoteRateType>>? _noteRateType;
private DirtyValue<int?>? _numberOfBorrowers;
private DirtyValue<int?>? _numberOfMonthsReserves;
private DirtyValue<decimal?>? _originalAmountOfFirstMortgage;
private DirtyValue<StringEnumValue<OtherTypeDescription>>? _otherTypeDescription;
private DirtyValue<string?>? _percentageofCoverage;
private DirtyValue<string?>? _projectName;
private DirtyValue<StringEnumValue<PropertyFormType>>? _propertyFormType;
private DirtyValue<StringEnumValue<OtherPropertyType>>? _propertyType;
private DirtyValue<decimal?>? _required;
private DirtyValue<StringEnumValue<RiskAssessmentType>>? _riskAssessmentType;
private DirtyValue<string?>? _sellerAddress;
private DirtyValue<string?>? _sellerCity;
private DirtyValue<string?>? _sellerContactName;
private DirtyValue<string?>? _sellerCountry;
private DirtyValue<bool?>? _sellerForeignAddressIndicator;
private DirtyValue<string?>? _sellerName;
private DirtyValue<string?>? _sellerNumber;
private DirtyValue<string?>? _sellerPhone;
private DirtyValue<string?>? _sellerPostalCode;
private DirtyValue<StringEnumValue<State>>? _sellerState;
private DirtyValue<string?>? _specialFeatureCode1;
private DirtyValue<string?>? _specialFeatureCode2;
private DirtyValue<string?>? _specialFeatureCode3;
private DirtyValue<string?>? _specialFeatureCode4;
private DirtyValue<string?>? _specialFeatureCode5;
private DirtyValue<string?>? _specialFeatureCode6;
private DirtyValue<string?>? _thirdPartyName1;
private DirtyValue<string?>? _thirdPartyName2;
private DirtyValue<string?>? _typeOfCommitment;
private DirtyValue<string?>? _underwritingComment1;
private DirtyValue<string?>? _underwritingComment2;
private DirtyValue<string?>? _underwritingComment3;
private DirtyValue<string?>? _underwritingComment4;
private DirtyValue<string?>? _underwritingComment5;
private DirtyValue<string?>? _underwritingComment6;
private DirtyValue<string?>? _underwritingComment7;
private DirtyValue<string?>? _underwritingComment8;
private DirtyValue<decimal?>? _unpaidBalance;
private DirtyValue<decimal?>? _verified;
/// <summary>
/// Trans Details Qual Rate Amt Increase/Decrease [1660]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? AboveOrBelowRatePercent { get => _aboveOrBelowRatePercent; set => SetField(ref _aboveOrBelowRatePercent, value); }
/// <summary>
/// Tsum AdjustorCoverage [TSUM.X31]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AdjustorCoverage { get => _adjustorCoverage; set => SetField(ref _adjustorCoverage, value); }
/// <summary>
/// Underwriting Risk Assess AUS Recomm [1544]
/// </summary>
public string? AusRecommendation { get => _ausRecommendation; set => SetField(ref _ausRecommendation, value); }
/// <summary>
/// Tsum BedroomsUnit1 [TSUM.X5]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BedroomsUnit1 { get => _bedroomsUnit1; set => SetField(ref _bedroomsUnit1, value); }
/// <summary>
/// Tsum BedroomsUnit2 [TSUM.X6]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BedroomsUnit2 { get => _bedroomsUnit2; set => SetField(ref _bedroomsUnit2, value); }
/// <summary>
/// Tsum BedroomsUnit3 [TSUM.X7]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BedroomsUnit3 { get => _bedroomsUnit3; set => SetField(ref _bedroomsUnit3, value); }
/// <summary>
/// Tsum BedroomsUnit4 [TSUM.X8]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? BedroomsUnit4 { get => _bedroomsUnit4; set => SetField(ref _bedroomsUnit4, value); }
/// <summary>
/// Tsum CertificateNumber [TSUM.X30]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? CertificateNumber { get => _certificateNumber; set => SetField(ref _certificateNumber, value); }
/// <summary>
/// Trans Details Commitment # [996]
/// </summary>
public string? CommitmentNumber { get => _commitmentNumber; set => SetField(ref _commitmentNumber, value); }
/// <summary>
/// Underwriting Commun Lending/AHI [1551]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Community Lending/Affordable Housing Initiative\"}")]
public bool? CommunityLendingAfordableHousingInitiative { get => _communityLendingAfordableHousingInitiative; set => SetField(ref _communityLendingAfordableHousingInitiative, value); }
/// <summary>
/// File Contacts Seller Title [1143]
/// </summary>
public string? ContactTitle { get => _contactTitle; set => SetField(ref _contactTitle, value); }
/// <summary>
/// Trans Details Contract # [971]
/// </summary>
public string? ContractNumber { get => _contractNumber; set => SetField(ref _contractNumber, value); }
/// <summary>
/// Condo Project ID Number [3050]
/// </summary>
public string? CpmProjectId { get => _cpmProjectId; set => SetField(ref _cpmProjectId, value); }
/// <summary>
/// Underwriting DU Case ID/LP AUS Key # [DU.LP.ID]
/// </summary>
public string? DuCaseIdLpAusKey { get => _duCaseIdLpAusKey; set => SetField(ref _duCaseIdLpAusKey, value); }
/// <summary>
/// Underwriting Level of Prpty Review Form # [1542]
/// </summary>
public string? FormNumber { get => _formNumber; set => SetField(ref _formNumber, value); }
/// <summary>
/// Tsum GrossRentUnit1 [TSUM.X9]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? GrossRentUnit1 { get => _grossRentUnit1; set => SetField(ref _grossRentUnit1, value); }
/// <summary>
/// Tsum GrossRentUnit2 [TSUM.X10]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? GrossRentUnit2 { get => _grossRentUnit2; set => SetField(ref _grossRentUnit2, value); }
/// <summary>
/// Tsum GrossRentUnit3 [TSUM.X11]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? GrossRentUnit3 { get => _grossRentUnit3; set => SetField(ref _grossRentUnit3, value); }
/// <summary>
/// Tsum GrossRentUnit4 [TSUM.X12]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? GrossRentUnit4 { get => _grossRentUnit4; set => SetField(ref _grossRentUnit4, value); }
/// <summary>
/// Underwriting Buyer/Homeownrshp Edu Cert [1552]
/// </summary>
public StringEnumValue<HomeBuyersOwnershipEducationCertificateInFile> HomeBuyersOwnershipEducationCertificateInFile { get => _homeBuyersOwnershipEducationCertificateInFile; set => SetField(ref _homeBuyersOwnershipEducationCertificateInFile, value); }
/// <summary>
/// Tsum Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Tsum InsurerCode [TSUM.X13]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? InsurerCode { get => _insurerCode; set => SetField(ref _insurerCode, value); }
/// <summary>
/// Borr Funds to Close - Interested Party Contrib % [1549]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? InterestedPartyContributions { get => _interestedPartyContributions; set => SetField(ref _interestedPartyContributions, value); }
/// <summary>
/// Trans Details Investor Case/Loan # [352]
/// </summary>
public string? InvestorLoanNumber { get => _investorLoanNumber; set => SetField(ref _investorLoanNumber, value); }
/// <summary>
/// Underwriting Level of Prpty Review [1541]
/// </summary>
public StringEnumValue<LevelOfPropertyReviewType> LevelOfPropertyReviewType { get => _levelOfPropertyReviewType; set => SetField(ref _levelOfPropertyReviewType, value); }
/// <summary>
/// Underwriting Risk Assess LP Doc Class [1545]
/// </summary>
public string? LpDocClass { get => _lpDocClass; set => SetField(ref _lpDocClass, value); }
/// <summary>
/// Trans Details Mtg Originator [1149]
/// </summary>
public StringEnumValue<TsumMortgageOriginator> MortgageOriginator { get => _mortgageOriginator; set => SetField(ref _mortgageOriginator, value); }
/// <summary>
/// Trans Details Note Date [992]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public DateTime? NoteDate { get => _noteDate; set => SetField(ref _noteDate, value); }
/// <summary>
/// Trans Details Qual Rate Basis [1086]
/// </summary>
public StringEnumValue<NoteRateType> NoteRateType { get => _noteRateType; set => SetField(ref _noteRateType, value); }
/// <summary>
/// Tsum NumberOfBorrowers [TSUM.X4]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public int? NumberOfBorrowers { get => _numberOfBorrowers; set => SetField(ref _numberOfBorrowers, value); }
/// <summary>
/// Borr Funds to Close - Mos Resrv [1548]
/// </summary>
public int? NumberOfMonthsReserves { get => _numberOfMonthsReserves; set => SetField(ref _numberOfMonthsReserves, value); }
/// <summary>
/// Trans Details Original Loan Amt [1085]
/// </summary>
public decimal? OriginalAmountOfFirstMortgage { get => _originalAmountOfFirstMortgage; set => SetField(ref _originalAmountOfFirstMortgage, value); }
/// <summary>
/// Underwriting Risk Assess Other Descr [1556]
/// </summary>
public StringEnumValue<OtherTypeDescription> OtherTypeDescription { get => _otherTypeDescription; set => SetField(ref _otherTypeDescription, value); }
/// <summary>
/// Tsum PercentageofCoverage [TSUM.X29]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? PercentageofCoverage { get => _percentageofCoverage; set => SetField(ref _percentageofCoverage, value); }
/// <summary>
/// Subject Property Project Name [1298]
/// </summary>
public string? ProjectName { get => _projectName; set => SetField(ref _projectName, value); }
/// <summary>
/// Property Valuation Form Type [TSUM.PropertyFormType]
/// </summary>
[LoanFieldProperty(MissingOptionsJson = "[\"One Unit Residential Appraisal Desk Review Report\"]")]
public StringEnumValue<PropertyFormType> PropertyFormType { get => _propertyFormType; set => SetField(ref _propertyFormType, value); }
/// <summary>
/// Subject Property Type [1553]
/// </summary>
public StringEnumValue<OtherPropertyType> PropertyType { get => _propertyType; set => SetField(ref _propertyType, value); }
/// <summary>
/// Borr Funds to Close - Required [1546]
/// </summary>
public decimal? Required { get => _required; set => SetField(ref _required, value); }
/// <summary>
/// Underwriting Risk Assess Type [1543]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"LP\":\"LPA\"}")]
public StringEnumValue<RiskAssessmentType> RiskAssessmentType { get => _riskAssessmentType; set => SetField(ref _riskAssessmentType, value); }
/// <summary>
/// File Contacts Seller Addr [1302]
/// </summary>
public string? SellerAddress { get => _sellerAddress; set => SetField(ref _sellerAddress, value); }
/// <summary>
/// File Contacts Seller City [1304]
/// </summary>
public string? SellerCity { get => _sellerCity; set => SetField(ref _sellerCity, value); }
/// <summary>
/// File Contacts Seller Contact [1303]
/// </summary>
public string? SellerContactName { get => _sellerContactName; set => SetField(ref _sellerContactName, value); }
/// <summary>
/// File Contacts Seller Country [4679]
/// </summary>
public string? SellerCountry { get => _sellerCountry; set => SetField(ref _sellerCountry, value); }
/// <summary>
/// File Contacts Seller Foreign Address Indicator [4678]
/// </summary>
public bool? SellerForeignAddressIndicator { get => _sellerForeignAddressIndicator; set => SetField(ref _sellerForeignAddressIndicator, value); }
/// <summary>
/// File Contacts Seller Co Name [1301]
/// </summary>
public string? SellerName { get => _sellerName; set => SetField(ref _sellerName, value); }
/// <summary>
/// File Contacts Seller # [997]
/// </summary>
public string? SellerNumber { get => _sellerNumber; set => SetField(ref _sellerNumber, value); }
/// <summary>
/// File Contacts Seller Phone [1293]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? SellerPhone { get => _sellerPhone; set => SetField(ref _sellerPhone, value); }
/// <summary>
/// File Contacts Seller Zip [1305]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? SellerPostalCode { get => _sellerPostalCode; set => SetField(ref _sellerPostalCode, value); }
/// <summary>
/// File Contacts Seller State [1292]
/// </summary>
public StringEnumValue<State> SellerState { get => _sellerState; set => SetField(ref _sellerState, value); }
/// <summary>
/// Tsum SpecialFeatureCode1 [TSUM.X32]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SpecialFeatureCode1 { get => _specialFeatureCode1; set => SetField(ref _specialFeatureCode1, value); }
/// <summary>
/// Tsum SpecialFeatureCode2 [TSUM.X35]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SpecialFeatureCode2 { get => _specialFeatureCode2; set => SetField(ref _specialFeatureCode2, value); }
/// <summary>
/// Tsum SpecialFeatureCode3 [TSUM.X33]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SpecialFeatureCode3 { get => _specialFeatureCode3; set => SetField(ref _specialFeatureCode3, value); }
/// <summary>
/// Tsum SpecialFeatureCode4 [TSUM.X36]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SpecialFeatureCode4 { get => _specialFeatureCode4; set => SetField(ref _specialFeatureCode4, value); }
/// <summary>
/// Tsum SpecialFeatureCode5 [TSUM.X34]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SpecialFeatureCode5 { get => _specialFeatureCode5; set => SetField(ref _specialFeatureCode5, value); }
/// <summary>
/// Tsum SpecialFeatureCode6 [TSUM.X37]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? SpecialFeatureCode6 { get => _specialFeatureCode6; set => SetField(ref _specialFeatureCode6, value); }
/// <summary>
/// Trans Details Mtg Orig Third Party Name [1133]
/// </summary>
public string? ThirdPartyName1 { get => _thirdPartyName1; set => SetField(ref _thirdPartyName1, value); }
/// <summary>
/// Loan Info Third Party Name [1714]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? ThirdPartyName2 { get => _thirdPartyName2; set => SetField(ref _thirdPartyName2, value); }
/// <summary>
/// Trans Details Commitment Type [987]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? TypeOfCommitment { get => _typeOfCommitment; set => SetField(ref _typeOfCommitment, value); }
/// <summary>
/// Underwriting Comment 1 [1216]
/// </summary>
public string? UnderwritingComment1 { get => _underwritingComment1; set => SetField(ref _underwritingComment1, value); }
/// <summary>
/// Underwriting Comment 2 [1217]
/// </summary>
public string? UnderwritingComment2 { get => _underwritingComment2; set => SetField(ref _underwritingComment2, value); }
/// <summary>
/// Underwriting Comment 3 [1218]
/// </summary>
public string? UnderwritingComment3 { get => _underwritingComment3; set => SetField(ref _underwritingComment3, value); }
/// <summary>
/// Underwriting Comment 4 [1219]
/// </summary>
public string? UnderwritingComment4 { get => _underwritingComment4; set => SetField(ref _underwritingComment4, value); }
/// <summary>
/// Underwriting Comment 5 [1220]
/// </summary>
public string? UnderwritingComment5 { get => _underwritingComment5; set => SetField(ref _underwritingComment5, value); }
/// <summary>
/// Underwriting Comment 6 [1221]
/// </summary>
public string? UnderwritingComment6 { get => _underwritingComment6; set => SetField(ref _underwritingComment6, value); }
/// <summary>
/// Underwriting Comment 7 [1222]
/// </summary>
public string? UnderwritingComment7 { get => _underwritingComment7; set => SetField(ref _underwritingComment7, value); }
/// <summary>
/// Underwriting Comment 8 [1829]
/// </summary>
public string? UnderwritingComment8 { get => _underwritingComment8; set => SetField(ref _underwritingComment8, value); }
/// <summary>
/// Trans Details Sub Fin Additional Mtgs [1732]
/// </summary>
public decimal? UnpaidBalance { get => _unpaidBalance; set => SetField(ref _unpaidBalance, value); }
/// <summary>
/// Borr Funds to Close - Verif [1547]
/// </summary>
public decimal? Verified { get => _verified; set => SetField(ref _verified, value); }
}
}
| |
// <copyright file="ISqlConnection.CrudAsync.cs" company="Berkeleybross">
// Copyright (c) Berkeleybross. All rights reserved.
// </copyright>
namespace PeregrineDb
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Pagination;
using PeregrineDb.SqlCommands;
public partial interface ISqlConnection
{
/// <summary>
/// Counts how many entities in the <typeparamref name="TEntity"/> table match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// await databaseConnection.CountAsync<DogEntity>("WHERE Age > @MinAge", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<int> CountAsync<TEntity>(string conditions = null, object parameters = null, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Counts how many entities in the <typeparamref name="TEntity"/> table match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// await databaseConnection.CountAsync<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<int> CountAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets whether an entity in the <typeparamref name="TEntity"/> table matches the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var minAge = 18;
/// databaseConnection.Exists<DogEntity>($"WHERE Age > {minAge}");
/// ]]>
/// </code>
/// </example>
Task<bool> ExistsAsync<TEntity>(string conditions = null, object parameters = null, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets whether an entity in the <typeparamref name="TEntity"/> table matches the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// databaseConnection.Exists<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<bool> ExistsAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Finds a single entity from the <typeparamref name="TEntity"/> table by it's primary key, or the default value if not found.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entity = await databaseConnection.FindAsync<DogEntity>(12);
/// ]]>
/// </code>
/// </example>
Task<TEntity> FindAsync<TEntity>(object id, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets a single entity from the <typeparamref name="TEntity"/> table by it's primary key, or throws an exception if not found.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entity = await databaseConnection.GetAsync<DogEntity>(12);
/// ]]>
/// </code>
/// </example>
/// <exception cref="InvalidOperationException">The entity was not found.</exception>
Task<TEntity> GetAsync<TEntity>(object id, int? commandTimeout = null, CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Gets the first matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or the default value if none match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetFirstOrDefaultAsync<DogEntity>("WHERE Age > @MinAge", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> FindFirstAsync<TEntity>(
string orderBy,
string conditions = null,
object parameters = null,
int? commandTimeout = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets the first matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or the default value if none match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetFirstOrDefaultAsync<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> FindFirstAsync<TEntity>(
string orderBy,
object conditions,
int? commandTimeout = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets the first matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or throws an <see cref="InvalidOperationException"/> if none match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetFirstAsync<DogEntity>("WHERE Age > @MinAge", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> GetFirstAsync<TEntity>(
string orderBy,
string conditions = null,
object parameters = null,
int? commandTimeout = null,
CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Gets the first matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or throws an <see cref="InvalidOperationException"/> if none match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetFirstAsync<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> GetFirstAsync<TEntity>(string orderBy, object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Gets the only matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or the default value if none match. Throws an <see cref="InvalidOperationException"/> if multiple entities match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetSingleOrDefaultAsync<DogEntity>("WHERE Age > @MinAge", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> FindSingleAsync<TEntity>(string conditions, object parameters, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the only matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or the default value if none match. Throws an <see cref="InvalidOperationException"/> if multiple entities match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetSingleOrDefaultAsync<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> FindSingleAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the only matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or throws an <see cref="InvalidOperationException"/> if no entries, or multiple entities match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetSingleAsync<DogEntity>("WHERE Age > @MinAge", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> GetSingleAsync<TEntity>(string conditions, object parameters, int? commandTimeout = null, CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Gets the only matching entity from the <typeparamref name="TEntity"/> table which matches the <paramref name="conditions"/>,
/// or throws an <see cref="InvalidOperationException"/> if no entries, or multiple entities match.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dog = await databaseConnection.GetSingleAsync<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<TEntity> GetSingleAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Gets a collection of entities from the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dogs = await databaseConnection.GetRangeAsync<DogEntity>("WHERE Age > @MinAge", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<IReadOnlyList<TEntity>> GetRangeAsync<TEntity>(string conditions, object parameters = null, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets a collection of entities from the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dogs = await databaseConnection.GetRangeAsync<DogEntity>(new { Age = 18 });
/// ]]>
/// </code>
/// </example>
Task<IReadOnlyList<TEntity>> GetRangeAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the first <parmref name="count"/> entities from the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var minAge = 18;
/// var dogs = databaseConnection.GetTop<DogEntity>(5, $"WHERE Age > {minAge}", "id");
/// ]]>
/// </code>
/// </example>
Task<IReadOnlyList<TEntity>> GetTopAsync<TEntity>(int count, string orderBy, string conditions = null, object parameters = null, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the first <parmref name="count"/> entities from the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var dogs = databaseConnection.GetTop<DogEntity>(5, new { Age = 18 }, "id");
/// ]]>
/// </code>
/// </example>
Task<IReadOnlyList<TEntity>> GetTopAsync<TEntity>(int count, string orderBy, object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Gets a collection of entities from the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var pageBuilder = new PageIndexPageBuilder(3, 10);
/// var dogs = await databaseConnection.GetPageAsync<DogEntity>(pageBuilder, "WHERE Age > @MinAge", "Age DESC", new { MinAge = 18 });
/// ]]>
/// </code>
/// </example>
Task<PagedList<TEntity>> GetPageAsync<TEntity>(
IPageBuilder pageBuilder,
string orderBy,
string conditions = null,
object parameters = null,
int? commandTimeout = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets a collection of entities from the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ...
/// var pageBuilder = new PageIndexPageBuilder(3, 10);
/// var dogs = await databaseConnection.GetPageAsync<DogEntity>(pageBuilder, new { Age = 10 }, "Age DESC");
/// ]]>
/// </code>
/// </example>
Task<PagedList<TEntity>> GetPageAsync<TEntity>(
IPageBuilder pageBuilder,
string orderBy,
object conditions,
int? commandTimeout = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Gets all the entities in the <typeparamref name="TEntity"/> table.
/// </summary>
Task<IReadOnlyList<TEntity>> GetAllAsync<TEntity>(int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Inserts the <paramref name="entity"/> into the databaseConnection.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entity = new dog { Name = "Little bobby tables" };
/// await databaseConnection.InsertAsync(entity);
/// ]]>
/// </code>
/// </example>
Task InsertAsync(object entity, int? commandTimeout = null, bool? verifyAffectedRowCount = null, CancellationToken cancellationToken = default);
/// <summary>
/// Inserts the <paramref name="entity"/> into the databaseConnection, and returns the auto-generated identity (or the default if invalid).
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entity = new dog { Name = "Little bobby tables" };
/// entity.Id = await databaseConnection.InsertAsync<int>(entity);
/// ]]>
/// </code>
/// </example>
Task<TPrimaryKey> InsertAsync<TPrimaryKey>(object entity, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// <para>Efficiently inserts multiple <paramref name="entities"/> into the databaseConnection.</para>
/// <para>For performance, it's recommended to always perform this action inside of a transaction.</para>
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entities = new []
/// {
/// new dog { Name = "Little bobby tables" },
/// new dog { Name = "Jimmy" };
/// };
///
/// using (var databaseConnection = databaseProvider.StartUnitOfWork())
/// {
/// await databaseConnection.InsertRangeAsync(entities);
///
/// databaseConnection.SaveChanges();
/// }
/// ]]>
/// </code>
/// </example>
Task<CommandResult> InsertRangeAsync<TEntity>(IEnumerable<TEntity> entities, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// <para>
/// Efficiently inserts multiple <paramref name="entities"/> into the databaseConnection,
/// and for each one calls <paramref name="setPrimaryKey"/> allowing the primary key to be recorded.
/// </para>
/// <para>For performance, it's recommended to always perform this action inside of a transaction.</para>
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entities = new []
/// {
/// new dog { Name = "Little bobby tables" },
/// new dog { Name = "Jimmy" };
/// };
///
/// using (var databaseConnection = databaseProvider.StartUnitOfWork())
/// {
/// await databaseConnection.InsertRangeAsync<dog, int>(entities, (e, k) => { e.Id = k; });
///
/// databaseConnection.SaveChanges();
/// }
/// ]]>
/// </code>
/// </example>
Task InsertRangeAsync<TEntity, TPrimaryKey>(
IEnumerable<TEntity> entities,
Action<TEntity, TPrimaryKey> setPrimaryKey,
int? commandTimeout = null,
CancellationToken cancellationToken = default);
/// <summary>
/// Updates the <paramref name="entity"/> in the databaseConnection.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entity = databaseConnection.Get<DogEntity>(5);
/// entity.Name = "Little bobby tables";
/// await databaseConnection.UpdateAsync(entity);
/// ]]>
/// </code>
/// </example>
/// <exception cref="AffectedRowCountException">The update command didn't change any record, or changed multiple records.</exception>
Task UpdateAsync<TEntity>(
TEntity entity,
int? commandTimeout = null,
bool? verifyAffectedRowCount = null,
CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// <para>Efficiently updates multiple <paramref name="entities"/> in the databaseConnection.</para>
/// <para>For performance, it's recommended to always perform this action inside of a transaction.</para>
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// using (var databaseConnection = databaseProvider.StartUnitOfWork())
/// {
/// var entities = databaseConnection.GetRange<DogEntity>("WHERE @Age = 10");
///
/// foreach (var entity in entities)
/// {
/// entity.Name = "Little bobby tables";
/// }
///
/// await databaseConnection.UpdateRangeAsync(entities);
/// databaseConnection.SaveChanges();
/// }
/// ]]>
/// </code>
/// </example>
/// <returns>The number of affected records.</returns>
Task<CommandResult> UpdateRangeAsync<TEntity>(
IEnumerable<TEntity> entities,
int? commandTimeout = null,
CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Deletes the entity in the <typeparamref name="TEntity"/> table, identified by its primary key.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// var entity = databaseConnection.Get<DogEntity>(5);
/// await databaseConnection.DeleteAsync(entity);
/// ]]>
/// </code>
/// </example>
/// <exception cref="AffectedRowCountException">The delete command didn't delete anything, or deleted multiple records.</exception>
Task DeleteAsync<TEntity>(
TEntity entity,
int? commandTimeout = null,
bool? verifyAffectedRowCount = null,
CancellationToken cancellationToken = default)
where TEntity : class;
/// <summary>
/// Deletes the entity in the <typeparamref name="TEntity"/> table which has the <paramref name="id"/>.
/// </summary>
/// <example>
/// <code>
/// await databaseConnection.DeleteAsync(5);
/// </code>
/// </example>
/// <exception cref="AffectedRowCountException">The delete command didn't delete anything, or deleted multiple records.</exception>
Task DeleteAsync<TEntity>(object id, int? commandTimeout = null, bool? verifyAffectedRowCount = null, CancellationToken cancellationToken = default);
/// <summary>
/// <para>Deletes all the entities in the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.</para>
/// <para>Note: <paramref name="conditions"/> must contain a WHERE clause. Use <see cref="DeleteAll{TEntity}"/> if you want to delete all entities.</para>
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// await databaseConnection.DeleteRangeAsync<DogEntity>("WHERE Name LIKE '%Foo%'");
/// ]]>
/// </code>
/// </example>
/// <returns>The number of deleted entities.</returns>
Task<CommandResult> DeleteRangeAsync<TEntity>(string conditions = null, object parameters = null, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// <para>Deletes all the entities in the <typeparamref name="TEntity"/> table which match the <paramref name="conditions"/>.</para>
/// <para>Note: <paramref name="conditions"/> must contain a WHERE clause. Use <see cref="DeleteAll{TEntity}"/> if you want to delete all entities.</para>
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// await databaseConnection.DeleteRangeAsync<DogEntity>("WHERE Name LIKE '%Foo%'");
/// ]]>
/// </code>
/// </example>
/// <returns>The number of deleted entities.</returns>
Task<CommandResult> DeleteRangeAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);
/// <summary>
/// Deletes all the entities in the <typeparamref name="TEntity"/> table.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// await databaseConnection.DeleteAllAsync<DogEntity>();
/// ]]>
/// </code>
/// </example>
/// <returns>The number of deleted entities.</returns>
Task<CommandResult> DeleteAllAsync<TEntity>(int? commandTimeout = null, CancellationToken cancellationToken = default);
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Serialization;
namespace Orleans.Streams
{
[Serializable]
[Immutable]
internal class StreamImpl<T> : IAsyncStream<T>, IStreamControl, ISerializable, IOnDeserialized
{
private readonly InternalStreamId streamId;
private readonly bool isRewindable;
[NonSerialized]
private IInternalStreamProvider provider;
[NonSerialized]
private volatile IInternalAsyncBatchObserver<T> producerInterface;
[NonSerialized]
private IInternalAsyncObservable<T> consumerInterface;
[NonSerialized]
private readonly object initLock; // need the lock since the same code runs in the provider on the client and in the silo.
[NonSerialized]
private IRuntimeClient runtimeClient;
internal InternalStreamId InternalStreamId { get { return streamId; } }
public StreamId StreamId => streamId;
public bool IsRewindable { get { return isRewindable; } }
public string ProviderName { get { return streamId.ProviderName; } }
// IMPORTANT: This constructor needs to be public for Json deserialization to work.
public StreamImpl()
{
initLock = new object();
}
internal StreamImpl(InternalStreamId streamId, IInternalStreamProvider provider, bool isRewindable, IRuntimeClient runtimeClient)
{
this.streamId = streamId;
this.provider = provider ?? throw new ArgumentNullException(nameof(provider));
this.runtimeClient = runtimeClient ?? throw new ArgumentNullException(nameof(runtimeClient));
producerInterface = null;
consumerInterface = null;
initLock = new object();
this.isRewindable = isRewindable;
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer)
{
return GetConsumerInterface().SubscribeAsync(observer, null);
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncObserver<T> observer, StreamSequenceToken token)
{
return GetConsumerInterface().SubscribeAsync(observer, token);
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncBatchObserver<T> batchObserver)
{
return GetConsumerInterface().SubscribeAsync(batchObserver);
}
public Task<StreamSubscriptionHandle<T>> SubscribeAsync(IAsyncBatchObserver<T> batchObserver, StreamSequenceToken token)
{
return GetConsumerInterface().SubscribeAsync(batchObserver, token);
}
public async Task Cleanup(bool cleanupProducers, bool cleanupConsumers)
{
// Cleanup producers
if (cleanupProducers && producerInterface != null)
{
await producerInterface.Cleanup();
producerInterface = null;
}
// Cleanup consumers
if (cleanupConsumers && consumerInterface != null)
{
await consumerInterface.Cleanup();
consumerInterface = null;
}
}
public Task OnNextAsync(T item, StreamSequenceToken token = null)
{
return GetProducerInterface().OnNextAsync(item, token);
}
public Task OnNextBatchAsync(IEnumerable<T> batch, StreamSequenceToken token)
{
return GetProducerInterface().OnNextBatchAsync(batch, token);
}
public Task OnCompletedAsync()
{
IInternalAsyncBatchObserver<T> producerInterface = GetProducerInterface();
return producerInterface.OnCompletedAsync();
}
public Task OnErrorAsync(Exception ex)
{
IInternalAsyncBatchObserver<T> producerInterface = GetProducerInterface();
return producerInterface.OnErrorAsync(ex);
}
internal Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncObserver<T> observer,
StreamSequenceToken token)
{
return GetConsumerInterface().ResumeAsync(handle, observer, token);
}
internal Task<StreamSubscriptionHandle<T>> ResumeAsync(
StreamSubscriptionHandle<T> handle,
IAsyncBatchObserver<T> observer,
StreamSequenceToken token)
{
return GetConsumerInterface().ResumeAsync(handle, observer, token);
}
public Task<IList<StreamSubscriptionHandle<T>>> GetAllSubscriptionHandles()
{
return GetConsumerInterface().GetAllSubscriptions();
}
internal Task UnsubscribeAsync(StreamSubscriptionHandle<T> handle)
{
return GetConsumerInterface().UnsubscribeAsync(handle);
}
internal IInternalAsyncBatchObserver<T> GetProducerInterface()
{
if (producerInterface != null) return producerInterface;
lock (initLock)
{
if (producerInterface != null)
return producerInterface;
if (provider == null)
provider = GetStreamProvider();
producerInterface = provider.GetProducerInterface(this);
}
return producerInterface;
}
internal IInternalAsyncObservable<T> GetConsumerInterface()
{
if (consumerInterface == null)
{
lock (initLock)
{
if (consumerInterface == null)
{
if (provider == null)
provider = GetStreamProvider();
consumerInterface = provider.GetConsumerInterface<T>(this);
}
}
}
return consumerInterface;
}
private IInternalStreamProvider GetStreamProvider()
{
return this.runtimeClient.ServiceProvider.GetRequiredServiceByName<IStreamProvider>(streamId.ProviderName) as IInternalStreamProvider;
}
public int CompareTo(IAsyncStream<T> other)
{
var o = other as StreamImpl<T>;
return o == null ? 1 : streamId.CompareTo(o.streamId);
}
public virtual bool Equals(IAsyncStream<T> other)
{
var o = other as StreamImpl<T>;
return o != null && streamId.Equals(o.streamId);
}
public override bool Equals(object obj)
{
var o = obj as StreamImpl<T>;
return o != null && streamId.Equals(o.streamId);
}
public override int GetHashCode()
{
return streamId.GetHashCode();
}
public override string ToString()
{
return streamId.ToString();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("StreamId", streamId, typeof(InternalStreamId));
info.AddValue("IsRewindable", isRewindable, typeof(bool));
}
// The special constructor is used to deserialize values.
protected StreamImpl(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
streamId = (InternalStreamId)info.GetValue("StreamId", typeof(InternalStreamId));
isRewindable = info.GetBoolean("IsRewindable");
initLock = new object();
var serializerContext = context.Context as ISerializerContext;
((IOnDeserialized)this).OnDeserialized(serializerContext);
}
void IOnDeserialized.OnDeserialized(ISerializerContext context)
{
this.runtimeClient = context?.AdditionalContext as IRuntimeClient;
}
}
}
| |
using System;
using System.Security.AccessControl;
using System.Runtime.InteropServices;
using Asprosys.Win32;
namespace Asprosys.Security.AccessControl
{
/// <summary>
/// The base class for all security objects.
/// </summary>
public abstract class BaseSecurity : NativeObjectSecurity, IDisposable
{
private string m_Name;
private GenericSafeHandle m_Handle;
private StandardRights m_HandleRights = StandardRights.ReadPermissions;
private const int MaximumAccessAllowed = 0x02000000;
#region Constructors
internal BaseSecurity(bool isContainer)
: base(isContainer, ResourceType.Unknown)
{
}
internal BaseSecurity(ResourceType resType, bool isContainer)
: base(isContainer, resType)
{
}
internal BaseSecurity(string objectName, ResourceType resType, AccessControlSections sectionsRequested, bool isContainer)
: base(isContainer, resType, objectName, sectionsRequested)
{
m_Name = objectName;
}
internal BaseSecurity(GenericSafeHandle objectHandle, ResourceType resType, AccessControlSections sectionsRequested, bool isContainer)
: base(isContainer, resType, objectHandle, sectionsRequested)
{
m_Handle = objectHandle;
}
#endregion
#region Persistence methods
/// <summary>
/// Persists the changes made to the security object. Must be overridden for
/// custom security objects.
/// </summary>
public virtual void AcceptChanges()
{
if (m_Name == null && m_Handle == null)
throw new InvalidOperationException("Not associated with a valid Securable Object.");
base.WriteLock();
try
{
AccessControlSections sectionsChanged = GetSectionsChanged();
if (sectionsChanged != AccessControlSections.None)
{
if (m_Name != null)
{
base.Persist(m_Name, sectionsChanged);
}
else
{
MakeWriteableHandle(sectionsChanged);
base.Persist(m_Handle, sectionsChanged);
}
ClearSectionsChanged();
}
}
finally
{
base.WriteUnlock();
}
}
/// <summary>
/// Gets the access control sections that have been changed.
/// </summary>
/// <returns></returns>
protected AccessControlSections GetSectionsChanged()
{
AccessControlSections sectionsChanged = AccessControlSections.None;
if (base.OwnerModified) sectionsChanged |= AccessControlSections.Owner;
if (base.GroupModified) sectionsChanged |= AccessControlSections.Group;
if (base.AccessRulesModified) sectionsChanged |= AccessControlSections.Access;
if (base.AuditRulesModified) sectionsChanged |= AccessControlSections.Audit;
return sectionsChanged;
}
/// <summary>
/// Resets the sections changed flags.
/// </summary>
protected void ClearSectionsChanged()
{
base.OwnerModified = false;
base.GroupModified = false;
base.AccessRulesModified = false;
base.AuditRulesModified = false;
}
#endregion
#region Handle Methods
private void MakeWriteableHandle(AccessControlSections sectionsToWrite)
{
StandardRights rightsRequired = m_HandleRights;
bool newHandleRequired = false;
if ((sectionsToWrite & AccessControlSections.Access) != 0 || (sectionsToWrite & AccessControlSections.Group) != 0)
{
if ((m_HandleRights & StandardRights.WritePermissions) == 0)
{
rightsRequired |= StandardRights.WritePermissions;
newHandleRequired = true;
}
}
if ((sectionsToWrite & AccessControlSections.Owner) != 0)
{
if ((m_HandleRights & StandardRights.TakeOwnership) == 0)
{
rightsRequired |= StandardRights.TakeOwnership;
newHandleRequired = true;
}
}
if ((sectionsToWrite & AccessControlSections.Audit) != 0)
{
if ((m_HandleRights & (StandardRights)NativeConstants.ACCESS_SYSTEM_SECURITY) == 0)
{
rightsRequired |= (StandardRights)NativeConstants.ACCESS_SYSTEM_SECURITY;
newHandleRequired = true;
}
}
if (newHandleRequired)
{
IntPtr writeHandle = NativeMethods.DuplicateHandle(m_Handle.DangerousGetHandle(), (int)rightsRequired);
if (writeHandle == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
switch (err)
{
case NativeConstants.ERROR_ACCESS_DENIED:
throw new UnauthorizedAccessException();
default:
throw new System.ComponentModel.Win32Exception(err);
}
}
try
{
m_Handle = new GenericSafeHandle(writeHandle, m_Handle);
m_HandleRights = rightsRequired;
}
catch
{
//Should only happen if out of memory. Release new handle and rethrow.
NativeMethods.CloseHandle(writeHandle);
throw;
}
}
}
internal static GenericSafeHandle GetReadHandle(IntPtr handle)
{
return GetReadHandle(handle, NativeMethods.CloseHandle);
}
internal static GenericSafeHandle GetReadHandle(IntPtr handle, ReleaseHandleCallback releaseCallback)
{
IntPtr readHandle = NativeMethods.DuplicateHandle(handle, (int)StandardRights.ReadPermissions);
if (readHandle == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
switch (err)
{
case NativeConstants.ERROR_ACCESS_DENIED:
throw new UnauthorizedAccessException();
default:
throw new System.ComponentModel.Win32Exception(err);
}
}
return new GenericSafeHandle(readHandle, releaseCallback);
}
#endregion
#region Access Methods
/// <summary>
/// Gets the generic mapping associated with the securable object.
/// </summary>
/// <returns>A <see cref="GenericMapping"/> associated with this security
/// object type.</returns>
protected abstract GenericMapping GetGenericMapping();
/// <summary>
/// Gets a bitmask representing the maximum access allowed to this
/// securable object.
/// </summary>
/// <param name="tokenHandle">The handle to the token for which the
/// access is being calculated. This must be an impersonation token.</param>
/// <returns>An <see cref="Int32"/> containing the bitmask of the access
/// rights that have been granted to the user represented by the token.</returns>
public int GetMaximumAccessAllowed(SafeHandle tokenHandle)
{
int privilegeLength = 4096;
byte[] accessCheckBuffer = new byte[privilegeLength];
int accessGranted;
bool accessAllowed;
if (!NativeMethods.AccessCheck(base.GetSecurityDescriptorBinaryForm(), tokenHandle,
MaximumAccessAllowed, GetGenericMapping(), accessCheckBuffer, out privilegeLength,
out accessGranted, out accessAllowed))
{
int err = Marshal.GetLastWin32Error();
switch (err)
{
case NativeConstants.ERROR_ACCESS_DENIED:
throw new UnauthorizedAccessException();
case NativeConstants.ERROR_NO_IMPERSONATION_TOKEN:
throw new InvalidOperationException("The token is not an impersonation token.");
default:
throw new System.ComponentModel.Win32Exception(err);
}
}
return accessGranted;
}
/// <summary>
/// Determines whether the user represented by the specified token handle
/// has been granted access to this securable object.
/// </summary>
/// <param name="tokenHandle">The handle to the token for which the
/// access is being verified. This must be an impersonation token.</param>
/// <param name="desiredAccess">The desired access.</param>
/// <returns>
/// <c>true</c> if the desired access is allowed; otherwise, <c>false</c>.
/// </returns>
public bool IsAccessAllowed(SafeHandle tokenHandle, int desiredAccess)
{
int accessGranted;
bool accessAllowed;
int privilegeLength = 4096;
byte[] accessCheckBuffer = new byte[privilegeLength];
GenericMapping mapping = GetGenericMapping();
NativeMethods.MapGenericMask(ref desiredAccess, mapping);
if (!NativeMethods.AccessCheck(base.GetSecurityDescriptorBinaryForm(), tokenHandle,
desiredAccess, mapping, accessCheckBuffer, out privilegeLength, out accessGranted,
out accessAllowed))
{
int err = Marshal.GetLastWin32Error();
switch (err)
{
case NativeConstants.ERROR_ACCESS_DENIED:
throw new UnauthorizedAccessException();
case NativeConstants.ERROR_NO_IMPERSONATION_TOKEN:
throw new InvalidOperationException("The token is not an impersonation token.");
default:
throw new System.ComponentModel.Win32Exception(err);
}
}
return accessAllowed;
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
if (m_Handle != null) m_Handle.Close();
}
#endregion
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation
{
public class SmartIndenterEnterOnTokenTests : FormatterTestsBase
{
[WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MethodBody1()
{
var code = @"class Class1
{
void method()
{ }
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 3,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Preprocessor1()
{
var code = @"class A
{
#region T
#endregion
}
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Preprocessor2()
{
var code = @"class A
{
#line 1
#lien 2
}
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Preprocessor3()
{
var code = @"#region stuff
#endregion
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 2,
expectedIndentation: 0);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Comments()
{
var code = @"using System;
class Class
{
// Comments
// Comments
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task UsingDirective()
{
var code = @"using System;
using System.Linq;
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'u',
indentationLine: 1,
expectedIndentation: 0);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task AfterTopOfFileComment()
{
var code = @"// comment
class
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 2,
expectedIndentation: 0);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task DottedName()
{
var code = @"using System.
Collection;
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 1,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Namespace()
{
var code = @"using System;
namespace NS
{
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 3,
expectedIndentation: 0);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task NamespaceDottedName()
{
var code = @"using System;
namespace NS.
NS2
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task NamespaceBody()
{
var code = @"using System;
namespace NS
{
class
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'c',
indentationLine: 4,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task NamespaceCloseBrace()
{
var code = @"using System;
namespace NS
{
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 4,
expectedIndentation: 0);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Class()
{
var code = @"using System;
namespace NS
{
class Class
{
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 5,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ClassBody()
{
var code = @"using System;
namespace NS
{
class Class
{
int
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 6,
expectedIndentation: 8);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ClassCloseBrace()
{
var code = @"using System;
namespace NS
{
class Class
{
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 6,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Method()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 7,
expectedIndentation: 8);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MethodBody()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 8,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MethodCloseBrace()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 8,
expectedIndentation: 8);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Statement()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10;
int
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 9,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MethodCall()
{
var code = @"class c
{
void Method()
{
M(
a: 1,
b: 1);
}
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Switch()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 9,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task SwitchBody()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'c',
indentationLine: 10,
expectedIndentation: 16);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task SwitchCase()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
int
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 11,
expectedIndentation: 20);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task SwitchCaseBlock()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
{
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 11,
expectedIndentation: 20);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Block()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
switch (10)
{
case 10 :
{
int
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 12,
expectedIndentation: 24);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MultilineStatement1()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10 +
1
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 9,
expectedIndentation: 16);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MultilineStatement2()
{
var code = @"using System;
namespace NS
{
class Class
{
void Method()
{
int i = 10 +
20 +
30
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 10,
expectedIndentation: 20);
}
// Bug number 902477
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Comments2()
{
var code = @"class Class
{
void Method()
{
if (true) // Test
int
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task AfterCompletedBlock()
{
var code = @"class Program
{
static void Main(string[] args)
{
foreach(var a in x) {}
int
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 5,
expectedIndentation: 8);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task AfterTopLevelAttribute()
{
var code = @"class Program
{
[Attr]
[
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'[',
indentationLine: 3,
expectedIndentation: 4);
}
[WorkItem(537802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537802")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task EmbededStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
if (true)
Console.WriteLine(1);
int
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'i',
indentationLine: 6,
expectedIndentation: 8);
}
[WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MethodBraces1()
{
var code = @"class Class1
{
void method()
{ }
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 3,
expectedIndentation: 4);
}
[WorkItem(537808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537808")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task MethodBraces2()
{
var code = @"class Class1
{
void method()
{
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 4,
expectedIndentation: 4);
}
[WorkItem(537795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537795")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Property1()
{
var code = @"class C
{
string Name
{
get;
set;
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 6,
expectedIndentation: 4);
}
[WorkItem(537563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537563")]
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Class1()
{
var code = @"class C
{
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 2,
expectedIndentation: 0);
}
[WpfFact]
[WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ArrayInitializer1()
{
var code = @"class C
{
var a = new []
{ 1, 2, 3 }
}
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ArrayInitializer2()
{
var code = @"class C
{
var a = new []
{
1, 2, 3
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 5,
expectedIndentation: 4);
}
[WpfFact]
[WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public async Task ArrayInitializer3()
{
var code = @"namespace NS
{
class Class
{
void Method(int i)
{
var a = new []
{
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 7,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task QueryExpression2()
{
var code = @"class C
{
void Method()
{
var a = from c in b
where
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'w',
indentationLine: 5,
expectedIndentation: 16);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task QueryExpression3()
{
var code = @"class C
{
void Method()
{
var a = from c in b
where select
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'w',
indentationLine: 5,
expectedIndentation: 16);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task QueryExpression4()
{
var code = @"class C
{
void Method()
{
var a = from c in b where c > 10
select
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
's',
indentationLine: 5,
expectedIndentation: 16);
}
[WpfFact]
[WorkItem(853748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853748")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ArrayInitializer()
{
var code = @"class C
{
void Method()
{
var l = new int[] {
}
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'}',
indentationLine: 5,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(939305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939305")]
[WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ArrayExpression()
{
var code = @"class C
{
void M(object[] q)
{
M(
q: new object[]
{ });
}
}
";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 6,
expectedIndentation: 14);
}
[WpfFact]
[WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task CollectionExpression()
{
var code = @"class C
{
void M(List<int> e)
{
M(
new List<int>
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
}
}
";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 6,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(1070773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070773")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task ObjectInitializer()
{
var code = @"class C
{
void M(What dd)
{
M(
new What
{ d = 3, dd = "" });
}
}
class What
{
public int d;
public string dd;
}";
await AssertIndentUsingSmartTokenFormatterAsync(
code,
'{',
indentationLine: 6,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task Preprocessor()
{
var code = @"
#line 1 """"Bar""""class Foo : [|IComparable|]#line default#line hidden";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 1,
expectedIndentation: 0);
}
[WpfFact]
[WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInitializerWithTypeBody_Implicit()
{
var code = @"class X {
int[] a = {
1,
};
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInitializerWithTypeBody_ImplicitNew()
{
var code = @"class X {
int[] a = new[] {
1,
};
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInitializerWithTypeBody_Explicit()
{
var code = @"class X {
int[] a = new int[] {
1,
};
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInitializerWithTypeBody_Collection()
{
var code = @"using System.Collections.Generic;
class X {
private List<int> a = new List<int>() {
1,
};
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 4,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(1070774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070774")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInitializerWithTypeBody_ObjectInitializers()
{
var code = @"class C
{
private What sdfsd = new What
{
d = 3,
}
}
class What
{
public int d;
public string dd;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationString_1()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""
{Program.number}"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationString_2()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment
{Program.number}"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationString_3()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment{Program.number}
"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationString_4()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment{Program.number}Comment here
"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 0);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task OutsideInterpolationString()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""Comment{Program.number}Comment here""
;
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_1()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""{
Program.number}"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_2()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""{
Program
.number}"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 6,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_3()
{
var code = @"class Program
{
static void Main(string[] args)
{
var s = $@""{
}"";
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_4()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{
((Func<int, int>)((int s) => { return number; })).Invoke(3):(408) ###-####}"");
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_5()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{ ((Func<int, int>)((int s)
=> { return number; })).Invoke(3):(408) ###-####}"");
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_6()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) => { return number; }))
.Invoke(3):(408) ###-####}"");
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 12);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task InsideInterpolationSyntax_7()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine($@""PPP{ ((Func<int, int>)((int s) =>
{ return number; })).Invoke(3):(408) ###-####}"");
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(872, "https://github.com/dotnet/roslyn/issues/872")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task IndentLambdaBodyOneIndentationToFirstTokenOfTheStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
Console.WriteLine(((Func<int, int>)((int s) =>
{ return number; })).Invoke(3));
}
static int number;
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 5,
expectedIndentation: 8);
}
[WpfFact]
[WorkItem(1339, "https://github.com/dotnet/roslyn/issues/1339")]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task IndentAutoPropertyInitializerAsPartOfTheDeclaration()
{
var code = @"class Program
{
public int d { get; }
= 3;
static void Main(string[] args)
{
}
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 3,
expectedIndentation: 8);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task IndentPatternPropertyFirst()
{
var code = @"
class C
{
void Main(object o)
{
var y = o is Point
{
}
}
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 7,
expectedIndentation: 12);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartIndent)]
public async Task IndentPatternPropertySecond()
{
var code = @"
class C
{
void Main(object o)
{
var y = o is Point
{
X is 13,
}
}
}";
await AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
code,
indentationLine: 8,
expectedIndentation: 12);
}
private async Task AssertIndentUsingSmartTokenFormatterAsync(
string code,
char ch,
int indentationLine,
int? expectedIndentation)
{
// create tree service
using (var workspace = TestWorkspace.CreateCSharp(code))
{
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var snapshot = buffer.CurrentSnapshot;
var line = snapshot.GetLineFromLineNumber(indentationLine);
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax;
Assert.True(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(workspace, root.Language),
root, line.AsTextLine(), await document.GetOptionsAsync(), CancellationToken.None));
var actualIndentation = await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch);
Assert.Equal(expectedIndentation.Value, actualIndentation);
}
}
private async Task AssertIndentNotUsingSmartTokenFormatterButUsingIndenterAsync(
string code,
int indentationLine,
int? expectedIndentation)
{
// create tree service
using (var workspace = TestWorkspace.CreateCSharp(code))
{
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var snapshot = buffer.CurrentSnapshot;
var line = snapshot.GetLineFromLineNumber(indentationLine);
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var root = (await document.GetSyntaxRootAsync()) as CompilationUnitSyntax;
Assert.False(
CSharpIndentationService.ShouldUseSmartTokenFormatterInsteadOfIndenter(
Formatter.GetDefaultFormattingRules(workspace, root.Language),
root, line.AsTextLine(), await document.GetOptionsAsync(), CancellationToken.None));
TestIndentation(indentationLine, expectedIndentation, workspace);
}
}
}
}
| |
using Plugin.VersionTracking.Abstractions;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Windows.ApplicationModel;
using Windows.Storage;
namespace Plugin.VersionTracking
{
/// <summary>
/// Implementation for VersionTracking
/// </summary>
public class VersionTrackingImplementation : IVersionTracking
{
private static ApplicationDataContainer AppSettings {
get { return ApplicationData.Current.LocalSettings; }
}
private readonly object locker = new object();
Dictionary<string, List<string>> versionTrail;
bool isFirstLaunchEver;
bool isFirstLaunchForVersion;
bool isFirstLaunchForBuild;
const string xamUserDefaultsVersionTrailKey = @"xamVersionTrail";
const string xamVersionsKey = @"xamVersion";
const string xamBuildsKey = @"xamBuild";
/// <summary>
/// Call this as the VERY FIRST THING in FinishedLaunching
/// </summary>
public void Track()
{
var needsSync = false;
// load history
var noValues = (!AppSettings.Values.ContainsKey(xamVersionsKey) || !AppSettings.Values.ContainsKey(xamBuildsKey));
if (noValues) {
isFirstLaunchEver = true;
versionTrail = new Dictionary<string, List<string>> {
{ xamVersionsKey, new List<string>() },
{ xamBuildsKey, new List<string>() }
};
} else {
var oldVersionList = (AppSettings.Values[xamVersionsKey] as string)?.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List<string>();
var oldBuildList = (AppSettings.Values[xamBuildsKey] as string)?.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List<string>();
versionTrail = new Dictionary<string, List<string>> {
{ xamVersionsKey, oldVersionList },
{ xamBuildsKey, oldBuildList }
};
isFirstLaunchEver = false;
needsSync = true;
}
//check if this version was previously launched
if (versionTrail[xamVersionsKey].Contains(CurrentVersion)) {
isFirstLaunchForVersion = false;
} else {
isFirstLaunchForVersion = true;
versionTrail[xamVersionsKey].Add(CurrentVersion);
needsSync = true;
}
//check if this build was previously launched
if (versionTrail[xamBuildsKey].Contains(CurrentBuild)) {
isFirstLaunchForBuild = false;
} else {
isFirstLaunchForBuild = true;
versionTrail[xamBuildsKey].Add(CurrentBuild);
needsSync = true;
}
//store the new version stuff
if (needsSync) {
lock (locker) {
if (!AppSettings.Values.ContainsKey(xamVersionsKey)) {
AppSettings.CreateContainer(xamVersionsKey, ApplicationDataCreateDisposition.Always);
}
if (AppSettings.Values.ContainsKey(xamBuildsKey)) {
AppSettings.CreateContainer(xamBuildsKey, ApplicationDataCreateDisposition.Always);
}
AppSettings.Values[xamVersionsKey] = String.Join("|", versionTrail[xamVersionsKey]);
AppSettings.Values[xamBuildsKey] = String.Join("|", versionTrail[xamBuildsKey]);
}
}
}
/// <summary>
/// Check if this is the first time ever that the app is launched.
/// </summary>
/// <value>The is first launch ever.</value>
public bool IsFirstLaunchEver => isFirstLaunchEver;
/// <summary>
/// Check if this is the first time that this particular version is being launched.
/// </summary>
/// <value>The is first launch for current version.</value>
public bool IsFirstLaunchForVersion => isFirstLaunchForVersion;
/// <summary>
/// Check if this is the first time that this particular build is being launched.
/// </summary>
/// <value>The is first launch for current build.</value>
public bool IsFirstLaunchForBuild => isFirstLaunchForBuild;
/// <summary>
/// Returns the current version of the app, as defined in the PList, e.g. "4.3".
/// </summary>
/// <value>The current version.</value>
public string CurrentVersion {
get {
var version = Package.Current.Id.Version;
return string.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision);
}
}
/// <summary>
/// Returns the current build of the app, as defined in the PList, e.g. "4300".
/// </summary>
/// <value>The current build.</value>
public string CurrentBuild => Package.Current.Id.Version.Build.ToString();
/// <summary>
/// Returns the previous version of the app, e.g. "4.3".
/// </summary>
/// <value>The previous version.</value>
public string PreviousVersion {
get {
var count = versionTrail?[xamVersionsKey]?.Count ?? 0;
return (count >= 2) ? versionTrail[xamVersionsKey][count - 2] : null;
}
}
/// <summary>
/// Returns the previous build of the app, "4300".
/// </summary>
/// <value>The previous build.</value>
public string PreviousBuild {
get {
var count = versionTrail?[xamBuildsKey]?.Count ?? 0;
return (count >= 2) ? versionTrail[xamBuildsKey][count - 2] : null;
}
}
/// <summary>
/// Returns the version which the user first installed the app.
/// </summary>
/// <value>The first installed version.</value>
public string FirstInstalledVersion => versionTrail?[xamVersionsKey]?.FirstOrDefault();
/// <summary>
/// Returns the build which the user first installed the app.
/// </summary>
/// <value>The first installed build.</value>
public string FirstInstalledBuild => versionTrail?[xamBuildsKey]?.FirstOrDefault();
/// <summary>
/// Returns a List of versions which the user has had installed, e.g. ["3.5", "4.0", "4.1"].
/// The List is ordered from first version installed to (including) the current version
/// </summary>
/// <value>The version history.</value>
public List<string> VersionHistory => versionTrail?[xamVersionsKey] ?? new List<string>();
/// <summary>
/// Returns a List of builds which the user has had installed, e.g. ["3500", "4000", "4100"].
/// The List is ordered from first build installed to (including) the current build
/// </summary>
/// <value>The build history.</value>
public List<string> BuildHistory => versionTrail?[xamBuildsKey] ?? new List<string>();
/// <summary>
/// Check if this is the first launch for a particular version number.
/// Useful if you want to execute some code for first time launches of a particular version
/// (like db migrations?).
/// </summary>
/// <returns>The first launch for version.</returns>
/// <param name="version">Version.</param>
public bool FirstLaunchForVersion(string version) =>
(CurrentVersion.Equals(version, StringComparison.OrdinalIgnoreCase)) && isFirstLaunchForVersion;
/// <summary>
/// Check if this is the first launch for a particular build number.
/// Useful if you want to execute some code for first time launches of a particular version
/// (like db migrations?).
/// </summary>
/// <returns>The first launch for build.</returns>
/// <param name="build">Build.</param>
public bool FirstLaunchForBuild(string build) =>
(CurrentBuild.Equals(build, StringComparison.OrdinalIgnoreCase)) && isFirstLaunchForBuild;
/// <summary>
/// Calls block if the condition is satisfied that the current version matches `version`,
/// and this is the first time this app version is being launched.
/// </summary>
/// <returns>The first launch of version.</returns>
/// <param name="version">Version.</param>
/// <param name="block">Block.</param>
public void OnFirstLaunchOfVersion(string version, Action block)
{
if (FirstLaunchForVersion(version)) block?.Invoke();
}
/// <summary>
/// Calls block if the condition is satisfied that the current build matches `build`,
/// and this is the first time this app build is being launched.
/// </summary>
/// <returns>The first launch of build.</returns>
/// <param name="build">Build.</param>
/// <param name="block">Block.</param>
public void OnFirstLaunchOfBuild(string build, Action block)
{
if (FirstLaunchForBuild(build)) block?.Invoke();
}
/// <summary>
/// Output to string
/// </summary>
/// <returns></returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("VersionTracking");
sb.AppendFormat(" {0}{1}\n", "IsFirstLaunchEver".PadRight(25), IsFirstLaunchEver);
sb.AppendFormat(" {0}{1}\n", "IsFirstLaunchForVersion".PadRight(25), IsFirstLaunchForVersion);
sb.AppendFormat(" {0}{1}\n", "IsFirstLaunchForBuild".PadRight(25), IsFirstLaunchForBuild);
sb.AppendFormat(" {0}{1}\n", "CurrentVersion".PadRight(25), CurrentVersion);
sb.AppendFormat(" {0}{1}\n", "PreviousVersion".PadRight(25), PreviousVersion);
sb.AppendFormat(" {0}{1}\n", "FirstInstalledVersion".PadRight(25), FirstInstalledVersion);
sb.AppendFormat(" {0}[ {1} ]\n", "VersionHistory".PadRight(25), string.Join(", ", VersionHistory));
sb.AppendFormat(" {0}{1}\n", "CurrentBuild".PadRight(25), CurrentBuild);
sb.AppendFormat(" {0}{1}\n", "PreviousBuild".PadRight(25), PreviousBuild);
sb.AppendFormat(" {0}{1}\n", "FirstInstalledBuild".PadRight(25), FirstInstalledBuild);
sb.AppendFormat(" {0}[ {1} ]\n", "BuildHistory".PadRight(25), string.Join(", ", BuildHistory));
return sb.ToString();
}
}
}
| |
// <copyright file="UpdateMapTests.cs" company="Basho Technologies, Inc.">
// Copyright 2015 - Basho Technologies, Inc.
//
// This file is provided 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.
// </copyright>
namespace Test.Unit.CRDT
{
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using RiakClient;
using RiakClient.Commands.CRDT;
using RiakClient.Messages;
using RiakClient.Util;
[TestFixture, UnitTest]
public class UpdateMapTests
{
private const string BucketType = "maps";
private const string Bucket = "myBucket";
private const string Key = "map_1";
private static readonly byte[] Context = Encoding.UTF8.GetBytes("test-context");
[Test]
public void Should_Build_DtUpdateReq_Correctly()
{
var mapOp = new UpdateMap.MapOperation()
.IncrementCounter("counter_1", 50)
.RemoveCounter("counter_2")
.AddToSet("set_1", "set_value_1")
.RemoveFromSet("set_2", "set_value_2")
.RemoveSet("set_3")
.SetRegister("register_1", "register_value_1")
.RemoveRegister("register_2")
.SetFlag("flag_1", true)
.RemoveFlag("flag_2")
.RemoveMap("map_3");
mapOp.Map("map_2").IncrementCounter("counter_1", 50)
.RemoveCounter("counter_2")
.AddToSet("set_1", "set_value_1")
.RemoveFromSet("set_2", "set_value_2")
.RemoveSet("set_3")
.SetRegister("register_1", "register_value_1")
.RemoveRegister("register_2")
.SetFlag("flag_1", true)
.RemoveFlag("flag_2")
.RemoveMap("map_3");
var updateMapCommandBuilder = new UpdateMap.Builder(mapOp);
var q1 = new Quorum(1);
var q2 = new Quorum(2);
var q3 = new Quorum(3);
updateMapCommandBuilder
.WithBucketType(BucketType)
.WithBucket(Bucket)
.WithKey(Key)
.WithContext(Context)
.WithW(q3)
.WithPW(q1)
.WithDW(q2)
.WithReturnBody(true)
.WithIncludeContext(false)
.WithTimeout(TimeSpan.FromSeconds(20));
UpdateMap updateMapCommand = updateMapCommandBuilder.Build();
DtUpdateReq protobuf = (DtUpdateReq)updateMapCommand.ConstructRequest(false);
Assert.AreEqual(Encoding.UTF8.GetBytes(BucketType), protobuf.type);
Assert.AreEqual(Encoding.UTF8.GetBytes(Bucket), protobuf.bucket);
Assert.AreEqual(Encoding.UTF8.GetBytes(Key), protobuf.key);
Assert.AreEqual((uint)q3, protobuf.w);
Assert.AreEqual((uint)q1, protobuf.pw);
Assert.AreEqual((uint)q2, protobuf.dw);
Assert.IsTrue(protobuf.return_body);
Assert.IsFalse(protobuf.include_context);
Assert.AreEqual(20000, protobuf.timeout);
Assert.AreEqual(Context, protobuf.context);
MapOp mapOpMsg = protobuf.op.map_op;
VerifyRemoves(mapOpMsg.removes);
MapUpdate innerMapUpdate = VerifyUpdates(mapOpMsg.updates, true);
VerifyRemoves(innerMapUpdate.map_op.removes);
VerifyUpdates(innerMapUpdate.map_op.updates, false);
}
[Test]
public void Should_Construct_MapResponse_From_DtUpdateResp()
{
var key = new RiakString("riak_generated_key");
var context = new RiakString("1234");
var updateResp = new DtUpdateResp();
updateResp.key = key;
updateResp.context = context;
Func<IEnumerable<MapEntry>> createMapEntries = () =>
{
var mapEntries = new List<MapEntry>();
var mapField = new MapField();
mapField.type = MapField.MapFieldType.COUNTER;
mapField.name = new RiakString("counter_1");
var mapEntry = new MapEntry();
mapEntry.field = mapField;
mapEntry.counter_value = 50;
mapEntries.Add(mapEntry);
mapField = new MapField();
mapField.type = MapField.MapFieldType.SET;
mapField.name = new RiakString("set_1");
mapEntry = new MapEntry();
mapEntry.field = mapField;
mapEntry.set_value.Add(RiakString.ToBytes("value_1"));
mapEntry.set_value.Add(RiakString.ToBytes("value_2"));
mapEntries.Add(mapEntry);
mapField = new MapField();
mapField.type = MapField.MapFieldType.REGISTER;
mapField.name = new RiakString("register_1");
mapEntry = new MapEntry();
mapEntry.field = mapField;
mapEntry.register_value = RiakString.ToBytes("1234");
mapEntries.Add(mapEntry);
mapField = new MapField();
mapField.type = MapField.MapFieldType.FLAG;
mapField.name = new RiakString("flag_1");
mapEntry = new MapEntry();
mapEntry.field = mapField;
mapEntry.flag_value = true;
mapEntries.Add(mapEntry);
return mapEntries;
};
updateResp.map_value.AddRange(createMapEntries());
var map_1_field = new MapField();
map_1_field.type = MapField.MapFieldType.MAP;
map_1_field.name = new RiakString("map_1");
var map_1_entry = new MapEntry();
map_1_entry.field = map_1_field;
map_1_entry.map_value.AddRange(createMapEntries());
updateResp.map_value.Add(map_1_entry);
Action<Map> verifyMap = (map) =>
{
Assert.AreEqual(50, map.Counters["counter_1"]);
Assert.AreEqual(RiakString.ToBytes("value_1"), map.Sets["set_1"][0]);
Assert.AreEqual(RiakString.ToBytes("value_2"), map.Sets["set_1"][1]);
Assert.AreEqual(RiakString.ToBytes("1234"), map.Registers["register_1"]);
Assert.IsTrue(map.Flags["flag_1"]);
};
var mapOp = new UpdateMap.MapOperation();
var update = new UpdateMap.Builder(mapOp)
.WithBucketType("maps")
.WithBucket("myBucket")
.WithKey("map_1")
.Build();
update.OnSuccess(updateResp);
MapResponse response = update.Response;
Assert.NotNull(response);
Assert.AreEqual(key, response.Key);
Assert.AreEqual(RiakString.ToBytes(context), response.Context);
verifyMap(response.Value);
verifyMap(response.Value.Maps["map_1"]);
}
private static void VerifyRemoves(ICollection<MapField> mapFields)
{
Assert.AreEqual(5, mapFields.Count);
bool counterRemoved = false;
bool setRemoval = false;
bool registerRemoved = false;
bool flagRemoved = false;
bool mapRemoved = false;
foreach (MapField mapField in mapFields)
{
switch (mapField.type)
{
case MapField.MapFieldType.COUNTER:
Assert.AreEqual(Encoding.UTF8.GetBytes("counter_2"), mapField.name);
counterRemoved = true;
break;
case MapField.MapFieldType.SET:
Assert.AreEqual(Encoding.UTF8.GetBytes("set_3"), mapField.name);
setRemoval = true;
break;
case MapField.MapFieldType.MAP:
Assert.AreEqual(Encoding.UTF8.GetBytes("map_3"), mapField.name);
mapRemoved = true;
break;
case MapField.MapFieldType.REGISTER:
Assert.AreEqual(Encoding.UTF8.GetBytes("register_2"), mapField.name);
registerRemoved = true;
break;
case MapField.MapFieldType.FLAG:
Assert.AreEqual(Encoding.UTF8.GetBytes("flag_2"), mapField.name);
flagRemoved = true;
break;
default:
break;
}
}
Assert.IsTrue(counterRemoved);
Assert.IsTrue(setRemoval);
Assert.IsTrue(registerRemoved);
Assert.IsTrue(flagRemoved);
Assert.IsTrue(mapRemoved);
}
private static MapUpdate VerifyUpdates(IEnumerable<MapUpdate> updates, bool expectMapUpdate)
{
bool counterIncremented = false;
bool setAddedTo = false;
bool setRemovedFrom = false;
bool registerSet = false;
bool flagSet = false;
bool mapAdded = false;
MapUpdate mapUpdate = null;
foreach (MapUpdate update in updates)
{
switch (update.field.type)
{
case MapField.MapFieldType.COUNTER:
Assert.AreEqual(Encoding.UTF8.GetBytes("counter_1"), update.field.name);
Assert.AreEqual(50, update.counter_op.increment);
counterIncremented = true;
break;
case MapField.MapFieldType.SET:
if (!EnumerableUtil.IsNullOrEmpty(update.set_op.adds))
{
Assert.AreEqual(Encoding.UTF8.GetBytes("set_1"), update.field.name);
Assert.AreEqual(Encoding.UTF8.GetBytes("set_value_1"), update.set_op.adds[0]);
setAddedTo = true;
}
else
{
Assert.AreEqual(Encoding.UTF8.GetBytes("set_2"), update.field.name);
Assert.AreEqual(Encoding.UTF8.GetBytes("set_value_2"), update.set_op.removes[0]);
setRemovedFrom = true;
}
break;
case MapField.MapFieldType.MAP:
if (expectMapUpdate)
{
Assert.AreEqual(Encoding.UTF8.GetBytes("map_2"), update.field.name);
mapAdded = true;
mapUpdate = update;
}
break;
case MapField.MapFieldType.REGISTER:
Assert.AreEqual(Encoding.UTF8.GetBytes("register_1"), update.field.name);
Assert.AreEqual(Encoding.UTF8.GetBytes("register_value_1"), update.register_op);
registerSet = true;
break;
case MapField.MapFieldType.FLAG:
Assert.AreEqual(Encoding.UTF8.GetBytes("flag_1"), update.field.name);
Assert.AreEqual(MapUpdate.FlagOp.ENABLE, update.flag_op);
flagSet = true;
break;
default:
break;
}
}
Assert.IsTrue(counterIncremented);
Assert.IsTrue(setAddedTo);
Assert.IsTrue(setRemovedFrom);
Assert.IsTrue(registerSet);
Assert.IsTrue(flagSet);
if (expectMapUpdate)
{
Assert.IsTrue(mapAdded);
}
else
{
Assert.IsFalse(mapAdded);
}
return mapUpdate;
}
}
}
| |
using System;
using System.Drawing;
namespace Rectangle
{
public partial class Rect
{
Rect Modify(Action<Rect> modify)
{
Rect newRect = Clone();
modify(newRect);
return newRect;
}
// Horizontal dimension, basic properties
public Rect Left(float left)
{
return Modify((Rect rect) => rect.SetLeft(left));
}
public Rect CenterX(float centerX)
{
return Modify((Rect rect) => rect.SetCenterX(centerX));
}
public Rect Right(float right)
{
return Modify((Rect rect) => rect.SetRight(right));
}
public Rect Width(float width)
{
return Modify((Rect rect) => rect.SetWidth(width));
}
// Vertical dimension, basic properties
public Rect Top(float top)
{
return Modify((Rect rect) => rect.SetTop(top));
}
public Rect CenterY(float centerY)
{
return Modify((Rect rect) => rect.SetCenterY(centerY));
}
public Rect Bottom(float bottom)
{
return Modify((Rect rect) => rect.SetBottom(bottom));
}
public Rect Height(float height)
{
return Modify((Rect rect) => rect.SetHeight(height));
}
// Horizontal dimension, from RectangleF
public Rect ToLeftOf(RectangleF rect, float margin = 0)
{
return Right(rect.Left - margin);
}
public Rect ToRightOf(RectangleF rect, float margin = 0)
{
return Left(rect.Right + margin);
}
public Rect AtRightOf(RectangleF rect, float margin = 0)
{
return Right(rect.Right - margin);
}
public Rect AtLeftOf(RectangleF rect, float margin = 0)
{
return Left(rect.Left + margin);
}
public Rect LeftOf(RectangleF rect)
{
return Left(rect.Left);
}
public Rect RightOf(RectangleF rect)
{
return Right(rect.Right);
}
public Rect LeftRightOf(RectangleF rect, float margin = 0)
{
return Left(rect.Left + margin).Right(rect.Right - margin);
}
public Rect WidthOf(RectangleF rect)
{
return Width(rect.Width);
}
public Rect RelativeWidthOf(RectangleF rect, float fraction)
{
return Width(rect.Width * fraction);
}
public Rect CenterXOf(RectangleF rect)
{
return CenterX(rect.Left + rect.Width / 2);
}
// Vertical dimension, from RectangleF
public Rect Above(RectangleF rect, float margin = 0)
{
return Bottom(rect.Top - margin);
}
public Rect Below(RectangleF rect, float margin = 0)
{
return Top(rect.Bottom + margin);
}
public Rect AtTopOf(RectangleF rect, float margin = 0)
{
return Top(rect.Top + margin);
}
public Rect AtBottomOf(RectangleF rect, float margin = 0)
{
return Bottom(rect.Bottom - margin);
}
public Rect TopOf(RectangleF rect)
{
return Top(rect.Top);
}
public Rect BottomOf(RectangleF rect)
{
return Bottom(rect.Bottom);
}
public Rect TopBottomOf(RectangleF rect, float margin = 0)
{
return Top(rect.Top + margin).Bottom(rect.Bottom - margin);
}
public Rect HeightOf(RectangleF rect)
{
return Height(rect.Height);
}
public Rect RelativeHeightOf(RectangleF rect, float fraction)
{
return Height(rect.Height * fraction);
}
public Rect CenterYOf(RectangleF rect)
{
return CenterY(rect.Top + rect.Height / 2);
}
// Both dimensions, from RectangleF
public Rect TopLeftOf(RectangleF rect)
{
return TopOf(rect).LeftOf(rect);
}
public Rect CenterOf(RectangleF rect)
{
return CenterXOf(rect).CenterYOf(rect);
}
public Rect SizeOf(RectangleF rect)
{
return WidthOf(rect).HeightOf(rect);
}
public Rect RelativeSizeOf(RectangleF rect, float fraction)
{
return RelativeWidthOf(rect, fraction).RelativeHeightOf(rect, fraction);
}
public Rect LeftTopRightBottom(float left, float top, float right, float bottom)
{
return Left(left).Top(top).Right(right).Bottom(bottom);
}
public Rect LeftTopRightBottomOf(RectangleF rect)
{
return LeftOf(rect).TopOf(rect).BottomOf(rect).RightOf(rect);
}
public Rect LeftTopWidthHeight(float left, float top, float width, float height)
{
return Left(left).Top(top).Width(width).Height(height);
}
public Rect LeftTopWidthHeightOf(RectangleF rect)
{
return LeftOf(rect).TopOf(rect).WidthOf(rect).HeightOf(rect);
}
// Both dimensions, from SizeF
public Rect Size(SizeF size)
{
return Width(size.Width).Height(size.Height);
}
public Rect RelativeSize(SizeF size, float fraction)
{
return Width(size.Width * fraction).Height(size.Height * fraction);
}
public Rect Size(float width, float height)
{
return Width(width).Height(height);
}
// Both dimensions, from PointF
public Rect TopLeft(PointF point)
{
return Top(point.Y).Left(point.X);
}
public Rect TopRight(PointF point)
{
return Top(point.Y).Right(point.X);
}
public Rect TopCenter(PointF point)
{
return Top(point.Y).CenterX(point.X);
}
public Rect CenterLeft(PointF point)
{
return CenterY(point.Y).Left(point.X);
}
public Rect CenterRight(PointF point)
{
return CenterY(point.Y).Right(point.X);
}
public Rect BottomLeft(PointF point)
{
return Bottom(point.Y).Left(point.X);
}
public Rect BottomCenter(PointF point)
{
return Bottom(point.Y).CenterX(point.X);
}
public Rect BottomRight(PointF point)
{
return Bottom(point.Y).Right(point.X);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using L10NSharp;
using Microsoft.Win32;
using Palaso.UI.WindowsForms.Keyboarding;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
using Palaso.WritingSystems;
namespace Palaso.UI.WindowsForms.WritingSystems
{
public partial class WSKeyboardControl : UserControl
{
private class KeyboardDefinitionAdapter
{
private IKeyboardDefinition _descriptor;
public KeyboardDefinitionAdapter(IKeyboardDefinition descriptor)
{
_descriptor = descriptor;
}
public string Id
{
get { return _descriptor.Id; }
}
public string Layout
{
get { return _descriptor.Layout; }
}
public string Locale
{
get { return _descriptor.Locale; }
}
public override string ToString()
{
return _descriptor.LocalizedName;
}
}
private WritingSystemSetupModel _model;
private string _defaultFontName;
private float _defaultFontSize;
public WSKeyboardControl()
{
InitializeComponent();
if (KeyboardController.IsInitialized)
KeyboardController.Register(_testArea);
_defaultFontSize = _testArea.Font.SizeInPoints;
_defaultFontName = _testArea.Font.Name;
_possibleKeyboardsList.ShowItemToolTips = true;
#if MONO
// Keyman is not supported, setup link should not say "Windows".
_keymanConfigurationLink.Visible = false;
_keyboardSettingsLink.Text = L10NSharp.LocalizationManager.GetString("WSKeyboardControl.SetupKeyboards", "Set up keyboards");
// The sequence of Events in Mono dictate using GotFocus instead of Enter as the point
// when we want to assign keyboard and font to this textbox. (For some reason, using
// Enter works fine for the WSFontControl._testArea textbox control.)
this._testArea.Enter -= new System.EventHandler(this._testArea_Enter);
this._testArea.GotFocus += new System.EventHandler(this._testArea_Enter);
#endif
}
private bool _hookedToForm;
/// <summary>
/// This seems to be the best available hook to connect this control to the form's Activated event.
/// The control can't be visible until it is on a form!
/// It is tempting to unhook it when it is no longer visible, but unfortunately OnVisibleChanged
/// apparently doesn't work like that. According to http://memprofiler.com/articles/thecontrolvisiblechangedevent.aspx,
/// it is fired when visibility is gained because parent visibility changed, but not when visibility
/// is LOST because parent visibility changed.
/// </summary>
/// <param name="e"></param>
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (_hookedToForm || !(TopLevelControl is Form))
return;
_hookedToForm = true;
((Form) TopLevelControl).Activated += WSKeyboardControl_Activated;
}
// When the top-level form we are part of is activated, update our keyboard list,
// in case the user changed things using the control panel.
private void WSKeyboardControl_Activated(object sender, EventArgs e)
{
Keyboard.Controller.UpdateAvailableKeyboards(); // Enhance JohnT: would it be cleaner to have a Model method to do this?
PopulateKeyboardList();
UpdateFromModel(); // to restore selection.
}
public void BindToModel(WritingSystemSetupModel model)
{
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= ModelCurrentItemUpdated;
}
_model = model;
Enabled = false;
if (_model != null)
{
_model.SelectionChanged += ModelSelectionChanged;
_model.CurrentItemUpdated += ModelCurrentItemUpdated;
PopulateKeyboardList();
UpdateFromModel();
}
this.Disposed += OnDisposed;
}
private void OnDisposed(object sender, EventArgs e)
{
if (_model != null)
_model.SelectionChanged -= ModelSelectionChanged;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
// single column occupies whole list, leaving room for vertical scroll so we don't get a spurious
// horizontal one.
_keyboards.Width = _possibleKeyboardsList.ClientSize.Width - SystemInformation.VerticalScrollBarWidth;
}
private Color _unavailableColor = Color.FromKnownColor(KnownColor.DimGray);
private Color _labelColor = Color.LightCyan;
private ListViewItem MakeLabelItem(string text)
{
var label1 = new ListViewItem(text);
label1.BackColor = _labelColor;
label1.Font = new Font(_possibleKeyboardsList.Font, FontStyle.Bold);
return label1;
}
private bool IsItemLabel(ListViewItem item)
{
return item.BackColor == _labelColor;
}
private void PopulateKeyboardList()
{
if (_model == null || !_model.HasCurrentSelection)
{
_possibleKeyboardsList.Items.Clear();
return;
}
_possibleKeyboardsList.BeginUpdate();
Rectangle originalBounds = _possibleKeyboardsList.Bounds;
_possibleKeyboardsList.Items.Clear();
_possibleKeyboardsList.Items.Add(MakeLabelItem(
LocalizationManager.GetString("WSKeyboardControl.KeyboardsPreviouslyUsed", "Previously used keyboards")));
var unavailableFont = new Font(_possibleKeyboardsList.Font, FontStyle.Italic);
foreach (var keyboard in _model.KnownKeyboards)
{
var adapter = new KeyboardDefinitionAdapter(keyboard);
var item = new ListViewItem(adapter.ToString());
item.Tag = adapter;
if (!keyboard.IsAvailable)
{
item.Font = unavailableFont;
item.ForeColor = _unavailableColor;
}
item.ToolTipText = adapter.ToString();
_possibleKeyboardsList.Items.Add(item);
if (keyboard == _model.CurrentKeyboard)
item.Selected = true;
}
_possibleKeyboardsList.Items.Add(MakeLabelItem(
LocalizationManager.GetString("WSKeyboardControl.KeyboardsAvailable", "Available keyboards")));
foreach (var keyboard in _model.OtherAvailableKeyboards)
{
var adapter = new KeyboardDefinitionAdapter(keyboard);
var item = new ListViewItem(adapter.ToString());
item.Tag = adapter;
item.ToolTipText = adapter.ToString();
_possibleKeyboardsList.Items.Add(item);
}
_possibleKeyboardsList.Bounds = originalBounds;
_possibleKeyboardsList.EndUpdate();
}
private void ModelCurrentItemUpdated(object sender, EventArgs e)
{
UpdateFromModel();
}
private void ModelSelectionChanged(object sender, EventArgs e)
{
PopulateKeyboardList(); // different writing system may have different current ones.
UpdateFromModel();
}
private string _selectKeyboardPattern;
private void UpdateFromModel()
{
if (_model == null || !_model.HasCurrentSelection)
{
Enabled = false;
_selectKeyboardLabel.Visible = false;
return;
}
Enabled = true;
_selectKeyboardLabel.Visible = true;
if (_selectKeyboardPattern == null)
_selectKeyboardPattern = _selectKeyboardLabel.Text;
_selectKeyboardLabel.Text = string.Format(_selectKeyboardPattern, _model.CurrentDefinition.ListLabel);
KeyboardDefinitionAdapter currentKeyboardDefinition = null;
if (_possibleKeyboardsList.SelectedItems.Count > 0)
currentKeyboardDefinition = _possibleKeyboardsList.SelectedItems[0].Tag as KeyboardDefinitionAdapter;
if (_model.CurrentKeyboard != null &&
(currentKeyboardDefinition == null || _model.CurrentKeyboard.Layout != currentKeyboardDefinition.Layout
|| _model.CurrentKeyboard.Locale != currentKeyboardDefinition.Locale))
{
foreach (ListViewItem item in _possibleKeyboardsList.Items)
{
var keyboard = item.Tag as KeyboardDefinitionAdapter;
if (keyboard != null && keyboard.Layout == _model.CurrentKeyboard.Layout
&& keyboard.Locale == _model.CurrentKeyboard.Locale)
{
//_possibleKeyboardsList.SelectedItems.Clear();
// We're updating the display from the model, so we don't need to run the code that
// updates the model from the display.
_possibleKeyboardsList.SelectedIndexChanged -= _possibleKeyboardsList_SelectedIndexChanged;
item.Selected = true; // single select is true, so should clear any old one.
_possibleKeyboardsList.SelectedIndexChanged += _possibleKeyboardsList_SelectedIndexChanged;
break;
}
}
}
SetTestAreaFont();
}
private void SetTestAreaFont()
{
float fontSize = _model.CurrentDefaultFontSize;
if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize))
{
fontSize = _defaultFontSize;
}
string fontName = _model.CurrentDefaultFontName;
if (string.IsNullOrEmpty(fontName))
{
fontName = _defaultFontName;
}
_testArea.Font = new Font(fontName, fontSize);
_testArea.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No;
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
_possibleKeyboardsList.Focus(); // allows the user to use arrows to select, also makes selection more conspicuous
}
private string _previousKeyboard;
private int _previousTime;
private void _possibleKeyboardsList_SelectedIndexChanged(object sender, EventArgs e)
{
if (_possibleKeyboardsList.SelectedItems.Count != 0)
{
var item = _possibleKeyboardsList.SelectedItems[0];
if (IsItemLabel(item) || item.ForeColor == _unavailableColor)
{
item.Selected = false;
UpdateFromModel(); // back to whatever the model has
return;
}
}
if (Environment.TickCount - _previousTime < 1000 && _possibleKeyboardsList.SelectedItems.Count == 0)
{
_previousTime = Environment.TickCount;
}
_previousTime = Environment.TickCount;
if (_model == null)
{
return;
}
if (_possibleKeyboardsList.SelectedItems.Count != 0)
{
var currentKeyboard = _possibleKeyboardsList.SelectedItems[0].Tag as KeyboardDefinitionAdapter;
if (_model.CurrentKeyboard == null ||
_model.CurrentKeyboard.Layout != currentKeyboard.Layout ||
_model.CurrentKeyboard.Locale != currentKeyboard.Locale)
{
_model.CurrentKeyboard = Keyboard.Controller.CreateKeyboardDefinition(currentKeyboard.Layout,
currentKeyboard.Locale);
}
}
}
private void _testArea_Enter(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
_model.ActivateCurrentKeyboard();
SetTestAreaFont();
}
private void _testArea_Leave(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
Keyboard.Controller.ActivateDefaultKeyboard();
}
private void _windowsKeyboardSettingsLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string program = null;
string arguments = null;
#if MONO
// Try for the most likely keyboard setup programs. If none found,
// inform the user.
if (KeyboardController.CombinedKeyboardHandling)
{
if (File.Exists("/usr/bin/unity-control-center"))
{
program = "/usr/bin/unity-control-center";
arguments = "region layouts";
}
else if (File.Exists("/usr/bin/gnome-control-center"))
{
program = "/usr/bin/gnome-control-center";
arguments = "region layouts";
}
}
else
{
if (File.Exists("/usr/bin/ibus-setup"))
program = "/usr/bin/ibus-setup";
}
if (String.IsNullOrEmpty(program))
{
MessageBox.Show("Cannot open keyboard setup program", "Information");
return;
}
#else
program = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System), @"control.exe");
arguments = @"input.dll";
#endif
var processInfo = new ProcessStartInfo(program, arguments);
using (Process.Start(processInfo))
{
}
}
private void _keymanConfigurationLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
int version = 0;
string keymanPath = GetKeymanRegistryValue(@"root path", ref version);
if (keymanPath != null)
{
string keyman = Path.Combine(keymanPath, @"kmshell.exe");
if (File.Exists(keyman))
{
// From Marc Durdin (7/16/09):
// Re LT-9902, in Keyman 6, you could launch the configuration dialog reliably by running kmshell.exe.
// However, Keyman 7 works slightly differently. The recommended approach is to use the COM API:
// http://www.tavultesoft.com/keymandev/documentation/70/comapi_interface_IKeymanProduct_OpenConfiguration.html
// Sample code:
// dim kmcom, product
// Set kmcom = CreateObject("kmcomapi.TavultesoftKeyman")
// rem Pro = ProductID 1; Light = ProductID 8
// rem Following line will raise exception if product is not installed, so try/catch it
// Set product = kmcom.Products.ItemsByProductID(1)
// Product.OpenConfiguration
// But if that is not going to be workable for you, then use the parameter "-c" to start configuration.
// Without a parameter, the action is to start Keyman Desktop itself; v7.0 would fire configuration if restarted,
// v7.1 just flags to the user that Keyman is running and where to find it. This change was due to feedback that
// users would repeatedly try to start Keyman when it was already running, and get confused when they got the
// Configuration dialog. Sorry for the unannounced change... 9
// The -c parameter will not work with Keyman 6, so you would need to test for the specific version. For what it's worth, the
// COM API is static and should not change, while the command line parameters are not guaranteed to change from version to version.
string param = @"";
if (version > 6)
param = @"-c";
using (Process.Start(keyman, param))
{
return;
}
}
}
MessageBox.Show(LocalizationManager.GetString("WSKeyboardControl.KeymanNotInstalled", "Keyman 5.0 or later is not Installed."));
}
/// <summary>
/// This method returns the path to Keyman Configuration if it is installed. Otherwise it returns null.
/// It also sets the version of Keyman that it found.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="version">The version.</param>
/// <returns></returns>
private static string GetKeymanRegistryValue(string key, ref int version)
{
using (var rkKeyman = Registry.LocalMachine.OpenSubKey(@"Software\Tavultesoft\Keyman", false))
{
if (rkKeyman == null)
return null;
//May 2008 version 7.0 is the lastest version. The others are here for
//future versions.
int[] versions = {10, 9, 8, 7, 6, 5};
foreach (int vers in versions)
{
using (var rkApplication = rkKeyman.OpenSubKey(vers + @".0", false))
{
if (rkApplication != null)
{
foreach (string sKey in rkApplication.GetValueNames())
{
if (sKey == key)
{
version = vers;
return (string) rkApplication.GetValue(sKey);
}
}
}
}
}
}
return null;
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Types;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CSharp
{
public class CSharpMarshalContext : MarshalContext
{
public CSharpMarshalContext(BindingContext context)
: base(context)
{
ArgumentPrefix = new TextGenerator();
Cleanup = new TextGenerator();
}
public TextGenerator ArgumentPrefix { get; private set; }
public TextGenerator Cleanup { get; private set; }
public bool HasCodeBlock { get; set; }
}
public abstract class CSharpMarshalPrinter : MarshalPrinter<CSharpMarshalContext>
{
protected CSharpMarshalPrinter(CSharpMarshalContext context)
: base(context)
{
VisitOptions.VisitFunctionParameters = false;
VisitOptions.VisitTemplateArguments = false;
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
}
public class CSharpMarshalNativeToManagedPrinter : CSharpMarshalPrinter
{
public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context)
: base(context)
{
typePrinter = new CSharpTypePrinter(context.Context);
}
public bool MarshalsParameter { get; set; }
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = type;
typeMap.CSharpMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Declaration = decl;
typeMap.CSharpMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (Context.MarshalKind != MarshalKind.NativeField &&
Context.MarshalKind != MarshalKind.ReturnVariableArray)
goto case ArrayType.ArraySize.Incomplete;
var supportBefore = Context.Before;
string value = Generator.GeneratedIdentifier("value");
var arrayType = array.Type.Desugar();
supportBefore.WriteLine($"{arrayType}[] {value} = null;");
supportBefore.WriteLine($"if ({Context.ReturnVarName} != null)");
supportBefore.WriteStartBraceIndent();
supportBefore.WriteLine($"{value} = new {arrayType}[{array.Size}];");
supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
supportBefore.WriteLineIndent($@"{value}[i] = new global::System.IntPtr({
Context.ReturnVarName}[i]);");
else
{
var finalArrayType = arrayType.GetPointee() ?? arrayType;
Class @class;
if ((finalArrayType.TryGetClass(out @class)) && @class.IsRefType)
{
if (arrayType == finalArrayType)
supportBefore.WriteLineIndent(
"{0}[i] = {1}.{2}(*(({1}.{3}*)&({4}[i * sizeof({1}.{3})])));",
value, array.Type, Helpers.CreateInstanceIdentifier,
Helpers.InternalStruct, Context.ReturnVarName);
else
supportBefore.WriteLineIndent(
$@"{value}[i] = {finalArrayType}.{Helpers.CreateInstanceIdentifier}(({
CSharpTypePrinter.IntPtrType}) {Context.ReturnVarName}[i]);");
}
else
{
if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
supportBefore.WriteLineIndent($@"{value}[i] = {
Context.ReturnVarName}[i] != 0;");
else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{value}[i] = global::System.Convert.ToChar({
Context.ReturnVarName}[i]);");
else
supportBefore.WriteLineIndent($@"{value}[i] = {
Context.ReturnVarName}[i];");
}
}
supportBefore.WriteCloseBraceIndent();
Context.Return.Write(value);
break;
case ArrayType.ArraySize.Incomplete:
// const char* and const char[] are the same so we can use a string
if (array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
array.QualifiedType.Qualifiers.IsConst)
return VisitPointerType(new PointerType
{
QualifiedPointee = array.QualifiedType
}, quals);
MarshalArray(array);
break;
case ArrayType.ArraySize.Variable:
Context.Return.Write(Context.ReturnVarName);
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
var pointee = pointer.Pointee.Desugar();
bool marshalPointeeAsString = CSharpTypePrinter.IsConstCharString(pointee) && isRefParam;
if ((CSharpTypePrinter.IsConstCharString(pointer) && !MarshalsParameter) ||
marshalPointeeAsString)
{
Context.Return.Write(MarshalStringToManaged(Context.ReturnVarName,
pointer.GetFinalPointee().Desugar() as BuiltinType));
return true;
}
var finalPointee = pointer.GetFinalPointee();
PrimitiveType primitive;
if (finalPointee.IsPrimitiveType(out primitive) || finalPointee.IsEnumType())
{
if (isRefParam)
{
Context.Return.Write("_{0}", param.Name);
return true;
}
if (Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
Context.Return.Write($"({pointer}) ");
var type = Context.ReturnType.Type.Desugar(
resolveTemplateSubstitution: false);
if (Context.Function != null &&
Context.Function.OperatorKind == CXXOperatorKind.Subscript)
{
if (type.IsPrimitiveType(primitive))
{
Context.Return.Write("*");
}
else
{
var templateParameter = type as TemplateParameterType;
if (templateParameter != null)
Context.Return.Write($@"({templateParameter.Parameter.Name}) (object) *");
}
}
Context.Return.Write(Context.ReturnVarName);
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
private string MarshalStringToManaged(string varName, BuiltinType type)
{
var isChar = type.Type == PrimitiveType.Char;
var encoding = isChar ? Encoding.ASCII : Encoding.Unicode;
if (Equals(encoding, Encoding.ASCII))
encoding = Context.Context.Options.Encoding;
if (Equals(encoding, Encoding.ASCII))
return $"Marshal.PtrToStringAnsi({varName})";
if (Equals(encoding, Encoding.UTF8))
return $"Marshal.PtrToStringUTF8({varName})";
// If we reach this, we know the string is Unicode.
if (type.Type == PrimitiveType.Char ||
Context.Context.TargetInfo.WCharWidth == 16)
return $"Marshal.PtrToStringUni({varName})";
// If we reach this, we should have an UTF-32 wide string.
const string encodingName = "System.Text.Encoding.UTF32";
return $"CppSharp.Runtime.Helpers.MarshalEncodedString({varName}, {encodingName})";
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write("global::System.Convert.ToChar({0})",
Context.ReturnVarName);
return true;
}
goto default;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("{0} != 0", Context.ReturnVarName);
return true;
}
goto default;
default:
Context.Return.Write(Context.ReturnVarName);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!VisitType(typedef, quals))
return false;
var decl = typedef.Declaration;
var functionType = decl.Type as FunctionType;
if (functionType != null || decl.Type.IsPointerTo(out functionType))
{
var ptrName = $"{Generator.GeneratedIdentifier("ptr")}{Context.ParameterIndex}";
Context.Before.WriteLine($"var {ptrName} = {Context.ReturnVarName};");
var specialization = decl.Namespace as ClassTemplateSpecialization;
Type returnType = Context.ReturnType.Type.Desugar();
var finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
var res = string.Format(
"{0} == IntPtr.Zero? null : {1}({2}) Marshal.GetDelegateForFunctionPointer({0}, typeof({2}))",
ptrName,
finalType.IsDependent ? $@"({specialization.TemplatedDecl.TemplatedClass.Typedefs.First(
t => t.Name == decl.Name).Visit(this.typePrinter)}) (object) " : string.Empty,
typedef);
Context.Return.Write(res);
return true;
}
return decl.Type.Visit(this);
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex;
Context.Before.WriteLine("var {0} = {1};", ptrName,
Context.ReturnVarName);
Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
ptrName, function.ToString());
return true;
}
public override bool VisitClassDecl(Class @class)
{
var originalClass = @class.OriginalClass ?? @class;
Type returnType = Context.ReturnType.Type.Desugar();
// if the class is an abstract impl, use the original for the object map
var qualifiedClass = originalClass.Visit(typePrinter);
var finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
Class returnedClass;
if (finalType.TryGetClass(out returnedClass) && returnedClass.IsDependent)
Context.Return.Write($"({returnType.Visit(typePrinter)}) (object) ");
if (returnType.IsAddress())
Context.Return.Write(HandleReturnedPointer(@class, qualifiedClass.Type));
else
Context.Return.Write($"{qualifiedClass}.{Helpers.CreateInstanceIdentifier}({Context.ReturnVarName})");
return true;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("{0}", Context.ReturnVarName);
return true;
}
public override bool VisitParameterDecl(Parameter parameter)
{
if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn)
return base.VisitParameterDecl(parameter);
var ctx = new CSharpMarshalContext(Context.Context)
{
ReturnType = Context.ReturnType,
ReturnVarName = Context.ReturnVarName
};
var marshal = new CSharpMarshalNativeToManagedPrinter(ctx);
parameter.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(ctx.Before))
Context.Before.WriteLine(ctx.Before);
if (!string.IsNullOrWhiteSpace(ctx.Return) &&
!parameter.Type.IsPrimitiveTypeConvertibleToRef())
{
Context.Before.WriteLine("var _{0} = {1};", parameter.Name,
ctx.Return);
}
Context.Return.Write("{0}{1}",
parameter.Type.IsPrimitiveTypeConvertibleToRef() ? "ref *" : "_", parameter.Name);
return true;
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
Type returnType = Context.ReturnType.Type.Desugar();
Type finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
if (finalType.IsDependent)
Context.Return.Write($"({param.ReplacedParameter.Parameter.Name}) (object) ");
if (param.Replacement.Type.Desugar().IsPointerToPrimitiveType())
Context.Return.Write($"({CSharpTypePrinter.IntPtrType}) ");
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
private string HandleReturnedPointer(Class @class, string qualifiedClass)
{
var originalClass = @class.OriginalClass ?? @class;
var ret = Generator.GeneratedIdentifier("result") + Context.ParameterIndex;
var qualifiedIdentifier = @class.Visit(typePrinter);
Context.Before.WriteLine("{0} {1};", qualifiedIdentifier, ret);
Context.Before.WriteLine("if ({0} == IntPtr.Zero) {1} = {2};", Context.ReturnVarName, ret,
originalClass.IsRefType ? "null" : string.Format("new {0}()", qualifiedClass));
if (originalClass.IsRefType)
{
Context.Before.WriteLine(
"else if ({0}.NativeToManagedMap.ContainsKey({1}))", qualifiedClass, Context.ReturnVarName);
Context.Before.WriteLineIndent("{0} = ({1}) {2}.NativeToManagedMap[{3}];",
ret, qualifiedIdentifier, qualifiedClass, Context.ReturnVarName);
var dtor = originalClass.Destructors.FirstOrDefault();
if (dtor != null && dtor.IsVirtual)
{
Context.Before.WriteLine("else {0}{1} = ({2}) {3}.{4}({5}{6});",
MarshalsParameter
? string.Empty
: string.Format("{0}.NativeToManagedMap[{1}] = ", qualifiedClass, Context.ReturnVarName),
ret, qualifiedIdentifier, qualifiedClass, Helpers.CreateInstanceIdentifier, Context.ReturnVarName,
MarshalsParameter ? ", skipVTables: true" : string.Empty);
}
else
{
Context.Before.WriteLine("else {0} = {1}.{2}({3});", ret, qualifiedClass,
Helpers.CreateInstanceIdentifier, Context.ReturnVarName);
}
}
else
{
Context.Before.WriteLine("else {0} = {1}.{2}({3});", ret, qualifiedClass,
Helpers.CreateInstanceIdentifier, Context.ReturnVarName);
}
return ret;
}
private void MarshalArray(ArrayType array)
{
Type arrayType = array.Type.Desugar();
if (arrayType.IsPrimitiveType() ||
arrayType.IsPointerToPrimitiveType() ||
Context.MarshalKind != MarshalKind.GenericDelegate)
{
Context.Return.Write(Context.ReturnVarName);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.ReturnVarName);
var intermediateArrayType = arrayType.Visit(typePrinter);
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if (ReferenceEquals({Context.ReturnVarName}, null))");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteStartBraceIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.ReturnVarName}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
if (arrayType.IsAddress())
{
Context.Before.WriteStartBraceIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.ReturnVarName}[i];");
var intPtrZero = $"{CSharpTypePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = {element} == {
intPtrZero} ? null : {intermediateArrayType}.{
Helpers.CreateInstanceIdentifier}({element});");
Context.Before.WriteCloseBraceIndent();
}
else
Context.Before.WriteLineIndent($@"{intermediateArray}[i] = {
intermediateArrayType}.{Helpers.CreateInstanceIdentifier}({
Context.ReturnVarName}[i]);");
Context.Before.WriteCloseBraceIndent();
Context.Return.Write(intermediateArray);
}
private readonly CSharpTypePrinter typePrinter;
}
public class CSharpMarshalManagedToNativePrinter : CSharpMarshalPrinter
{
public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context)
: base(context)
{
typePrinter = new CSharpTypePrinter(context.Context);
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Type = type;
typeMap.CSharpMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.Declaration = decl;
typeMap.CSharpMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (string.IsNullOrEmpty(Context.ReturnVarName))
goto case ArrayType.ArraySize.Incomplete;
var supportBefore = Context.Before;
supportBefore.WriteLine($"if ({Context.ArgName} != null)");
supportBefore.WriteStartBraceIndent();
Class @class;
var arrayType = array.Type.Desugar();
var finalArrayType = arrayType.GetPointee() ?? arrayType;
if (finalArrayType.TryGetClass(out @class) && @class.IsRefType)
{
supportBefore.WriteLine($"if (value.Length != {array.Size})");
ThrowArgumentOutOfRangeException();
}
supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
if (@class != null && @class.IsRefType)
{
if (finalArrayType == arrayType)
supportBefore.WriteLineIndent(
"*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};",
Context.ReturnVarName, arrayType, Helpers.InternalStruct,
Context.ArgName, Helpers.InstanceIdentifier);
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = ({
(Context.Context.TargetInfo.PointerWidth == 64 ? "long" : "int")}) {
Context.ArgName}[i].{Helpers.InstanceIdentifier};");
}
else
{
if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = (byte)({
Context.ArgName}[i] ? 1 : 0);");
else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = global::System.Convert.ToSByte({
Context.ArgName}[i]);");
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = {
Context.ArgName}[i]{
(arrayType.IsPointerToPrimitiveType(PrimitiveType.Void) ?
".ToPointer()" : string.Empty)};");
}
supportBefore.WriteCloseBraceIndent();
break;
case ArrayType.ArraySize.Incomplete:
MarshalArray(array);
break;
default:
Context.Return.Write("null");
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var templateSubstitution = pointer.Pointee as TemplateParameterSubstitutionType;
PointerType realPointer = null;
if (templateSubstitution != null)
realPointer = templateSubstitution.Replacement.Type.Desugar() as PointerType;
realPointer = realPointer ?? pointer;
var pointee = pointer.Pointee.Desugar();
if (Context.Function != null &&
(realPointer.IsPrimitiveTypeConvertibleToRef() ||
(templateSubstitution != null && realPointer.Pointee.IsEnumType())) &&
Context.MarshalKind != MarshalKind.VTableReturnValue)
{
var refParamPtr = $"__refParamPtr{Context.ParameterIndex}";
if (templateSubstitution != null)
{
var castParam = $"__{Context.Parameter.Name}{Context.ParameterIndex}";
Context.Before.Write($"var {castParam} = ({templateSubstitution}) ");
if (realPointer != pointer)
Context.Before.Write($"({CSharpTypePrinter.IntPtrType}) ");
Context.Before.WriteLine($"(object) {Context.Parameter.Name};");
Context.Before.Write($"var {refParamPtr} = ");
if (realPointer == pointer)
Context.Before.Write("&");
Context.Before.WriteLine($"{castParam};");
Context.Return.Write(refParamPtr);
return true;
}
if (Context.Function.OperatorKind != CXXOperatorKind.Subscript)
{
if (Context.Parameter.Kind == ParameterKind.PropertyValue)
{
Context.Return.Write($"&{Context.Parameter.Name}");
}
else
{
Context.Before.WriteLine(
$"fixed ({realPointer} {refParamPtr} = &{Context.Parameter.Name})");
Context.HasCodeBlock = true;
Context.Before.WriteStartBraceIndent();
Context.Return.Write(refParamPtr);
}
return true;
}
}
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
if (CSharpTypePrinter.IsConstCharString(pointee) && isRefParam)
{
if (param.IsOut)
{
Context.Return.Write("IntPtr.Zero");
Context.ArgumentPrefix.Write("&");
}
else if (param.IsInOut)
{
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
Context.ArgumentPrefix.Write("&");
}
else
{
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
Context.Cleanup.WriteLine("Marshal.FreeHGlobal({0});", Context.ArgName);
}
return true;
}
if (pointee is FunctionType)
return VisitDelegateType();
Class @class;
if (pointee.TryGetClass(out @class) && @class.IsValueType)
{
if (Context.Parameter.Usage == ParameterUsage.Out)
{
var qualifiedIdentifier = (@class.OriginalClass ?? @class).Visit(typePrinter);
Context.Before.WriteLine("var {0} = new {1}.{2}();",
Generator.GeneratedIdentifier(Context.ArgName), qualifiedIdentifier,
Helpers.InternalStruct);
}
else
{
Context.Before.WriteLine("var {0} = {1}.{2};",
Generator.GeneratedIdentifier(Context.ArgName),
Context.Parameter.Name,
Helpers.InstanceIdentifier);
}
Context.Return.Write("new global::System.IntPtr(&{0})",
Generator.GeneratedIdentifier(Context.ArgName));
return true;
}
var marshalAsString = CSharpTypePrinter.IsConstCharString(pointer);
var finalPointee = pointer.GetFinalPointee();
PrimitiveType primitive;
if (finalPointee.IsPrimitiveType(out primitive) || finalPointee.IsEnumType() ||
marshalAsString)
{
// From MSDN: "note that a ref or out parameter is classified as a moveable
// variable". This means we must create a local variable to hold the result
// and then assign this value to the parameter.
if (isRefParam)
{
var typeName = Type.TypePrinterDelegate(finalPointee);
if (Context.Function.OperatorKind == CXXOperatorKind.Subscript)
Context.Return.Write(param.Name);
else
{
if (param.IsInOut)
Context.Before.WriteLine($"{typeName} _{param.Name} = {param.Name};");
else
Context.Before.WriteLine($"{typeName} _{param.Name};");
Context.Return.Write($"&_{param.Name}");
}
}
else
{
if (!marshalAsString &&
Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
Context.Return.Write($"({typePrinter.PrintNative(pointer)}) ");
if (marshalAsString && (Context.MarshalKind == MarshalKind.NativeField ||
Context.MarshalKind == MarshalKind.VTableReturnValue ||
Context.MarshalKind == MarshalKind.Variable))
Context.Return.Write(MarshalStringToUnmanaged(Context.Parameter.Name));
else
Context.Return.Write(Context.Parameter.Name);
}
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
private string MarshalStringToUnmanaged(string varName)
{
if (Equals(Context.Context.Options.Encoding, Encoding.ASCII))
{
return string.Format("Marshal.StringToHGlobalAnsi({0})", varName);
}
if (Equals(Context.Context.Options.Encoding, Encoding.Unicode) ||
Equals(Context.Context.Options.Encoding, Encoding.BigEndianUnicode))
{
return string.Format("Marshal.StringToHGlobalUni({0})", varName);
}
throw new NotSupportedException(string.Format("{0} is not supported yet.",
Context.Context.Options.Encoding.EncodingName));
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Char:
// returned structs must be blittable and char isn't
if (Context.Context.Options.MarshalCharAsManagedChar)
{
Context.Return.Write("global::System.Convert.ToSByte({0})",
Context.Parameter.Name);
return true;
}
goto default;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("(byte) ({0} ? 1 : 0)", Context.Parameter.Name);
return true;
}
goto default;
default:
Context.Return.Write(Context.Parameter.Name);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!VisitType(typedef, quals))
return false;
var decl = typedef.Declaration;
FunctionType func;
if (decl.Type.IsPointerTo(out func))
{
VisitDelegateType();
return true;
}
return decl.Type.Visit(this);
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
var replacement = param.Replacement.Type.Desugar();
Class @class;
if (!replacement.IsAddress() && !replacement.TryGetClass(out @class))
Context.Return.Write($"({replacement}) (object) ");
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
Context.Return.Write(param.Parameter.Name);
return true;
}
public override bool VisitClassDecl(Class @class)
{
if (!VisitDeclaration(@class))
return false;
if (@class.IsValueType)
{
MarshalValueClass();
}
else
{
MarshalRefClass(@class);
}
return true;
}
private void MarshalRefClass(Class @class)
{
var method = Context.Function as Method;
if (method != null
&& method.Conversion == MethodConversionKind.FunctionToInstanceMethod
&& Context.ParameterIndex == 0)
{
Context.Return.Write("{0}", Helpers.InstanceIdentifier);
return;
}
string param = Context.Parameter.Name;
Type type = Context.Parameter.Type.Desugar(resolveTemplateSubstitution: false);
string paramInstance;
Class @interface;
var finalType = type.GetFinalPointee() ?? type;
var templateType = finalType as TemplateParameterSubstitutionType;
type = Context.Parameter.Type.Desugar();
if (templateType != null)
param = $"(({@class.Visit(typePrinter)}) (object) {param})";
if (finalType.TryGetClass(out @interface) &&
@interface.IsInterface)
paramInstance = $"{param}.__PointerTo{@interface.OriginalClass.Name}";
else
paramInstance = $@"{param}.{Helpers.InstanceIdentifier}";
if (type.IsAddress())
{
Class decl;
if (type.TryGetClass(out decl) && decl.IsValueType)
Context.Return.Write(paramInstance);
else
{
if (type.IsPointer())
{
Context.Return.Write("{0}{1}",
method != null && method.OperatorKind == CXXOperatorKind.EqualEqual
? string.Empty
: $"ReferenceEquals({param}, null) ? global::System.IntPtr.Zero : ",
paramInstance);
}
else
{
if (method == null ||
// redundant for comparison operators, they are handled in a special way
(method.OperatorKind != CXXOperatorKind.EqualEqual &&
method.OperatorKind != CXXOperatorKind.ExclaimEqual))
{
Context.Before.WriteLine("if (ReferenceEquals({0}, null))", param);
Context.Before.WriteLineIndent(
"throw new global::System.ArgumentNullException(\"{0}\", " +
"\"Cannot be null because it is a C++ reference (&).\");",
param);
}
Context.Return.Write(paramInstance);
}
}
return;
}
var realClass = @class.OriginalClass ?? @class;
var qualifiedIdentifier = typePrinter.PrintNative(realClass);
Context.Return.Write(
"ReferenceEquals({0}, null) ? new {1}() : *({1}*) {2}",
param, qualifiedIdentifier, paramInstance);
}
private void MarshalValueClass()
{
Context.Return.Write("{0}.{1}", Context.Parameter.Name, Helpers.InstanceIdentifier);
}
public override bool VisitFieldDecl(Field field)
{
if (!VisitDeclaration(field))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType
};
return field.Type.Visit(this, field.QualifiedType.Qualifiers);
}
public override bool VisitProperty(Property property)
{
if (!VisitDeclaration(property))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
return base.VisitProperty(property);
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write(Context.Parameter.Name);
return true;
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return VisitClassDecl(template.TemplatedClass);
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
private bool VisitDelegateType()
{
Context.Return.Write("{0} == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate({0})",
Context.Parameter.Name);
return true;
}
private void ThrowArgumentOutOfRangeException()
{
Context.Before.WriteLineIndent(
"throw new ArgumentOutOfRangeException(\"{0}\", " +
"\"The dimensions of the provided array don't match the required size.\");",
Context.Parameter.Name);
}
private void MarshalArray(ArrayType arrayType)
{
if (arrayType.SizeType == ArrayType.ArraySize.Constant)
{
Context.Before.WriteLine("if ({0} == null || {0}.Length != {1})",
Context.Parameter.Name, arrayType.Size);
ThrowArgumentOutOfRangeException();
}
var elementType = arrayType.Type.Desugar();
if (elementType.IsPrimitiveType() ||
elementType.IsPointerToPrimitiveType())
{
Context.Return.Write(Context.Parameter.Name);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.Parameter.Name);
var intermediateArrayType = typePrinter.PrintNative(elementType);
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteStartBraceIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.Parameter.Name}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
Context.Before.WriteStartBraceIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.Parameter.Name}[i];");
if (elementType.IsAddress())
{
var intPtrZero = $"{CSharpTypePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = ReferenceEquals({
element}, null) ? {intPtrZero} : {element}.{Helpers.InstanceIdentifier};");
}
else
Context.Before.WriteLine($@"{intermediateArray}[i] = ReferenceEquals({
element}, null) ? new {intermediateArrayType}() : *({
intermediateArrayType}*) {element}.{Helpers.InstanceIdentifier};");
Context.Before.WriteCloseBraceIndent();
Context.Before.WriteCloseBraceIndent();
Context.Return.Write(intermediateArray);
}
private readonly CSharpTypePrinter typePrinter;
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using ReactBoilerplate.Controllers.Manage.Models;
using ReactBoilerplate.Models;
using ReactBoilerplate.Services;
using ReactBoilerplate.State;
using ReactBoilerplate.State.Manage;
namespace ReactBoilerplate.Controllers.Manage
{
[Authorize]
[Route("api/manage")]
public class ApiController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
public ApiController(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender)
: base(userManager, signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
}
[Route("security")]
public async Task<object> Security()
{
var user = await GetCurrentUserAsync();
return new
{
twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user),
validTwoFactorProviders = await _userManager.GetValidTwoFactorProvidersAsync(user),
emailConfirmed = await _userManager.IsEmailConfirmedAsync(user)
};
}
[Route("settwofactor")]
public async Task<object> SetTwoFactor([FromBody]SetTwoFactorModel model)
{
var user = await GetCurrentUserAsync();
if (await _userManager.GetTwoFactorEnabledAsync(user) == model.Enabled)
{
// already set
return new
{
success = true
};
}
await _userManager.SetTwoFactorEnabledAsync(user, model.Enabled);
return new
{
twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user),
success = true
};
}
[Route("email")]
public async Task<object> Email()
{
var user = await GetCurrentUserAsync();
return new
{
email = await _userManager.GetEmailAsync(user),
emailConfirmed = await _userManager.IsEmailConfirmedAsync(user)
};
}
[Route("changeemail")]
public async Task<object> ChangeEmail([FromBody]ChangeEmailModel model)
{
if (!ModelState.IsValid)
{
return new
{
success = false,
errors = GetModelState()
};
}
var user = await GetCurrentUserAsync();
if (!await _userManager.CheckPasswordAsync(user, model.CurrentPassword))
{
ModelState.AddModelError("currentPassword", "Invalid password.");
return new
{
success = false,
errors = GetModelState()
};
}
// send an email to the user asking them to finish the change of email.
var code = await _userManager.GenerateChangeEmailTokenAsync(user, model.Email);
var callbackUrl = Url.RouteUrl("confirmemail", new { userId = user.Id, newEmail = model.Email, code = code }, protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Confirm your email change", "Please confirm your new email by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
return new
{
success = true
};
}
[Route("verifyemail")]
public async Task<object> VerifyEmail()
{
var user = await GetCurrentUserAsync();
// send an email to the user asking them to finish the change of email.
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.RouteUrl("confirmemail", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(user.Email, "Confirm your email change", "Please confirm your new email by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
return new
{
success = true
};
}
[Route("changepassword")]
public async Task<object> ChangePassword([FromBody]ChangePasswordModel model)
{
if (!ModelState.IsValid)
{
return new
{
success = false,
errors = GetModelState()
};
}
var user = await GetCurrentUserAsync();
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return new
{
success = true
};
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return new
{
success = false,
errors = GetModelState()
};
}
[Route("externallogins")]
public async Task<object> ExternalLogins()
{
return new
{
success = true,
externalLogins = await GetExternalLoginsState()
};
}
[Route("addexternallogin")]
public async Task<object> AddExternalLogin()
{
var user = await GetCurrentUserAsync();
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return new
{
success = false,
externalLogins = await GetExternalLoginsState(),
errors = new List<string> { "Enable to authenticate with service." }
};
}
var result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
return new
{
success = true,
externalLogins = await GetExternalLoginsState()
};
}
return new
{
success = false,
externalLogins = await GetExternalLoginsState(),
errors = result.Errors.Select(x => x.Description)
};
}
[Route("removeexternallogin")]
public async Task<object> RemoveExternalLogin([FromBody]RemoveExternalLoginModel model)
{
var user = await GetCurrentUserAsync();
var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return new
{
success = true,
externalLogins = await GetExternalLoginsState()
};
}
return new
{
success = false,
error = result.Errors.Select(x => x.Description)
};
}
private async Task<ExternalLoginsState> GetExternalLoginsState()
{
var user = await GetCurrentUserAsync();
var userLogins = await _userManager.GetLoginsAsync(user);
var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync();
foreach (var userLogin in userLogins.Where(userLogin => string.IsNullOrEmpty(userLogin.ProviderDisplayName)))
{
userLogin.ProviderDisplayName =
schemes
.SingleOrDefault(x => x.Name.Equals(userLogin.LoginProvider))?
.DisplayName;
if (string.IsNullOrEmpty(userLogin.ProviderDisplayName))
{
userLogin.ProviderDisplayName = userLogin.LoginProvider;
}
}
var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList();
return new ExternalLoginsState
{
CurrentLogins = userLogins.Select(x => new ExternalLoginsState.ExternalLogin
{
ProviderKey = x.ProviderKey,
LoginProvider = x.LoginProvider,
LoginProviderDisplayName = x.ProviderDisplayName
}).ToList(),
OtherLogins = otherLogins.Select(x => new ExternalLoginState.ExternalLoginProvider
{
DisplayName = x.DisplayName,
Scheme = x.Name
}).ToList()
};
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.IO.Pipelines
{
/// <summary>
/// Default <see cref="PipeWriter"/> and <see cref="PipeReader"/> implementation.
/// </summary>
public sealed partial class Pipe
{
private const int SegmentPoolSize = 16;
private static readonly Action<object> s_signalReaderAwaitable = state => ((Pipe)state).ReaderCancellationRequested();
private static readonly Action<object> s_signalWriterAwaitable = state => ((Pipe)state).WriterCancellationRequested();
private static readonly Action<object> s_invokeCompletionCallbacks = state => ((PipeCompletionCallbacks)state).Execute();
// This sync objects protects the following state:
// 1. _commitHead & _commitHeadIndex
// 2. _length
// 3. _readerAwaitable & _writerAwaitable
private readonly object _sync = new object();
private readonly MemoryPool<byte> _pool;
private readonly int _minimumSegmentSize;
private readonly long _pauseWriterThreshold;
private readonly long _resumeWriterThreshold;
private readonly PipeScheduler _readerScheduler;
private readonly PipeScheduler _writerScheduler;
private readonly BufferSegment[] _bufferSegmentPool;
private readonly DefaultPipeReader _reader;
private readonly DefaultPipeWriter _writer;
private long _length;
private long _currentWriteLength;
private int _pooledSegmentCount;
private PipeAwaitable _readerAwaitable;
private PipeAwaitable _writerAwaitable;
private PipeCompletion _writerCompletion;
private PipeCompletion _readerCompletion;
// The read head which is the extent of the IPipelineReader's consumed bytes
private BufferSegment _readHead;
private int _readHeadIndex;
// The commit head which is the extent of the bytes available to the IPipelineReader to consume
private BufferSegment _commitHead;
private int _commitHeadIndex;
// The write head which is the extent of the IPipelineWriter's written bytes
private BufferSegment _writingHead;
private PipeReaderState _readingState;
private bool _disposed;
internal long Length => _length;
/// <summary>
/// Initializes the <see cref="Pipe"/> using <see cref="PipeOptions.Default"/> as options.
/// </summary>
public Pipe() : this(PipeOptions.Default)
{
}
/// <summary>
/// Initializes the <see cref="Pipe"/> with the specified <see cref="PipeOptions"/>.
/// </summary>
public Pipe(PipeOptions options)
{
if (options == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
}
_bufferSegmentPool = new BufferSegment[SegmentPoolSize];
_readingState = default;
_readerCompletion = default;
_writerCompletion = default;
_pool = options.Pool;
_minimumSegmentSize = options.MinimumSegmentSize;
_pauseWriterThreshold = options.PauseWriterThreshold;
_resumeWriterThreshold = options.ResumeWriterThreshold;
_readerScheduler = options.ReaderScheduler;
_writerScheduler = options.WriterScheduler;
_readerAwaitable = new PipeAwaitable(completed: false);
_writerAwaitable = new PipeAwaitable(completed: true);
_reader = new DefaultPipeReader(this);
_writer = new DefaultPipeWriter(this);
}
private void ResetState()
{
_readerCompletion.Reset();
_writerCompletion.Reset();
_commitHeadIndex = 0;
_currentWriteLength = 0;
_length = 0;
}
internal Memory<byte> GetMemory(int minimumSize)
{
if (_writerCompletion.IsCompleted)
{
ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
}
if (minimumSize < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumSize);
}
lock (_sync)
{
BufferSegment segment = _writingHead ?? AllocateWriteHeadUnsynchronized(minimumSize);
int bytesLeftInBuffer = segment.WritableBytes;
// If inadequate bytes left or if the segment is readonly
if (bytesLeftInBuffer == 0 || bytesLeftInBuffer < minimumSize || segment.ReadOnly)
{
BufferSegment nextSegment = CreateSegmentUnsynchronized();
nextSegment.SetMemory(_pool.Rent(Math.Max(_minimumSegmentSize, minimumSize)));
segment.SetNext(nextSegment);
_writingHead = nextSegment;
}
}
return _writingHead.AvailableMemory.Slice(_writingHead.End, _writingHead.WritableBytes);
}
private BufferSegment AllocateWriteHeadUnsynchronized(int count)
{
BufferSegment segment = null;
if (_commitHead != null && !_commitHead.ReadOnly)
{
// Try to return the tail so the calling code can append to it
int remaining = _commitHead.WritableBytes;
if (count <= remaining && remaining > 0)
{
// Free tail space of the right amount, use that
segment = _commitHead;
}
}
if (segment == null)
{
// No free tail space, allocate a new segment
segment = CreateSegmentUnsynchronized();
segment.SetMemory(_pool.Rent(Math.Max(_minimumSegmentSize, count)));
}
if (_commitHead == null)
{
// No previous writes have occurred
_commitHead = segment;
}
else if (segment != _commitHead && _commitHead.Next == null)
{
// Append the segment to the commit head if writes have been committed
// and it isn't the same segment (unused tail space)
_commitHead.SetNext(segment);
}
// Set write head to assigned segment
_writingHead = segment;
return segment;
}
private BufferSegment CreateSegmentUnsynchronized()
{
if (_pooledSegmentCount > 0)
{
_pooledSegmentCount--;
return _bufferSegmentPool[_pooledSegmentCount];
}
return new BufferSegment();
}
private void ReturnSegmentUnsynchronized(BufferSegment segment)
{
if (_pooledSegmentCount < _bufferSegmentPool.Length)
{
_bufferSegmentPool[_pooledSegmentCount] = segment;
_pooledSegmentCount++;
}
}
internal void CommitUnsynchronized()
{
if (_writingHead == null)
{
// Nothing written to commit
return;
}
if (_readHead == null)
{
// Update the head to point to the head of the buffer.
// This happens if we called alloc(0) then write
_readHead = _commitHead;
_readHeadIndex = 0;
}
// Always move the commit head to the write head
_commitHead = _writingHead;
_commitHeadIndex = _writingHead.End;
_length += _currentWriteLength;
// Do not reset if reader is complete
if (_pauseWriterThreshold > 0 &&
_length >= _pauseWriterThreshold &&
!_readerCompletion.IsCompleted)
{
_writerAwaitable.Reset();
}
// Clear the writing state
_writingHead = null;
_currentWriteLength = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Advance(int bytesWritten)
{
if (_writingHead == null)
{
ThrowHelper.ThrowInvalidOperationException_NotWritingNoAlloc();
}
if (bytesWritten > 0)
{
Debug.Assert(!_writingHead.ReadOnly);
Debug.Assert(_writingHead.Next == null);
Memory<byte> buffer = _writingHead.AvailableMemory;
if (_writingHead.End > buffer.Length - bytesWritten)
{
ThrowHelper.ThrowInvalidOperationException_AdvancingPastBufferSize();
}
_writingHead.End += bytesWritten;
_currentWriteLength += bytesWritten;
}
else if (bytesWritten < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytesWritten);
}
// and if zero, just do nothing; don't need to validate tail etc
}
internal PipeAwaiter<FlushResult> FlushAsync(CancellationToken cancellationToken)
{
Action awaitable;
CancellationTokenRegistration cancellationTokenRegistration;
lock (_sync)
{
if (_writingHead != null)
{
// Commit the data as not already committed
CommitUnsynchronized();
}
awaitable = _readerAwaitable.Complete();
cancellationTokenRegistration = _writerAwaitable.AttachToken(cancellationToken, s_signalWriterAwaitable, this);
}
cancellationTokenRegistration.Dispose();
TrySchedule(_readerScheduler, awaitable);
return new PipeAwaiter<FlushResult>(_writer);
}
internal void CompleteWriter(Exception exception)
{
Action awaitable;
PipeCompletionCallbacks completionCallbacks;
bool readerCompleted;
lock (_sync)
{
// Commit any pending buffers
CommitUnsynchronized();
completionCallbacks = _writerCompletion.TryComplete(exception);
awaitable = _readerAwaitable.Complete();
readerCompleted = _readerCompletion.IsCompleted;
}
if (completionCallbacks != null)
{
TrySchedule(_readerScheduler, s_invokeCompletionCallbacks, completionCallbacks);
}
TrySchedule(_readerScheduler, awaitable);
if (readerCompleted)
{
CompletePipe();
}
}
internal void AdvanceReader(SequencePosition consumed)
{
AdvanceReader(consumed, consumed);
}
internal void AdvanceReader(SequencePosition consumed, SequencePosition examined)
{
BufferSegment returnStart = null;
BufferSegment returnEnd = null;
Action continuation = null;
lock (_sync)
{
var examinedEverything = false;
if (examined.Segment == _commitHead)
{
examinedEverything = _commitHead != null ? examined.Index == _commitHeadIndex - _commitHead.Start : examined.Index == 0;
}
if (consumed.Segment != null)
{
if (_readHead == null)
{
ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
return;
}
var consumedSegment = (BufferSegment)consumed.Segment;
returnStart = _readHead;
returnEnd = consumedSegment;
// Check if we crossed _maximumSizeLow and complete backpressure
long consumedBytes = new ReadOnlySequence<byte>(returnStart, _readHeadIndex, consumedSegment, consumed.Index).Length;
long oldLength = _length;
_length -= consumedBytes;
if (oldLength >= _resumeWriterThreshold &&
_length < _resumeWriterThreshold)
{
continuation = _writerAwaitable.Complete();
}
// Check if we consumed entire last segment
// if we are going to return commit head we need to check that there is no writing operation that
// might be using tailspace
if (consumed.Index == returnEnd.Length && _writingHead != returnEnd)
{
BufferSegment nextBlock = returnEnd.NextSegment;
if (_commitHead == returnEnd)
{
_commitHead = nextBlock;
_commitHeadIndex = 0;
}
_readHead = nextBlock;
_readHeadIndex = 0;
returnEnd = nextBlock;
}
else
{
_readHead = consumedSegment;
_readHeadIndex = consumed.Index;
}
}
// We reset the awaitable to not completed if we've examined everything the producer produced so far
// but only if writer is not completed yet
if (examinedEverything && !_writerCompletion.IsCompleted)
{
// Prevent deadlock where reader awaits new data and writer await backpressure
if (!_writerAwaitable.IsCompleted)
{
ThrowHelper.ThrowInvalidOperationException_BackpressureDeadlock();
}
_readerAwaitable.Reset();
}
while (returnStart != null && returnStart != returnEnd)
{
returnStart.ResetMemory();
ReturnSegmentUnsynchronized(returnStart);
returnStart = returnStart.NextSegment;
}
_readingState.End();
}
TrySchedule(_writerScheduler, continuation);
}
internal void CompleteReader(Exception exception)
{
PipeCompletionCallbacks completionCallbacks;
Action awaitable;
bool writerCompleted;
lock (_sync)
{
if (_readingState.IsActive)
{
ThrowHelper.ThrowInvalidOperationException_CompleteReaderActiveReader();
}
completionCallbacks = _readerCompletion.TryComplete(exception);
awaitable = _writerAwaitable.Complete();
writerCompleted = _writerCompletion.IsCompleted;
}
if (completionCallbacks != null)
{
TrySchedule(_writerScheduler, s_invokeCompletionCallbacks, completionCallbacks);
}
TrySchedule(_writerScheduler, awaitable);
if (writerCompleted)
{
CompletePipe();
}
}
internal void OnWriterCompleted(Action<Exception, object> callback, object state)
{
if (callback == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
}
PipeCompletionCallbacks completionCallbacks;
lock (_sync)
{
completionCallbacks = _writerCompletion.AddCallback(callback, state);
}
if (completionCallbacks != null)
{
TrySchedule(_readerScheduler, s_invokeCompletionCallbacks, completionCallbacks);
}
}
internal void CancelPendingRead()
{
Action awaitable;
lock (_sync)
{
awaitable = _readerAwaitable.Cancel();
}
TrySchedule(_readerScheduler, awaitable);
}
internal void CancelPendingFlush()
{
Action awaitable;
lock (_sync)
{
awaitable = _writerAwaitable.Cancel();
}
TrySchedule(_writerScheduler, awaitable);
}
internal void OnReaderCompleted(Action<Exception, object> callback, object state)
{
if (callback == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
}
PipeCompletionCallbacks completionCallbacks;
lock (_sync)
{
completionCallbacks = _readerCompletion.AddCallback(callback, state);
}
if (completionCallbacks != null)
{
TrySchedule(_writerScheduler, s_invokeCompletionCallbacks, completionCallbacks);
}
}
internal PipeAwaiter<ReadResult> ReadAsync(CancellationToken token)
{
CancellationTokenRegistration cancellationTokenRegistration;
if (_readerCompletion.IsCompleted)
{
ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
}
lock (_sync)
{
cancellationTokenRegistration = _readerAwaitable.AttachToken(token, s_signalReaderAwaitable, this);
}
cancellationTokenRegistration.Dispose();
return new PipeAwaiter<ReadResult>(_reader);
}
internal bool TryRead(out ReadResult result)
{
lock (_sync)
{
if (_readerCompletion.IsCompleted)
{
ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
}
result = new ReadResult();
if (_length > 0 || _readerAwaitable.IsCompleted)
{
GetResult(ref result);
return true;
}
if (_readerAwaitable.HasContinuation)
{
ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
}
return false;
}
}
private static void TrySchedule(PipeScheduler scheduler, Action action)
{
if (action != null)
{
scheduler.Schedule(action);
}
}
private static void TrySchedule(PipeScheduler scheduler, Action<object> action, object state)
{
if (action != null)
{
scheduler.Schedule(action, state);
}
}
private void CompletePipe()
{
lock (_sync)
{
if (_disposed)
{
return;
}
_disposed = true;
// Return all segments
// if _readHead is null we need to try return _commitHead
// because there might be a block allocated for writing
BufferSegment segment = _readHead ?? _commitHead;
while (segment != null)
{
BufferSegment returnSegment = segment;
segment = segment.NextSegment;
returnSegment.ResetMemory();
}
_writingHead = null;
_readHead = null;
_commitHead = null;
}
}
internal bool IsReadAsyncCompleted => _readerAwaitable.IsCompleted;
internal void OnReadAsyncCompleted(Action continuation)
{
Action awaitable;
bool doubleCompletion;
lock (_sync)
{
awaitable = _readerAwaitable.OnCompleted(continuation, out doubleCompletion);
}
if (doubleCompletion)
{
Writer.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
}
TrySchedule(_readerScheduler, awaitable);
}
internal ReadResult GetReadAsyncResult()
{
if (!_readerAwaitable.IsCompleted)
{
ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
}
var result = new ReadResult();
lock (_sync)
{
GetResult(ref result);
}
return result;
}
private void GetResult(ref ReadResult result)
{
if (_writerCompletion.IsCompletedOrThrow())
{
result._resultFlags |= ResultFlags.Completed;
}
bool isCanceled = _readerAwaitable.ObserveCancelation();
if (isCanceled)
{
result._resultFlags |= ResultFlags.Canceled;
}
// No need to read end if there is no head
BufferSegment head = _readHead;
if (head != null)
{
// Reading commit head shared with writer
result._resultBuffer = new ReadOnlySequence<byte>(head, _readHeadIndex, _commitHead, _commitHeadIndex - _commitHead.Start);
}
if (isCanceled)
{
_readingState.BeginTentative();
}
else
{
_readingState.Begin();
}
}
internal bool IsFlushAsyncCompleted => _writerAwaitable.IsCompleted;
internal FlushResult GetFlushAsyncResult()
{
var result = new FlushResult();
lock (_sync)
{
if (!_writerAwaitable.IsCompleted)
{
ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
}
// Change the state from to be canceled -> observed
if (_writerAwaitable.ObserveCancelation())
{
result._resultFlags |= ResultFlags.Canceled;
}
if (_readerCompletion.IsCompletedOrThrow())
{
result._resultFlags |= ResultFlags.Completed;
}
}
return result;
}
internal void OnFlushAsyncCompleted(Action continuation)
{
Action awaitable;
bool doubleCompletion;
lock (_sync)
{
awaitable = _writerAwaitable.OnCompleted(continuation, out doubleCompletion);
}
if (doubleCompletion)
{
Reader.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
}
TrySchedule(_writerScheduler, awaitable);
}
private void ReaderCancellationRequested()
{
Action action;
lock (_sync)
{
action = _readerAwaitable.Cancel();
}
TrySchedule(_readerScheduler, action);
}
private void WriterCancellationRequested()
{
Action action;
lock (_sync)
{
action = _writerAwaitable.Cancel();
}
TrySchedule(_writerScheduler, action);
}
/// <summary>
/// Gets the <see cref="PipeReader"/> for this pipe.
/// </summary>
public PipeReader Reader => _reader;
/// <summary>
/// Gets the <see cref="PipeWriter"/> for this pipe.
/// </summary>
public PipeWriter Writer => _writer;
/// <summary>
/// Resets the pipe
/// </summary>
public void Reset()
{
lock (_sync)
{
if (!_disposed)
{
ThrowHelper.ThrowInvalidOperationException_ResetIncompleteReaderWriter();
}
_disposed = false;
ResetState();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureReport
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestReportServiceForAzure : ServiceClient<AutoRestReportServiceForAzure>, IAutoRestReportServiceForAzure, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestReportServiceForAzure(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestReportServiceForAzure(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestReportServiceForAzure(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestReportServiceForAzure(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestReportServiceForAzure class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestReportServiceForAzure(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Get test coverage report
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IDictionary<string, int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, int?>>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public partial class ZipFileTestBase : FileCleanupTestBase
{
public static string bad(string filename) => Path.Combine("ZipTestData", "badzipfiles", filename);
public static string compat(string filename) => Path.Combine("ZipTestData", "compat", filename);
public static string strange(string filename) => Path.Combine("ZipTestData", "StrangeZipFiles", filename);
public static string zfile(string filename) => Path.Combine("ZipTestData", "refzipfiles", filename);
public static string zfolder(string filename) => Path.Combine("ZipTestData", "refzipfolders", filename);
public static string zmodified(string filename) => Path.Combine("ZipTestData", "modified", filename);
protected TempFile CreateTempCopyFile(string path, string newPath)
{
TempFile newfile = new TempFile(newPath);
File.Copy(path, newPath, overwrite: true);
return newfile;
}
public static long LengthOfUnseekableStream(Stream s)
{
long totalBytes = 0;
const int bufSize = 4096;
byte[] buf = new byte[bufSize];
long bytesRead = 0;
do
{
bytesRead = s.Read(buf, 0, bufSize);
totalBytes += bytesRead;
} while (bytesRead > 0);
return totalBytes;
}
// reads exactly bytesToRead out of stream, unless it is out of bytes
public static void ReadBytes(Stream stream, byte[] buffer, long bytesToRead)
{
int bytesLeftToRead;
if (bytesToRead > int.MaxValue)
{
throw new NotImplementedException("64 bit addresses");
}
else
{
bytesLeftToRead = (int)bytesToRead;
}
int totalBytesRead = 0;
while (bytesLeftToRead > 0)
{
int bytesRead = stream.Read(buffer, totalBytesRead, bytesLeftToRead);
if (bytesRead == 0) throw new IOException("Unexpected end of stream");
totalBytesRead += bytesRead;
bytesLeftToRead -= bytesRead;
}
}
public static bool ArraysEqual<T>(T[] a, T[] b) where T : IComparable<T>
{
if (a.Length != b.Length) return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i].CompareTo(b[i]) != 0) return false;
}
return true;
}
public static bool ArraysEqual<T>(T[] a, T[] b, int length) where T : IComparable<T>
{
for (int i = 0; i < length; i++)
{
if (a[i].CompareTo(b[i]) != 0) return false;
}
return true;
}
public static void StreamsEqual(Stream ast, Stream bst)
{
StreamsEqual(ast, bst, -1);
}
public static void StreamsEqual(Stream ast, Stream bst, int blocksToRead)
{
if (ast.CanSeek)
ast.Seek(0, SeekOrigin.Begin);
if (bst.CanSeek)
bst.Seek(0, SeekOrigin.Begin);
const int bufSize = 4096;
byte[] ad = new byte[bufSize];
byte[] bd = new byte[bufSize];
int ac = 0;
int bc = 0;
int blocksRead = 0;
//assume read doesn't do weird things
do
{
if (blocksToRead != -1 && blocksRead >= blocksToRead)
break;
ac = ast.Read(ad, 0, 4096);
bc = bst.Read(bd, 0, 4096);
if (ac != bc)
{
bd = NormalizeLineEndings(bd);
}
Assert.True(ArraysEqual<byte>(ad, bd, ac), "Stream contents not equal: " + ast.ToString() + ", " + bst.ToString());
blocksRead++;
} while (ac == 4096);
}
public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode)
{
await IsZipSameAsDirAsync(archiveFile, directory, mode, requireExplicit: false, checkTimes: false);
}
public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes)
{
var s = await StreamHelpers.CreateTempCopyStream(archiveFile);
IsZipSameAsDir(s, directory, mode, requireExplicit, checkTimes);
}
public static byte[] NormalizeLineEndings(byte[] str)
{
string rep = Text.Encoding.Default.GetString(str);
rep = rep.Replace("\r\n", "\n");
rep = rep.Replace("\n", "\r\n");
return Text.Encoding.Default.GetBytes(rep);
}
public static void IsZipSameAsDir(Stream archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes)
{
int count = 0;
using (ZipArchive archive = new ZipArchive(archiveFile, mode))
{
List<FileData> files = FileData.InPath(directory);
Assert.All<FileData>(files, (file) => {
count++;
string entryName = file.FullName;
if (file.IsFolder)
entryName += Path.DirectorySeparatorChar;
ZipArchiveEntry entry = archive.GetEntry(entryName);
if (entry == null)
{
entryName = FlipSlashes(entryName);
entry = archive.GetEntry(entryName);
}
if (file.IsFile)
{
Assert.NotNull(entry);
long givenLength = entry.Length;
var buffer = new byte[entry.Length];
using (Stream entrystream = entry.Open())
{
entrystream.Read(buffer, 0, buffer.Length);
#if netcoreapp
uint zipcrc = entry.Crc32;
Assert.Equal(CRC.CalculateCRC(buffer), zipcrc.ToString());
#endif
if (file.Length != givenLength)
{
buffer = NormalizeLineEndings(buffer);
}
Assert.Equal(file.Length, buffer.Length);
string crc = CRC.CalculateCRC(buffer);
Assert.Equal(file.CRC, crc);
}
if (checkTimes)
{
const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records
DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution);
DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution);
Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks);
}
Assert.Equal(file.Name, entry.Name);
Assert.Equal(entryName, entry.FullName);
Assert.Equal(entryName, entry.ToString());
Assert.Equal(archive, entry.Archive);
}
else if (file.IsFolder)
{
if (entry == null) //entry not found
{
string entryNameOtherSlash = FlipSlashes(entryName);
bool isEmtpy = !files.Any(
f => f.IsFile &&
(f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) ||
f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase)));
if (requireExplicit || isEmtpy)
{
Assert.Contains("emptydir", entryName);
}
if ((!requireExplicit && !isEmtpy) || entryName.Contains("emptydir"))
count--; //discount this entry
}
else
{
using (Stream es = entry.Open())
{
try
{
Assert.Equal(0, es.Length);
}
catch (NotSupportedException)
{
try
{
Assert.Equal(-1, es.ReadByte());
}
catch (Exception)
{
Console.WriteLine("Didn't return EOF");
throw;
}
}
}
}
}
});
Assert.Equal(count, archive.Entries.Count);
}
}
private static string FlipSlashes(string name)
{
Debug.Assert(!(name.Contains("\\") && name.Contains("/")));
return
name.Contains("\\") ? name.Replace("\\", "/") :
name.Contains("/") ? name.Replace("/", "\\") :
name;
}
public static void DirsEqual(string actual, string expected)
{
var expectedList = FileData.InPath(expected);
var actualList = Directory.GetFiles(actual, "*.*", SearchOption.AllDirectories);
var actualFolders = Directory.GetDirectories(actual, "*.*", SearchOption.AllDirectories);
var actualCount = actualList.Length + actualFolders.Length;
Assert.Equal(expectedList.Count, actualCount);
ItemEqual(actualList, expectedList, isFile: true);
ItemEqual(actualFolders, expectedList, isFile: false);
}
public static void DirFileNamesEqual(string actual, string expected)
{
IEnumerable<string> actualEntries = Directory.EnumerateFileSystemEntries(actual, "*", SearchOption.AllDirectories);
IEnumerable<string> expectedEntries = Directory.EnumerateFileSystemEntries(expected, "*", SearchOption.AllDirectories);
Assert.True(Enumerable.SequenceEqual(expectedEntries.Select(i => Path.GetFileName(i)), actualEntries.Select(i => Path.GetFileName(i))));
}
private static void ItemEqual(string[] actualList, List<FileData> expectedList, bool isFile)
{
for (int i = 0; i < actualList.Length; i++)
{
var actualFile = actualList[i];
string aEntry = Path.GetFullPath(actualFile);
string aName = Path.GetFileName(aEntry);
var bData = expectedList.Where(f => string.Equals(f.Name, aName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
string bEntry = Path.GetFullPath(Path.Combine(bData.OrigFolder, bData.FullName));
string bName = Path.GetFileName(bEntry);
// expected 'emptydir' folder doesn't exist because MSBuild doesn't copy empty dir
if (!isFile && aName.Contains("emptydir") && bName.Contains("emptydir"))
continue;
//we want it to be false that one of them is a directory and the other isn't
Assert.False(Directory.Exists(aEntry) ^ Directory.Exists(bEntry), "Directory in one is file in other");
//contents same
if (isFile)
{
Stream sa = StreamHelpers.CreateTempCopyStream(aEntry).Result;
Stream sb = StreamHelpers.CreateTempCopyStream(bEntry).Result;
StreamsEqual(sa, sb);
}
}
}
/// <param name="useSpansForWriting">Tests the Span overloads of Write</param>
/// <param name="writeInChunks">Writes in chunks of 5 to test Write with a nonzero offset</param>
public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode, bool useSpansForWriting = false, bool writeInChunks = false)
{
var files = FileData.InPath(directory);
using (ZipArchive archive = new ZipArchive(archiveStream, mode, true))
{
foreach (var i in files)
{
if (i.IsFolder)
{
string entryName = i.FullName;
ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/");
e.LastWriteTime = i.LastModifiedDate;
}
}
foreach (var i in files)
{
if (i.IsFile)
{
string entryName = i.FullName;
var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName));
if (installStream != null)
{
ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/'));
e.LastWriteTime = i.LastModifiedDate;
using (Stream entryStream = e.Open())
{
int bytesRead;
var buffer = new byte[1024];
if (useSpansForWriting)
{
while ((bytesRead = installStream.Read(new Span<byte>(buffer))) != 0)
{
entryStream.Write(new ReadOnlySpan<byte>(buffer, 0, bytesRead));
}
}
else if (writeInChunks)
{
while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0)
{
for (int k = 0; k < bytesRead; k += 5)
entryStream.Write(buffer, k, Math.Min(5, bytesRead - k));
}
}
else
{
while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0)
{
entryStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
}
}
internal static void AddEntry(ZipArchive archive, string name, string contents, DateTimeOffset lastWrite)
{
ZipArchiveEntry e = archive.CreateEntry(name);
e.LastWriteTime = lastWrite;
using (StreamWriter w = new StreamWriter(e.Open()))
{
w.WriteLine(contents);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F02_Continent (editable child object).<br/>
/// This is a generated base class of <see cref="F02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="F03_SubContinentObjects"/> of type <see cref="F03_SubContinentColl"/> (1:M relation to <see cref="F04_SubContinent"/>)<br/>
/// This class is an item of <see cref="F01_ContinentColl"/> collection.
/// </remarks>
[Serializable]
public partial class F02_Continent : BusinessBase<F02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F03_Continent_Child> F03_Continent_SingleObjectProperty = RegisterProperty<F03_Continent_Child>(p => p.F03_Continent_SingleObject, "F03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F03 Continent Single Object ("parent load" child property).
/// </summary>
/// <value>The F03 Continent Single Object.</value>
public F03_Continent_Child F03_Continent_SingleObject
{
get { return GetProperty(F03_Continent_SingleObjectProperty); }
private set { LoadProperty(F03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F03_Continent_ReChild> F03_Continent_ASingleObjectProperty = RegisterProperty<F03_Continent_ReChild>(p => p.F03_Continent_ASingleObject, "F03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F03 Continent ASingle Object ("parent load" child property).
/// </summary>
/// <value>The F03 Continent ASingle Object.</value>
public F03_Continent_ReChild F03_Continent_ASingleObject
{
get { return GetProperty(F03_Continent_ASingleObjectProperty); }
private set { LoadProperty(F03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<F03_SubContinentColl> F03_SubContinentObjectsProperty = RegisterProperty<F03_SubContinentColl>(p => p.F03_SubContinentObjects, "F03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the F03 Sub Continent Objects ("parent load" child property).
/// </summary>
/// <value>The F03 Sub Continent Objects.</value>
public F03_SubContinentColl F03_SubContinentObjects
{
get { return GetProperty(F03_SubContinentObjectsProperty); }
private set { LoadProperty(F03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F02_Continent"/> object.</returns>
internal static F02_Continent NewF02_Continent()
{
return DataPortal.CreateChild<F02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="F02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F02_Continent"/> object.</returns>
internal static F02_Continent GetF02_Continent(SafeDataReader dr)
{
F02_Continent obj = new F02_Continent();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.LoadProperty(F03_SubContinentObjectsProperty, F03_SubContinentColl.NewF03_SubContinentColl());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F02_Continent()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(F03_Continent_SingleObjectProperty, DataPortal.CreateChild<F03_Continent_Child>());
LoadProperty(F03_Continent_ASingleObjectProperty, DataPortal.CreateChild<F03_Continent_ReChild>());
LoadProperty(F03_SubContinentObjectsProperty, DataPortal.CreateChild<F03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F02_Continent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID"));
LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
internal void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
while (dr.Read())
{
var child = F03_Continent_Child.GetF03_Continent_Child(dr);
var obj = ((F01_ContinentColl)Parent).FindF02_ContinentByParentProperties(child.continent_ID1);
obj.LoadProperty(F03_Continent_SingleObjectProperty, child);
}
dr.NextResult();
while (dr.Read())
{
var child = F03_Continent_ReChild.GetF03_Continent_ReChild(dr);
var obj = ((F01_ContinentColl)Parent).FindF02_ContinentByParentProperties(child.continent_ID2);
obj.LoadProperty(F03_Continent_ASingleObjectProperty, child);
}
dr.NextResult();
var f03_SubContinentColl = F03_SubContinentColl.GetF03_SubContinentColl(dr);
f03_SubContinentColl.LoadItems((F01_ContinentColl)Parent);
dr.NextResult();
while (dr.Read())
{
var child = F05_SubContinent_Child.GetF05_SubContinent_Child(dr);
var obj = f03_SubContinentColl.FindF04_SubContinentByParentProperties(child.subContinent_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = F05_SubContinent_ReChild.GetF05_SubContinent_ReChild(dr);
var obj = f03_SubContinentColl.FindF04_SubContinentByParentProperties(child.subContinent_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var f05_CountryColl = F05_CountryColl.GetF05_CountryColl(dr);
f05_CountryColl.LoadItems(f03_SubContinentColl);
dr.NextResult();
while (dr.Read())
{
var child = F07_Country_Child.GetF07_Country_Child(dr);
var obj = f05_CountryColl.FindF06_CountryByParentProperties(child.country_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = F07_Country_ReChild.GetF07_Country_ReChild(dr);
var obj = f05_CountryColl.FindF06_CountryByParentProperties(child.country_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var f07_RegionColl = F07_RegionColl.GetF07_RegionColl(dr);
f07_RegionColl.LoadItems(f05_CountryColl);
dr.NextResult();
while (dr.Read())
{
var child = F09_Region_Child.GetF09_Region_Child(dr);
var obj = f07_RegionColl.FindF08_RegionByParentProperties(child.region_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = F09_Region_ReChild.GetF09_Region_ReChild(dr);
var obj = f07_RegionColl.FindF08_RegionByParentProperties(child.region_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var f09_CityColl = F09_CityColl.GetF09_CityColl(dr);
f09_CityColl.LoadItems(f07_RegionColl);
dr.NextResult();
while (dr.Read())
{
var child = F11_City_Child.GetF11_City_Child(dr);
var obj = f09_CityColl.FindF10_CityByParentProperties(child.city_ID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = F11_City_ReChild.GetF11_City_ReChild(dr);
var obj = f09_CityColl.FindF10_CityByParentProperties(child.city_ID2);
obj.LoadChild(child);
}
dr.NextResult();
var f11_CityRoadColl = F11_CityRoadColl.GetF11_CityRoadColl(dr);
f11_CityRoadColl.LoadItems(f09_CityColl);
}
/// <summary>
/// Inserts a new <see cref="F02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddF02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateF02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="F02_Continent"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteF02_Continent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(F03_Continent_SingleObjectProperty, DataPortal.CreateChild<F03_Continent_Child>());
LoadProperty(F03_Continent_ASingleObjectProperty, DataPortal.CreateChild<F03_Continent_ReChild>());
LoadProperty(F03_SubContinentObjectsProperty, DataPortal.CreateChild<F03_SubContinentColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools.Interpreter {
/// <summary>
/// Provides access to an on-disk store of cached intellisense information.
/// </summary>
public sealed class PythonTypeDatabase : ITypeDatabaseReader {
private readonly PythonInterpreterFactoryWithDatabase _factory;
private readonly SharedDatabaseState _sharedState;
/// <summary>
/// Gets the version of the analysis format that this class reads.
/// </summary>
public static readonly int CurrentVersion = 25;
private static string _completionDatabasePath;
private static string _referencesDatabasePath;
private static string _baselineDatabasePath;
public PythonTypeDatabase(
PythonInterpreterFactoryWithDatabase factory,
IEnumerable<string> databaseDirectories = null,
PythonTypeDatabase innerDatabase = null
) {
if (innerDatabase != null && factory.Configuration.Version != innerDatabase.LanguageVersion) {
throw new InvalidOperationException("Language versions do not match");
}
_factory = factory;
if (innerDatabase != null) {
_sharedState = new SharedDatabaseState(innerDatabase._sharedState);
} else {
_sharedState = new SharedDatabaseState(_factory.Configuration.Version);
}
if (databaseDirectories != null) {
foreach (var d in databaseDirectories) {
LoadDatabase(d);
}
}
_sharedState.ListenForCorruptDatabase(this);
}
private PythonTypeDatabase(
PythonInterpreterFactoryWithDatabase factory,
string databaseDirectory,
bool isDefaultDatabase
) {
_factory = factory;
_sharedState = new SharedDatabaseState(
factory.Configuration.Version,
databaseDirectory,
defaultDatabase: isDefaultDatabase
);
}
public PythonTypeDatabase Clone() {
return new PythonTypeDatabase(_factory, null, this);
}
public PythonTypeDatabase CloneWithNewFactory(PythonInterpreterFactoryWithDatabase newFactory) {
return new PythonTypeDatabase(newFactory, null, this);
}
public PythonTypeDatabase CloneWithNewBuiltins(IBuiltinPythonModule newBuiltins) {
var newDb = new PythonTypeDatabase(_factory, null, this);
newDb._sharedState.BuiltinModule = newBuiltins;
return newDb;
}
public IPythonInterpreterFactoryWithDatabase InterpreterFactory {
get {
return _factory;
}
}
/// <summary>
/// Gets the Python version associated with this database.
/// </summary>
public Version LanguageVersion {
get {
return _factory.Configuration.Version;
}
}
/// <summary>
/// Loads modules from the specified path. Except for a builtins module,
/// these will override any currently loaded modules.
/// </summary>
public void LoadDatabase(string databasePath) {
_sharedState.LoadDatabase(databasePath);
}
/// <summary>
/// Asynchrously loads the specified extension module into the type
/// database making the completions available.
///
/// If the module has not already been analyzed it will be analyzed and
/// then loaded.
///
/// If the specified module was already loaded it replaces the existing
/// module.
///
/// Returns a new Task which can be blocked upon until the analysis of
/// the new extension module is available.
///
/// If the extension module cannot be analyzed an exception is reproted.
/// </summary>
/// <param name="cancellationToken">A cancellation token which can be
/// used to cancel the async loading of the module</param>
/// <param name="extensionModuleFilename">The filename of the extension
/// module to be loaded</param>
/// <param name="interpreter">The Python interprefer which will be used
/// to analyze the extension module.</param>
/// <param name="moduleName">The module name of the extension module.</param>
public Task LoadExtensionModuleAsync(string moduleName, string extensionModuleFilename, CancellationToken cancellationToken = default(CancellationToken)) {
return Task.Factory.StartNew(
new ExtensionModuleLoader(
this,
_factory,
moduleName,
extensionModuleFilename,
cancellationToken
).LoadExtensionModule
);
}
public bool UnloadExtensionModule(string moduleName) {
IPythonModule dummy;
return _sharedState.Modules.TryRemove(moduleName, out dummy);
}
private static Task MakeExceptionTask(Exception e) {
var res = new TaskCompletionSource<Task>();
res.SetException(e);
return res.Task;
}
class ExtensionModuleLoader {
private readonly PythonTypeDatabase _typeDb;
private readonly IPythonInterpreterFactory _factory;
private readonly string _moduleName;
private readonly string _extensionFilename;
private readonly CancellationToken _cancel;
const string _extensionModuleInfoFile = "extensions.$list";
public ExtensionModuleLoader(PythonTypeDatabase typeDb, IPythonInterpreterFactory factory, string moduleName, string extensionFilename, CancellationToken cancel) {
_typeDb = typeDb;
_factory = factory;
_moduleName = moduleName;
_extensionFilename = extensionFilename;
_cancel = cancel;
}
public void LoadExtensionModule() {
List<string> existingModules = new List<string>();
string dbFile = null;
// open the file locking it - only one person can look at the "database" of per-project analysis.
using (var fs = OpenProjectExtensionList()) {
dbFile = FindDbFile(_factory, _extensionFilename, existingModules, dbFile, fs);
if (dbFile == null) {
dbFile = GenerateDbFile(_factory, _moduleName, _extensionFilename, existingModules, dbFile, fs);
}
}
_typeDb._sharedState.Modules[_moduleName] = new CPythonModule(_typeDb, _moduleName, dbFile, false);
}
private void PublishModule(object state) {
}
private FileStream OpenProjectExtensionList() {
Directory.CreateDirectory(ReferencesDatabasePath);
for (int i = 0; i < 50 && !_cancel.IsCancellationRequested; i++) {
try {
return new FileStream(Path.Combine(ReferencesDatabasePath, _extensionModuleInfoFile), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
} catch (IOException) {
if (_cancel.CanBeCanceled) {
_cancel.WaitHandle.WaitOne(100);
} else {
System.Threading.Thread.Sleep(100);
}
}
}
throw new CannotAnalyzeExtensionException("Cannot access per-project extension registry.");
}
private string GenerateDbFile(IPythonInterpreterFactory interpreter, string moduleName, string extensionModuleFilename, List<string> existingModules, string dbFile, FileStream fs) {
// we need to generate the DB file
dbFile = Path.Combine(ReferencesDatabasePath, moduleName + ".$project.idb");
int retryCount = 0;
while (File.Exists(dbFile)) {
dbFile = Path.Combine(ReferencesDatabasePath, moduleName + "." + ++retryCount + ".$project.idb");
}
using (var output = interpreter.Run(
PythonToolsInstallPath.GetFile("ExtensionScraper.py"),
"scrape",
"-", // do not use __import__
extensionModuleFilename, // extension module path
Path.ChangeExtension(dbFile, null) // output file path (minus .idb)
)) {
if (_cancel.CanBeCanceled) {
if (WaitHandle.WaitAny(new[] { _cancel.WaitHandle, output.WaitHandle }) != 1) {
// we were cancelled
return null;
}
} else {
output.Wait();
}
if (output.ExitCode == 0) {
// [FileName]|interpGuid|interpVersion|DateTimeStamp|[db_file.idb]
// save the new entry in the DB file
existingModules.Add(
String.Format("{0}|{1}|{2}|{3}|{4}",
extensionModuleFilename,
interpreter.Id,
interpreter.Configuration.Version,
new FileInfo(extensionModuleFilename).LastWriteTime.ToString("O"),
dbFile
)
);
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
using (var sw = new StreamWriter(fs)) {
sw.Write(String.Join(Environment.NewLine, existingModules));
sw.Flush();
}
} else {
throw new CannotAnalyzeExtensionException(string.Join(Environment.NewLine, output.StandardErrorLines));
}
}
return dbFile;
}
const int extensionModuleFilenameIndex = 0;
const int interpreterGuidIndex = 1;
const int interpreterVersionIndex = 2;
const int extensionTimeStamp = 3;
const int dbFileIndex = 4;
/// <summary>
/// Finds the appropriate entry in our database file and returns the name of the .idb file to be loaded or null
/// if we do not have a generated .idb file.
/// </summary>
private static string FindDbFile(IPythonInterpreterFactory interpreter, string extensionModuleFilename, List<string> existingModules, string dbFile, FileStream fs) {
var reader = new StreamReader(fs);
string line;
while ((line = reader.ReadLine()) != null) {
// [FileName]|interpGuid|interpVersion|DateTimeStamp|[db_file.idb]
string[] columns = line.Split('|');
Guid interpGuid;
Version interpVersion;
if (columns.Length != 5) {
// malformed data...
continue;
}
if (File.Exists(columns[dbFileIndex])) {
// db file still exists
DateTime lastModified;
if (!File.Exists(columns[extensionModuleFilenameIndex]) || // extension has been deleted
!DateTime.TryParseExact(columns[extensionTimeStamp], "O", null, System.Globalization.DateTimeStyles.RoundtripKind, out lastModified) ||
lastModified != File.GetLastWriteTime(columns[extensionModuleFilenameIndex])) { // extension has been modified
// cleanup the stale DB files as we go...
try {
File.Delete(columns[dbFileIndex]);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
continue;
}
} else {
continue;
}
// check if this is the file we're looking for...
if (!Guid.TryParse(columns[interpreterGuidIndex], out interpGuid) || // corrupt data
interpGuid != interpreter.Id || // not our interpreter
!Version.TryParse(columns[interpreterVersionIndex], out interpVersion) || // corrupt data
interpVersion != interpreter.Configuration.Version ||
String.Compare(columns[extensionModuleFilenameIndex], extensionModuleFilename, StringComparison.OrdinalIgnoreCase) != 0) { // not our interpreter
// nope, but remember the line for when we re-write out the DB.
existingModules.Add(line);
continue;
}
// this is our file, but continue reading the other lines for when we write out the DB...
dbFile = columns[dbFileIndex];
}
return dbFile;
}
}
public static PythonTypeDatabase CreateDefaultTypeDatabase(PythonInterpreterFactoryWithDatabase factory) {
return new PythonTypeDatabase(factory, BaselineDatabasePath, isDefaultDatabase: true);
}
internal static PythonTypeDatabase CreateDefaultTypeDatabase(Version languageVersion) {
return new PythonTypeDatabase(InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(languageVersion),
BaselineDatabasePath, isDefaultDatabase: true);
}
public IEnumerable<string> GetModuleNames() {
return _sharedState.GetModuleNames();
}
public IPythonModule GetModule(string name) {
return _sharedState.GetModule(name);
}
public string DatabaseDirectory {
get {
return _sharedState.DatabaseDirectory;
}
}
public IBuiltinPythonModule BuiltinModule {
get {
return _sharedState.BuiltinModule;
}
}
/// <summary>
/// The exit code returned when database generation fails due to an
/// invalid argument.
/// </summary>
public const int InvalidArgumentExitCode = -1;
/// <summary>
/// The exit code returned when database generation fails due to a
/// non-specific error.
/// </summary>
public const int InvalidOperationExitCode = -2;
/// <summary>
/// The exit code returned when a database is already being generated
/// for the interpreter factory.
/// </summary>
public const int AlreadyGeneratingExitCode = -3;
/// <summary>
/// The exit code returned when a database cannot be created for the
/// interpreter factory.
/// </summary>
public const int NotSupportedExitCode = -4;
public static async Task<int> GenerateAsync(PythonTypeDatabaseCreationRequest request) {
var fact = request.Factory;
var evt = request.OnExit;
if (fact == null || !Directory.Exists(fact.Configuration.LibraryPath)) {
if (evt != null) {
evt(NotSupportedExitCode);
}
return NotSupportedExitCode;
}
var outPath = request.OutputPath;
var analyzerPath = PythonToolsInstallPath.GetFile("Microsoft.PythonTools.Analyzer.exe");
Directory.CreateDirectory(CompletionDatabasePath);
var baseDb = BaselineDatabasePath;
if (request.ExtraInputDatabases.Any()) {
baseDb = baseDb + ";" + string.Join(";", request.ExtraInputDatabases);
}
var logPath = Path.Combine(outPath, "AnalysisLog.txt");
var glogPath = Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
using (var output = ProcessOutput.RunHiddenAndCapture(
analyzerPath,
"/id", fact.Id.ToString("B"),
"/version", fact.Configuration.Version.ToString(),
"/python", fact.Configuration.InterpreterPath,
request.DetectLibraryPath ? null : "/library",
request.DetectLibraryPath ? null : fact.Configuration.LibraryPath,
"/outdir", outPath,
"/basedb", baseDb,
(request.SkipUnchanged ? null : "/all"), // null will be filtered out; empty strings are quoted
"/log", logPath,
"/glog", glogPath,
"/wait", (request.WaitFor != null ? AnalyzerStatusUpdater.GetIdentifier(request.WaitFor) : "")
)) {
output.PriorityClass = ProcessPriorityClass.BelowNormal;
int exitCode = await output;
if (exitCode > -10 && exitCode < 0) {
try {
File.AppendAllLines(
glogPath,
new[] { string.Format("FAIL_STDLIB: ({0}) {1}", exitCode, output.Arguments) }
.Concat(output.StandardErrorLines)
);
} catch (IOException) {
} catch (ArgumentException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
}
if (evt != null) {
evt(exitCode);
}
return exitCode;
}
}
/// <summary>
/// Invokes Analyzer.exe for the specified factory.
/// </summary>
[Obsolete("Use GenerateAsync instead")]
public static void Generate(PythonTypeDatabaseCreationRequest request) {
var onExit = request.OnExit;
GenerateAsync(request).ContinueWith(t => {
var exc = t.Exception;
if (exc == null) {
return;
}
try {
var message = string.Format(
"ERROR_STDLIB: {0}\\{1}{2}{3}",
request.Factory.Id,
request.Factory.Configuration.Version,
Environment.NewLine,
(exc.InnerException ?? exc).ToString()
);
Debug.WriteLine(message);
var glogPath = Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
File.AppendAllText(glogPath, message);
} catch (IOException) {
} catch (ArgumentException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
if (onExit != null) {
onExit(PythonTypeDatabase.InvalidOperationExitCode);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
private static bool DatabaseExists(string path) {
string versionFile = Path.Combine(path, "database.ver");
if (File.Exists(versionFile)) {
try {
string allLines = File.ReadAllText(versionFile);
int version;
return Int32.TryParse(allLines, out version) && version == PythonTypeDatabase.CurrentVersion;
} catch (IOException) {
}
}
return false;
}
public static string GlobalLogFilename {
get {
return Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
}
}
internal static string BaselineDatabasePath {
get {
if (_baselineDatabasePath == null) {
_baselineDatabasePath = Path.GetDirectoryName(
PythonToolsInstallPath.GetFile("CompletionDB\\__builtin__.idb")
);
}
return _baselineDatabasePath;
}
}
public static string CompletionDatabasePath {
get {
if (_completionDatabasePath == null) {
_completionDatabasePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"CompletionDB",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.VSVersion
);
}
return _completionDatabasePath;
}
}
private static string ReferencesDatabasePath {
get {
if (_referencesDatabasePath == null) {
_referencesDatabasePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"ReferencesDB",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.VSVersion
);
}
return _referencesDatabasePath;
}
}
void ITypeDatabaseReader.LookupType(object type, Action<IPythonType> assign) {
_sharedState.LookupType(type, assign);
}
string ITypeDatabaseReader.GetBuiltinTypeName(BuiltinTypeId id) {
return _sharedState.GetBuiltinTypeName(id);
}
void ITypeDatabaseReader.ReadMember(string memberName, Dictionary<string, object> memberValue, Action<string, IMember> assign, IMemberContainer container) {
_sharedState.ReadMember(memberName, memberValue, assign, container);
}
void ITypeDatabaseReader.OnDatabaseCorrupt() {
OnDatabaseCorrupt();
}
public void OnDatabaseCorrupt() {
_factory.NotifyCorruptDatabase();
}
internal CPythonConstant GetConstant(IPythonType type) {
return _sharedState.GetConstant(type);
}
internal static bool TryGetLocation(Dictionary<string, object> table, ref int line, ref int column) {
object value;
if (table.TryGetValue("location", out value)) {
object[] locationInfo = value as object[];
if (locationInfo != null && locationInfo.Length == 2 && locationInfo[0] is int && locationInfo[1] is int) {
line = (int)locationInfo[0];
column = (int)locationInfo[1];
return true;
}
}
return false;
}
public bool BeginModuleLoad(IPythonModule module, int millisecondsTimeout) {
return _sharedState.BeginModuleLoad(module, millisecondsTimeout);
}
public void EndModuleLoad(IPythonModule module) {
_sharedState.EndModuleLoad(module);
}
/// <summary>
/// Returns true if the specified database has a version specified that
/// matches the current build of PythonTypeDatabase. If false, attempts
/// to load the database may fail with an exception.
/// </summary>
public static bool IsDatabaseVersionCurrent(string databasePath) {
if (// Also ensures databasePath won't crash Path.Combine()
Directory.Exists(databasePath) &&
// Ensures that the database is not currently regenerating
!File.Exists(Path.Combine(databasePath, "database.pid"))) {
string versionFile = Path.Combine(databasePath, "database.ver");
if (File.Exists(versionFile)) {
try {
return int.Parse(File.ReadAllText(versionFile)) == CurrentVersion;
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (SecurityException) {
} catch (InvalidOperationException) {
} catch (ArgumentException) {
} catch (OverflowException) {
} catch (FormatException) {
}
}
}
return false;
}
/// <summary>
/// Returns true if the specified database is currently regenerating.
/// </summary>
public static bool IsDatabaseRegenerating(string databasePath) {
return Directory.Exists(databasePath) &&
File.Exists(Path.Combine(databasePath, "database.pid"));
}
/// <summary>
/// Gets the default set of search paths based on the path to the root
/// of the standard library.
/// </summary>
/// <param name="library">Root of the standard library.</param>
/// <returns>A list of search paths for the interpreter.</returns>
/// <remarks>New in 2.2</remarks>
public static List<PythonLibraryPath> GetDefaultDatabaseSearchPaths(string library) {
var result = new List<PythonLibraryPath>();
if (!Directory.Exists(library)) {
return result;
}
result.Add(new PythonLibraryPath(library, true, null));
var sitePackages = Path.Combine(library, "site-packages");
if (!Directory.Exists(sitePackages)) {
return result;
}
result.Add(new PythonLibraryPath(sitePackages, false, null));
result.AddRange(ModulePath.ExpandPathFiles(sitePackages)
.Select(p => new PythonLibraryPath(p, false, null))
);
return result;
}
/// <summary>
/// Gets the set of search paths by running the interpreter.
/// </summary>
/// <param name="interpreter">Path to the interpreter.</param>
/// <returns>A list of search paths for the interpreter.</returns>
/// <remarks>Added in 2.2</remarks>
public static async Task<List<PythonLibraryPath>> GetUncachedDatabaseSearchPathsAsync(string interpreter) {
List<string> lines;
// sys.path will include the working directory, so we make an empty
// path that we can filter out later
var tempWorkingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempWorkingDir);
try {
using (var proc = ProcessOutput.Run(
interpreter,
new[] {
"-S", // don't import site - we do that in code
"-E", // ignore environment
"-c", "import sys;print('\\n'.join(sys.path));print('-');import site;site.main();print('\\n'.join(sys.path))"
},
tempWorkingDir,
null,
false,
null
)) {
if (await proc != 0) {
throw new InvalidOperationException(string.Format(
"Cannot obtain list of paths{0}{1}",
Environment.NewLine,
string.Join(Environment.NewLine, proc.StandardErrorLines))
);
}
lines = proc.StandardOutputLines.ToList();
}
} finally {
try {
Directory.Delete(tempWorkingDir, true);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
}
}
var result = new List<PythonLibraryPath>();
var treatPathsAsStandardLibrary = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
bool builtinLibraries = true;
foreach (var p in lines) {
if (p == "-") {
if (builtinLibraries) {
// Seen all the builtins
builtinLibraries = false;
continue;
} else {
// Extra hyphen, so stop processing
break;
}
}
if (string.IsNullOrEmpty(p) || p == ".") {
continue;
}
string path;
try {
if (!Path.IsPathRooted(p)) {
path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(interpreter), p));
} else {
path = Path.GetFullPath(p);
}
} catch (ArgumentException) {
continue;
} catch (PathTooLongException) {
continue;
}
if (string.Equals(p, tempWorkingDir, StringComparison.OrdinalIgnoreCase)) {
continue;
}
if (Directory.Exists(path)) {
if (builtinLibraries) {
// Looking at first section of output, which are
// considered to be the "standard library"
treatPathsAsStandardLibrary.Add(path);
} else {
// Looking at second section of output, which
// includes site-packages and .pth files
result.Add(new PythonLibraryPath(path, treatPathsAsStandardLibrary.Contains(path), null));
}
}
}
return result;
}
/// <summary>
/// Gets the set of search paths that were last saved for a database.
/// </summary>
/// <param name="databasePath">Path containing the database.</param>
/// <returns>The cached list of search paths.</returns>
/// <remarks>Added in 2.2</remarks>
public static List<PythonLibraryPath> GetCachedDatabaseSearchPaths(string databasePath) {
try {
var result = new List<PythonLibraryPath>();
using (var file = File.OpenText(Path.Combine(databasePath, "database.path"))) {
string line;
while ((line = file.ReadLine()) != null) {
try {
result.Add(PythonLibraryPath.Parse(line));
} catch (FormatException) {
Debug.Fail("Invalid format: " + line);
}
}
}
return result;
} catch (IOException) {
return null;
}
}
/// <summary>
/// Saves search paths for a database.
/// </summary>
/// <param name="databasePath">The path to the database.</param>
/// <param name="paths">The list of search paths.</param>
/// <remarks>Added in 2.2</remarks>
public static void WriteDatabaseSearchPaths(string databasePath, IEnumerable<PythonLibraryPath> paths) {
using (var file = new StreamWriter(Path.Combine(databasePath, "database.path"))) {
foreach (var path in paths) {
file.WriteLine(path.ToString());
}
}
}
/// <summary>
/// Returns ModulePaths representing the modules that should be analyzed
/// for the given search paths.
/// </summary>
/// <param name="languageVersion">
/// The Python language version to assume. This affects whether
/// namespace packages are supported or not.
/// </param>
/// <param name="searchPaths">A sequence of paths to search.</param>
/// <returns>
/// All the expected modules, grouped based on codependency. When
/// analyzing modules, all those in the same list should be analyzed
/// together.
/// </returns>
/// <remarks>Added in 2.2</remarks>
public static IEnumerable<List<ModulePath>> GetDatabaseExpectedModules(
Version languageVersion,
IEnumerable<PythonLibraryPath> searchPaths
) {
var requireInitPy = ModulePath.PythonVersionRequiresInitPyFiles(languageVersion);
var stdlibGroup = new List<ModulePath>();
var packages = new List<List<ModulePath>> { stdlibGroup };
foreach (var path in searchPaths ?? Enumerable.Empty<PythonLibraryPath>()) {
if (path.IsStandardLibrary) {
stdlibGroup.AddRange(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: true,
recurse: true,
// Always require __init__.py for stdlib folders
// Otherwise we will probably include libraries multiple
// times, and while Python 3.3+ allows this, it's really
// not a good idea.
requireInitPy: true
));
} else {
packages.Add(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: true,
recurse: false,
basePackage: path.ModulePrefix
).ToList());
packages.AddRange(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: false,
recurse: true,
basePackage: path.ModulePrefix,
requireInitPy: requireInitPy
).GroupBy(g => g.LibraryPath).Select(g => g.ToList()));
}
}
return packages;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class MinTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
Assert.Equal(q.Min(), q.Min());
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty }
where !string.IsNullOrEmpty(x)
select x;
Assert.Equal(q.Min(), q.Min());
}
public static IEnumerable<object[]> Min_Int_TestData()
{
yield return new object[] { Enumerable.Repeat(42, 1), 42 };
yield return new object[] { Enumerable.Range(1, 10).ToArray(), 1 };
yield return new object[] { new int[] { -1, -10, 10, 200, 1000 }, -10 };
yield return new object[] { new int[] { 3000, 100, 200, 1000 }, 100 };
yield return new object[] { new int[] { 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat(int.MinValue, 1)), int.MinValue };
yield return new object[] { Enumerable.Repeat(20, 1), 20 };
yield return new object[] { Enumerable.Repeat(-2, 5), -2 };
yield return new object[] { Enumerable.Range(1, 10).ToArray(), 1 };
yield return new object[] { new int[] { 6, 9, 10, 7, 8 }, 6 };
yield return new object[] { new int[] { 6, 9, 10, 0, -5 }, -5 };
yield return new object[] { new int[] { 6, 0, 9, 0, 10, 0 }, 0 };
}
[Theory]
[MemberData(nameof(Min_Int_TestData))]
public void Min_Int(IEnumerable<int> source, int expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_Int_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Min(x => x));
}
[Fact]
public void Min_Int_EmptySource_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Min());
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().Min(x => x));
}
public static IEnumerable<object[]> Min_Long_TestData()
{
yield return new object[] { Enumerable.Repeat(42L, 1), 42L };
yield return new object[] { Enumerable.Range(1, 10).Select(i => (long)i).ToArray(), 1L };
yield return new object[] { new long[] { -1, -10, 10, 200, 1000 }, -10L };
yield return new object[] { new long[] { 3000, 100, 200, 1000 }, 100L };
yield return new object[] { new long[] { 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat(long.MinValue, 1)), long.MinValue };
yield return new object[] { Enumerable.Repeat(int.MaxValue + 10L, 1), int.MaxValue + 10L };
yield return new object[] { Enumerable.Repeat(500L, 5), 500L };
yield return new object[] { new long[] { -250, 49, 130, 47, 28 }, -250L };
yield return new object[] { new long[] { 6, 9, 10, 0, -int.MaxValue - 50L }, -int.MaxValue - 50L };
yield return new object[] { new long[] { 6, -5, 9, -5, 10, -5 }, -5 };
}
[Theory]
[MemberData(nameof(Min_Long_TestData))]
public void Min_Long(IEnumerable<long> source, long expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_Long_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Min(x => x));
}
[Fact]
public void Min_Long_EmptySource_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().Min());
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().Min(x => x));
}
public static IEnumerable<object[]> Min_Float_TestData()
{
yield return new object[] { Enumerable.Repeat(42f, 1), 42f };
yield return new object[] { Enumerable.Range(1, 10).Select(i => (float)i).ToArray(), 1f };
yield return new object[] { new float[] { -1, -10, 10, 200, 1000 }, -10f };
yield return new object[] { new float[] { 3000, 100, 200, 1000 }, 100 };
yield return new object[] { new float[] { 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat(float.MinValue, 1)), float.MinValue };
yield return new object[] { Enumerable.Repeat(5.5f, 1), 5.5f };
yield return new object[] { Enumerable.Repeat(float.NaN, 5), float.NaN };
yield return new object[] { new float[] { -2.5f, 4.9f, 130f, 4.7f, 28f }, -2.5f};
yield return new object[] { new float[] { 6.8f, 9.4f, 10f, 0, -5.6f }, -5.6f };
yield return new object[] { new float[] { -5.5f, float.NegativeInfinity, 9.9f, float.NegativeInfinity }, float.NegativeInfinity };
yield return new object[] { new float[] { float.NaN, 6.8f, 9.4f, 10f, 0, -5.6f }, float.NaN };
yield return new object[] { new float[] { 6.8f, 9.4f, 10f, 0, -5.6f, float.NaN }, float.NaN };
yield return new object[] { new float[] { float.NaN, float.NegativeInfinity }, float.NaN };
yield return new object[] { new float[] { float.NegativeInfinity, float.NaN }, float.NaN };
// In .NET Core, Enumerable.Min shortcircuits if it finds any float.NaN in the array,
// as nothing can be less than float.NaN. See https://github.com/dotnet/corefx/pull/2426.
// Without this optimization, we would iterate through int.MaxValue elements, which takes
// a long time.
yield return new object[] { Enumerable.Repeat(float.NaN, int.MaxValue), float.NaN };
yield return new object[] { Enumerable.Repeat(float.NaN, 3), float.NaN };
// Normally NaN < anything is false, as is anything < NaN
// However, this leads to some irksome outcomes in Min and Max.
// If we use those semantics then Min(NaN, 5.0) is NaN, but
// Min(5.0, NaN) is 5.0! To fix this, we impose a total
// ordering where NaN is smaller than every value, including
// negative infinity.
yield return new object[] { Enumerable.Range(1, 10).Select(i => (float)i).Concat(Enumerable.Repeat(float.NaN, 1)).ToArray(), float.NaN };
yield return new object[] { new float[] { -1F, -10, float.NaN, 10, 200, 1000 }, float.NaN };
yield return new object[] { new float[] { float.MinValue, 3000F, 100, 200, float.NaN, 1000 }, float.NaN };
}
[Theory]
[MemberData(nameof(Min_Float_TestData))]
public void Min_Float(IEnumerable<float> source, float expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_Float_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Min(x => x));
}
[Fact]
public void Min_Float_EmptySource_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().Min());
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().Min(x => x));
}
public static IEnumerable<object[]> Min_Double_TestData()
{
yield return new object[] { Enumerable.Repeat(42.0, 1), 42.0 };
yield return new object[] { Enumerable.Range(1, 10).Select(i => (double)i).ToArray(), 1.0 };
yield return new object[] { new double[] { -1, -10, 10, 200, 1000 }, -10.0 };
yield return new object[] { new double[] { 3000, 100, 200, 1000 }, 100.0 };
yield return new object[] { new double[] { 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat(double.MinValue, 1)), double.MinValue };
yield return new object[] { Enumerable.Repeat(5.5, 1), 5.5 };
yield return new object[] { new double[] { -2.5, 4.9, 130, 4.7, 28 }, -2.5 };
yield return new object[] { new double[] { 6.8, 9.4, 10, 0, -5.6 }, -5.6 };
yield return new object[] { new double[] { -5.5, double.NegativeInfinity, 9.9, double.NegativeInfinity }, double.NegativeInfinity };
// In .NET Core, Enumerable.Min shortcircuits if it finds any double.NaN in the array,
// as nothing can be less than double.NaN. See https://github.com/dotnet/corefx/pull/2426.
// Without this optimization, we would iterate through int.MaxValue elements, which takes
// a long time.
yield return new object[] { Enumerable.Repeat(double.NaN, int.MaxValue), double.NaN };
yield return new object[] { Enumerable.Repeat(double.NaN, 3), double.NaN };
yield return new object[] { new double[] { double.NaN, 6.8, 9.4, 10, 0, -5.6 }, double.NaN };
yield return new object[] { new double[] { 6.8, 9.4, 10, 0, -5.6, double.NaN }, double.NaN };
yield return new object[] { new double[] { double.NaN, double.NegativeInfinity }, double.NaN };
yield return new object[] { new double[] { double.NegativeInfinity, double.NaN }, double.NaN };
// Normally NaN < anything is false, as is anything < NaN
// However, this leads to some irksome outcomes in Min and Max.
// If we use those semantics then Min(NaN, 5.0) is NaN, but
// Min(5.0, NaN) is 5.0! To fix this, we impose a total
// ordering where NaN is smaller than every value, including
// negative infinity.
yield return new object[] { Enumerable.Range(1, 10).Select(i => (double)i).Concat(Enumerable.Repeat(double.NaN, 1)).ToArray(), double.NaN };
yield return new object[] { new double[] { -1, -10, double.NaN, 10, 200, 1000 }, double.NaN };
yield return new object[] { new double[] { double.MinValue, 3000F, 100, 200, double.NaN, 1000 }, double.NaN };
}
[Theory]
[MemberData(nameof(Min_Double_TestData))]
public void Min_Double(IEnumerable<double> source, double expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_Double_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Min(x => x));
}
[Fact]
public void Min_Double_EmptySource_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().Min());
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().Min(x => x));
}
public static IEnumerable<object[]> Min_Decimal_TestData()
{
yield return new object[] { Enumerable.Repeat(42m, 1), 42m };
yield return new object[] { Enumerable.Range(1, 10).Select(i => (decimal)i).ToArray(), 1m };
yield return new object[] { new decimal[] { -1, -10, 10, 200, 1000 }, -10m };
yield return new object[] { new decimal[] { 3000, 100, 200, 1000 }, 100m };
yield return new object[] { new decimal[] { 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat(decimal.MinValue, 1)), decimal.MinValue };
yield return new object[] { Enumerable.Repeat(5.5m, 1), 5.5m };
yield return new object[] { Enumerable.Repeat(-3.4m, 5), -3.4m };
yield return new object[] { new decimal[] { -2.5m, 4.9m, 130m, 4.7m, 28m }, -2.5m };
yield return new object[] { new decimal[] { 6.8m, 9.4m, 10m, 0m, 0m, decimal.MinValue }, decimal.MinValue };
yield return new object[] { new decimal[] { -5.5m, 0m, 9.9m, -5.5m, 5m }, -5.5m };
}
[Theory]
[MemberData(nameof(Min_Decimal_TestData))]
public void Min_Decimal(IEnumerable<decimal> source, decimal expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_Decimal_EmptySource_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().Min());
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().Min(x => x));
}
[Fact]
public void Min_Decimal_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Min(x => x));
}
public static IEnumerable<object[]> Min_NullableInt_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => (int?)i).ToArray(), 1 };
yield return new object[] { new int?[] { null, -1, -10, 10, 200, 1000 }, -10 };
yield return new object[] { new int?[] { null, 3000, 100, 200, 1000 }, 100 };
yield return new object[] { new int?[] { null, 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat((int?)int.MinValue, 1)), int.MinValue };
yield return new object[] { Enumerable.Repeat(default(int?), 100), null };
yield return new object[] { Enumerable.Repeat((int?)42, 1), 42 };
yield return new object[] { Enumerable.Empty<int?>(), null };
yield return new object[] { Enumerable.Repeat((int?)20, 1), 20 };
yield return new object[] { Enumerable.Repeat(default(int?), 5), null };
yield return new object[] { new int?[] { 6, null, 9, 10, null, 7, 8 }, 6 };
yield return new object[] { new int?[] { null, null, null, null, null, -5 }, -5 };
yield return new object[] { new int?[] { 6, null, null, 0, 9, 0, 10, 0 }, 0 };
}
[Theory]
[MemberData(nameof(Min_NullableInt_TestData))]
public void Min_NullableInt(IEnumerable<int?> source, int? expected)
{
Assert.Equal(expected, source.Min());
}
[Theory, MemberData(nameof(Min_NullableInt_TestData))]
public void Min_NullableIntRunOnce(IEnumerable<int?> source, int? expected)
{
Assert.Equal(expected, source.RunOnce().Min());
}
[Fact]
public void Min_NullableInt_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Min(x => x));
}
public static IEnumerable<object[]> Min_NullableLong_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => (long?)i).ToArray(), 1L };
yield return new object[] { new long?[] { null, -1, -10, 10, 200, 1000 }, -10L };
yield return new object[] { new long?[] { null, 3000, 100, 200, 1000 }, 100L };
yield return new object[] { new long?[] { null, 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat((long?)long.MinValue, 1)), long.MinValue };
yield return new object[] { Enumerable.Repeat(default(long?), 100), null };
yield return new object[] { Enumerable.Repeat((long?)42, 1), 42L };
yield return new object[] { Enumerable.Empty<long?>(), null };
yield return new object[] { Enumerable.Repeat((long?)long.MaxValue, 1), long.MaxValue };
yield return new object[] { Enumerable.Repeat(default(long?), 5), null };
yield return new object[] { new long?[] { long.MinValue, null, 9, 10, null, 7, 8 }, long.MinValue };
yield return new object[] { new long?[] { null, null, null, null, null, -long.MaxValue }, -long.MaxValue };
yield return new object[] { new long?[] { 6, null, null, 0, 9, 0, 10, 0 }, 0L };
}
[Theory]
[MemberData(nameof(Min_NullableLong_TestData))]
public void Min_NullableLong(IEnumerable<long?> source, long? expected)
{
Assert.Equal(expected, source.Min());
}
[Fact]
public void Min_NullableLong_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Min(x => x));
}
public static IEnumerable<object[]> Min_NullableFloat_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => (float?)i).ToArray(), 1f };
yield return new object[] { new float?[] { null, -1, -10, 10, 200, 1000 }, -10f };
yield return new object[] { new float?[] { null, 3000, 100, 200, 1000 }, 100f };
yield return new object[] { new float?[] { null, 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat((float?)float.MinValue, 1)), float.MinValue };
yield return new object[] { Enumerable.Repeat(default(float?), 100), null };
yield return new object[] { Enumerable.Repeat((float?)42, 1), 42f };
yield return new object[] { Enumerable.Empty<float?>(), null };
yield return new object[] { Enumerable.Repeat((float?)float.MinValue, 1), float.MinValue };
yield return new object[] { Enumerable.Repeat(default(float?), 100), null };
yield return new object[] { new float?[] { -4.50f, null, 10.98f, null, 7.5f, 8.6f }, -4.5f };
yield return new object[] { new float?[] { null, null, null, null, null, 0f }, 0f };
yield return new object[] { new float?[] { 6.4f, null, null, -0.5f, 9.4f, -0.5f, 10.9f, -0.5f }, -0.5f };
yield return new object[] { new float?[] { float.NaN, 6.8f, 9.4f, 10f, 0, null, -5.6f }, float.NaN };
yield return new object[] { new float?[] { 6.8f, 9.4f, 10f, 0, null, -5.6f, float.NaN }, float.NaN };
yield return new object[] { new float?[] { float.NaN, float.NegativeInfinity }, float.NaN };
yield return new object[] { new float?[] { float.NegativeInfinity, float.NaN }, float.NaN };
yield return new object[] { new float?[] { float.NaN, null, null, null }, float.NaN };
yield return new object[] { new float?[] { null, null, null, float.NaN }, float.NaN };
yield return new object[] { new float?[] { null, float.NaN, null }, float.NaN };
// In .NET Core, Enumerable.Min shortcircuits if it finds any float.NaN in the array,
// as nothing can be less than float.NaN. See https://github.com/dotnet/corefx/pull/2426.
// Without this optimization, we would iterate through int.MaxValue elements, which takes
// a long time.
yield return new object[] { Enumerable.Repeat((float?)float.NaN, int.MaxValue), float.NaN };
yield return new object[] { Enumerable.Repeat((float?)float.NaN, 3), float.NaN };
}
[Theory]
[MemberData(nameof(Min_NullableFloat_TestData))]
public void Min_NullableFloat(IEnumerable<float?> source, float? expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_NullableFloat_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Min(x => x));
}
public static IEnumerable<object[]> Min_NullableDouble_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => (double?)i).ToArray(), 1.0 };
yield return new object[] { new double?[] { null, -1, -10, 10, 200, 1000 }, -10.0 };
yield return new object[] { new double?[] { null, 3000, 100, 200, 1000 }, 100.0 };
yield return new object[] { new double?[] { null, 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat((double?)double.MinValue, 1)), double.MinValue };
yield return new object[] { Enumerable.Repeat(default(double?), 100), null };
yield return new object[] { Enumerable.Repeat((double?)42, 1), 42.0 };
yield return new object[] { Enumerable.Empty<double?>(), null };
yield return new object[] { Enumerable.Repeat((double?)double.MinValue, 1), double.MinValue };
yield return new object[] { Enumerable.Repeat(default(double?), 5), null };
yield return new object[] { new double?[] { -4.50, null, 10.98, null, 7.5, 8.6 }, -4.5 };
yield return new object[] { new double?[] { null, null, null, null, null, 0 }, 0.0 };
yield return new object[] { new double?[] { 6.4, null, null, -0.5, 9.4, -0.5, 10.9, -0.5 }, -0.5 };
yield return new object[] { new double?[] { double.NaN, 6.8, 9.4, 10.0, 0.0, null, -5.6 }, double.NaN };
yield return new object[] { new double?[] { 6.8, 9.4, 10, 0.0, null, -5.6f, double.NaN }, double.NaN };
yield return new object[] { new double?[] { double.NaN, double.NegativeInfinity }, double.NaN };
yield return new object[] { new double?[] { double.NegativeInfinity, double.NaN }, double.NaN };
yield return new object[] { new double?[] { double.NaN, null, null, null }, double.NaN };
yield return new object[] { new double?[] { null, null, null, double.NaN }, double.NaN };
yield return new object[] { new double?[] { null, double.NaN, null }, double.NaN };
// In .NET Core, Enumerable.Min shortcircuits if it finds any double.NaN in the array,
// as nothing can be less than double.NaN. See https://github.com/dotnet/corefx/pull/2426.
// Without this optimization, we would iterate through int.MaxValue elements, which takes
// a long time.
yield return new object[] { Enumerable.Repeat((double?)double.NaN, int.MaxValue), double.NaN };
yield return new object[] { Enumerable.Repeat((double?)double.NaN, 3), double.NaN };
}
[Theory]
[MemberData(nameof(Min_NullableDouble_TestData))]
public void Min_NullableDouble(IEnumerable<double?> source, double? expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_NullableDouble_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Min());
}
public static IEnumerable<object[]> Min_NullableDecimal_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => (decimal?)i).ToArray(), 1m };
yield return new object[] { new decimal?[] { null, -1, -10, 10, 200, 1000 }, -10m };
yield return new object[] { new decimal?[] { null, 3000, 100, 200, 1000 }, 100m };
yield return new object[] { new decimal?[] { null, 3000, 100, 200, 1000 }.Concat(Enumerable.Repeat((decimal?)decimal.MinValue, 1)), decimal.MinValue };
yield return new object[] { Enumerable.Repeat(default(decimal?), 100), null };
yield return new object[] { Enumerable.Repeat((decimal?)42, 1), 42m };
yield return new object[] { Enumerable.Empty<decimal?>(), null };
yield return new object[] { Enumerable.Repeat((decimal?)decimal.MaxValue, 1), decimal.MaxValue };
yield return new object[] { Enumerable.Repeat(default(decimal?), 5), null };
yield return new object[] { new decimal?[] { -4.50m, null, null, 10.98m, null, 7.5m, 8.6m }, -4.5m };
yield return new object[] { new decimal?[] { null, null, null, null, null, 0m }, 0m };
yield return new object[] { new decimal?[] { 6.4m, null, null, decimal.MinValue, 9.4m, decimal.MinValue, 10.9m, decimal.MinValue }, decimal.MinValue };
}
[Theory]
[MemberData(nameof(Min_NullableDecimal_TestData))]
public void Min_NullableDecimal(IEnumerable<decimal?> source, decimal? expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_NullableDecimal_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Min(x => x));
}
public static IEnumerable<object[]> Min_DateTime_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => new DateTime(2000, 1, i)).ToArray(), new DateTime(2000, 1, 1) };
yield return new object[] { new DateTime[] { new DateTime(2000, 12, 1), new DateTime(2000, 1, 1), new DateTime(2000, 1, 12) }, new DateTime(2000, 1, 1) };
DateTime[] hundred = new DateTime[]
{
new DateTime(3000, 1, 1),
new DateTime(100, 1, 1),
new DateTime(200, 1, 1),
new DateTime(1000, 1, 1)
};
yield return new object[] { hundred, new DateTime(100, 1, 1) };
yield return new object[] { hundred.Concat(Enumerable.Repeat(DateTime.MinValue, 1)), DateTime.MinValue };
}
[Theory]
[MemberData(nameof(Min_DateTime_TestData))]
public void Min_DateTime(IEnumerable<DateTime> source, DateTime expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Fact]
public void Min_DateTime_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<DateTime>)null).Min(x => x));
}
[Fact]
public void Min_DateTime_EmptySource_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().Min());
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().Min(x => x));
}
public static IEnumerable<object[]> Min_String_TestData()
{
yield return new object[] { Enumerable.Range(1, 10).Select(i => i.ToString()).ToArray(), "1" };
yield return new object[] { new string[] { "Alice", "Bob", "Charlie", "Eve", "Mallory", "Trent", "Victor" }, "Alice" };
yield return new object[] { new string[] { null, "Charlie", null, "Victor", "Trent", null, "Eve", "Alice", "Mallory", "Bob" }, "Alice" };
yield return new object[] { Enumerable.Empty<string>(), null };
yield return new object[] { Enumerable.Repeat("Hello", 1), "Hello" };
yield return new object[] { Enumerable.Repeat("hi", 5), "hi" };
yield return new object[] { new string[] { "aaa", "abcd", "bark", "temp", "cat" }, "aaa" };
yield return new object[] { new string[] { null, null, null, null, "aAa" }, "aAa" };
yield return new object[] { new string[] { "ooo", "www", "www", "ooo", "ooo", "ppp" }, "ooo" };
yield return new object[] { Enumerable.Repeat(default(string), 5), null };
}
[Theory]
[MemberData(nameof(Min_String_TestData))]
public void Min_String(IEnumerable<string> source, string expected)
{
Assert.Equal(expected, source.Min());
Assert.Equal(expected, source.Min(x => x));
}
[Theory, MemberData(nameof(Min_String_TestData))]
public void Min_StringRunOnce(IEnumerable<string> source, string expected)
{
Assert.Equal(expected, source.RunOnce().Min());
Assert.Equal(expected, source.RunOnce().Min(x => x));
}
[Fact]
public void Min_String_NullSource_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<string>)null).Min());
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<string>)null).Min(x => x));
}
[Fact]
public void Min_Int_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=10 },
new { name="John", num=-105 },
new { name="Bob", num=-30 }
};
Assert.Equal(-105, source.Min(e => e.num));
}
[Fact]
public void Min_Int_NullSelector_ThrowsArgumentNullException()
{
Func<int, int> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().Min(selector));
}
[Fact]
public void Min_Long_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=10L },
new { name="John", num=long.MinValue },
new { name="Bob", num=-10L }
};
Assert.Equal(long.MinValue, source.Min(e => e.num));
}
[Fact]
public void Min_Long_NullSelector_ThrowsArgumentNullException()
{
Func<long, long> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().Min(selector));
}
[Fact]
public void Min_Float_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=-45.5f },
new { name="John", num=-132.5f },
new { name="Bob", num=20.45f }
};
Assert.Equal(-132.5f, source.Min(e => e.num));
}
[Fact]
public void Min_Float_NullSelector_ThrowsArgumentNullException()
{
Func<float, float> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().Min(selector));
}
[Fact]
public void Min_Double_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=-45.5 },
new { name="John", num=-132.5 },
new { name="Bob", num=20.45 }
};
Assert.Equal(-132.5, source.Min(e => e.num));
}
[Fact]
public void Min_Double_NullSelector_ThrowsArgumentNullException()
{
Func<double, double> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().Min(selector));
}
[Fact]
public void Min_Decimal_WithSelectorAccessingProperty()
{
var source = new[]
{
new {name="Tim", num=100.45m},
new {name="John", num=10.5m},
new {name="Bob", num=0.05m}
};
Assert.Equal(0.05m, source.Min(e => e.num));
}
[Fact]
public void Min_Decimal_NullSelector_ThrowsArgumentNullException()
{
Func<decimal, decimal> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().Min(selector));
}
[Fact]
public void Min_NullableInt_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=(int?)10 },
new { name="John", num=default(int?) },
new { name="Bob", num=(int?)-30 }
};
Assert.Equal(-30, source.Min(e => e.num));
}
[Fact]
public void Min_NullableInt_NullSelector_ThrowsArgumentNullException()
{
Func<int?, int?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().Min(selector));
}
[Fact]
public void Min_NullableLong_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=default(long?) },
new { name="John", num=(long?)long.MinValue },
new { name="Bob", num=(long?)-10L }
};
Assert.Equal(long.MinValue, source.Min(e => e.num));
}
[Fact]
public void Min_NullableLong_NullSelector_ThrowsArgumentNullException()
{
Func<long?, long?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().Min(selector));
}
[Fact]
public void Min_NullableFloat_WithSelectorAccessingProperty()
{
var source = new[]
{
new {name="Tim", num=(float?)-45.5f},
new {name="John", num=(float?)-132.5f},
new {name="Bob", num=default(float?)}
};
Assert.Equal(-132.5f, source.Min(e => e.num));
}
[Fact]
public void Min_NullableFloat_NullSelector_ThrowsArgumentNullException()
{
Func<float?, float?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().Min(selector));
}
[Fact]
public void Min_NullableDouble_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=(double?)-45.5 },
new { name="John", num=(double?)-132.5 },
new { name="Bob", num=default(double?) }
};
Assert.Equal(-132.5, source.Min(e => e.num));
}
[Fact]
public void Min_NullableDouble_NullSelector_ThrowsArgumentNullException()
{
Func<double?, double?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().Min(selector));
}
[Fact]
public void Min_NullableDecimal_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=(decimal?)100.45m },
new { name="John", num=(decimal?)10.5m },
new { name="Bob", num=default(decimal?) }
};
Assert.Equal(10.5m, source.Min(e => e.num));
}
[Fact]
public void Min_NullableDecimal_NullSelector_ThrowsArgumentNullException()
{
Func<decimal?, decimal?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().Min(selector));
}
[Fact]
public void Min_DateTime_NullSelector_ThrowsArgumentNullException()
{
Func<DateTime, DateTime> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<DateTime>().Min(selector));
}
[Fact]
public void Min_String_WithSelectorAccessingProperty()
{
var source = new[]
{
new { name="Tim", num=100.45m },
new { name="John", num=10.5m },
new { name="Bob", num=0.05m }
};
Assert.Equal("Bob", source.Min(e => e.name));
}
[Fact]
public void Min_String_NullSelector_ThrowsArgumentNullException()
{
Func<string, string> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<string>().Min(selector));
}
[Fact]
public void Min_Bool_EmptySource_ThrowsInvalodOperationException()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<bool>().Min());
}
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing User Groups.
/// </summary>
internal partial class UserGroupsOperations : IServiceOperations<ApiManagementClient>, IUserGroupsOperations
{
/// <summary>
/// Initializes a new instance of the UserGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UserGroupsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Adds existing user to existing group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> AddToGroupAsync(string resourceGroupName, string serviceName, string uid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "AddToGroupAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all user groups.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, string uid, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
url = url + "/groups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all user groups.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Remove existing user from existing group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RemoveFromGroupAsync(string resourceGroupName, string serviceName, string uid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "RemoveFromGroupAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB.Entity
{
using System.Collections.Generic;
using System.Text;
using Util;
/// <author>Mark - mark at arangodb.com</author>
public class BaseDocument
{
private IDictionary<string, object> properties;
public BaseDocument()
: base()
{
this.properties = new Dictionary<string, object>();
}
public BaseDocument(string key)
: this()
{
this.Key = key;
}
public BaseDocument(IDictionary<string, object> properties
)
: this()
{
var tmpId = properties.RemoveAndGet(DocumentFieldAttribute.Type.ID.GetSerializeName());
if (tmpId != null)
{
this.Id = tmpId.ToString();
}
var tmpKey = properties.RemoveAndGet(DocumentFieldAttribute.Type.KEY.GetSerializeName());
if (tmpKey != null)
{
this.Key = tmpKey.ToString();
}
var tmpRev = properties.RemoveAndGet(DocumentFieldAttribute.Type.REV.GetSerializeName());
if (tmpRev != null)
{
this.Revision = tmpRev.ToString();
}
this.properties = properties;
}
public virtual string Id { get; set; }
public virtual string Key { get; set; }
public virtual string Revision { get; set; }
public virtual IDictionary<string, object> getProperties()
{
return this.properties;
}
public virtual void setProperties(IDictionary<string, object> properties)
{
this.properties = properties;
}
public virtual void addAttribute(string key, object value)
{
this.properties[key] = value;
}
public virtual void updateAttribute(string key, object value)
{
if (this.properties.ContainsKey(key))
{
this.properties[key] = value;
}
}
public virtual object getAttribute(string key)
{
return this.properties[key];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("BaseDocument [documentRevision=");
sb.Append(this.Revision);
sb.Append(", documentHandle=");
sb.Append(this.Id);
sb.Append(", documentKey=");
sb.Append(this.Key);
sb.Append(", properties=");
sb.Append(this.properties);
sb.Append("]");
return sb.ToString();
}
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result + (this.Id == null ? 0 : this.Id.GetHashCode());
result = prime * result + (this.Key == null ? 0 : this.Key.GetHashCode());
result = prime * result + (this.properties == null ? 0 : this.properties.GetHashCode());
result = prime * result + (this.Revision == null ? 0 : this.Revision.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
BaseDocument other = (BaseDocument)obj;
if (this.Id == null)
{
if (other.Id != null)
{
return false;
}
}
else
{
if (!this.Id.Equals(other.Id))
{
return false;
}
}
if (this.Key == null)
{
if (other.Key != null)
{
return false;
}
}
else
{
if (!this.Key.Equals(other.Key))
{
return false;
}
}
if (this.properties == null)
{
if (other.properties != null)
{
return false;
}
}
else
{
if (!this.properties.Equals(other.properties))
{
return false;
}
}
if (this.Revision == null)
{
if (other.Revision != null)
{
return false;
}
}
else
{
if (!this.Revision.Equals(other.Revision))
{
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Soccer.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 (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.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
namespace OpenSim.Framework.Console
{
// A console that uses cursor control and color
//
public class LocalConsole : CommandConsole
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private readonly object m_syncRoot = new object();
private int y = -1;
private int cp = 0;
private int h = 1;
private StringBuilder cmdline = new StringBuilder();
private bool echo = true;
private List<string> history = new List<string>();
private static readonly ConsoleColor[] Colors = {
// the dark colors don't seem to be visible on some black background terminals like putty :(
//ConsoleColor.DarkBlue,
//ConsoleColor.DarkGreen,
//ConsoleColor.DarkCyan,
//ConsoleColor.DarkMagenta,
//ConsoleColor.DarkYellow,
ConsoleColor.Gray,
//ConsoleColor.DarkGray,
ConsoleColor.Blue,
ConsoleColor.Green,
ConsoleColor.Cyan,
ConsoleColor.Magenta,
ConsoleColor.Yellow
};
private static ConsoleColor DeriveColor(string input)
{
// it is important to do Abs, hash values can be negative
return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
}
public LocalConsole(string defaultPrompt) : base(defaultPrompt)
{
}
private void AddToHistory(string text)
{
while (history.Count >= 100)
history.RemoveAt(0);
history.Add(text);
}
private int SetCursorTop(int top)
{
if (top >= 0 && top < System.Console.BufferHeight)
{
System.Console.CursorTop = top;
return top;
}
else
{
return System.Console.CursorTop;
}
}
private int SetCursorLeft(int left)
{
if (left >= 0 && left < System.Console.BufferWidth)
{
System.Console.CursorLeft = left;
return left;
}
else
{
return System.Console.CursorLeft;
}
}
private void Show()
{
lock (cmdline)
{
if (y == -1 || System.Console.BufferWidth == 0)
return;
int xc = prompt.Length + cp;
int new_x = xc % System.Console.BufferWidth;
int new_y = y + xc / System.Console.BufferWidth;
int end_y = y + (cmdline.Length + prompt.Length) / System.Console.BufferWidth;
if (end_y / System.Console.BufferWidth >= h)
h++;
if (end_y >= System.Console.BufferHeight) // wrap
{
y--;
new_y--;
System.Console.CursorLeft = 0;
System.Console.CursorTop = System.Console.BufferHeight-1;
System.Console.WriteLine(" ");
}
y=SetCursorTop(y);
System.Console.CursorLeft = 0;
if (echo)
System.Console.Write("{0}{1}", prompt, cmdline);
else
System.Console.Write("{0}", prompt);
SetCursorLeft(new_x);
SetCursorTop(new_y);
}
}
public override void LockOutput()
{
Monitor.Enter(cmdline);
try
{
if (y != -1)
{
y = SetCursorTop(y);
System.Console.CursorLeft = 0;
int count = cmdline.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
y = SetCursorTop(y);
System.Console.CursorLeft = 0;
}
}
catch (Exception)
{
}
}
public override void UnlockOutput()
{
if (y != -1)
{
y = System.Console.CursorTop;
Show();
}
Monitor.Exit(cmdline);
}
private void WriteColorText(ConsoleColor color, string sender)
{
try
{
lock (this)
{
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
}
}
catch (ObjectDisposedException)
{
}
}
private void WriteLocalText(string text, string level)
{
string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
Regex RE = new Regex(regex, RegexOptions.Multiline);
MatchCollection matches = RE.Matches(text);
string outText = text;
if (matches.Count == 1)
{
outText = matches[0].Groups["End"].Value;
System.Console.Write(matches[0].Groups["Front"].Value);
System.Console.Write("[");
WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
matches[0].Groups["Category"].Value);
System.Console.Write("]:");
}
if (level == "error")
WriteColorText(ConsoleColor.Red, outText);
else if (level == "warn")
WriteColorText(ConsoleColor.Yellow, outText);
else
System.Console.Write(outText);
System.Console.WriteLine();
}
public override void Output(string text)
{
Output(text, "normal");
}
public override void Output(string text, string level)
{
lock (cmdline)
{
if (y == -1)
{
WriteLocalText(text, level);
return;
}
y = SetCursorTop(y);
System.Console.CursorLeft = 0;
int count = cmdline.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
y = SetCursorTop(y);
System.Console.CursorLeft = 0;
WriteLocalText(text, level);
y = System.Console.CursorTop;
Show();
}
}
private bool ContextHelp()
{
string[] words = Parser.Parse(cmdline.ToString());
bool trailingSpace = cmdline.ToString().EndsWith(" ");
// Allow ? through while typing a URI
//
if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
return false;
string[] opts = Commands.FindNextOption(words, trailingSpace);
if (opts[0].StartsWith("Command help:"))
Output(opts[0]);
else
Output(String.Format("Options: {0}", String.Join(" ", opts)));
return true;
}
public override string ReadLine(string p, bool isCommand, bool e)
{
h = 1;
cp = 0;
prompt = p;
echo = e;
int historyLine = history.Count;
System.Console.CursorLeft = 0; // Needed for mono
System.Console.Write(" "); // Needed for mono
lock (cmdline)
{
y = System.Console.CursorTop;
cmdline.Remove(0, cmdline.Length);
}
while (true)
{
Show();
ConsoleKeyInfo key = System.Console.ReadKey(true);
char c = key.KeyChar;
if (!Char.IsControl(c))
{
if (cp >= 318)
continue;
if (c == '?' && isCommand)
{
if (ContextHelp())
continue;
}
cmdline.Insert(cp, c);
cp++;
}
else
{
switch (key.Key)
{
case ConsoleKey.Backspace:
if (cp == 0)
break;
cmdline.Remove(cp-1, 1);
cp--;
System.Console.CursorLeft = 0;
y = SetCursorTop(y);
System.Console.Write("{0}{1} ", prompt, cmdline);
break;
case ConsoleKey.End:
cp = cmdline.Length;
break;
case ConsoleKey.Home:
cp = 0;
break;
case ConsoleKey.UpArrow:
if (historyLine < 1)
break;
historyLine--;
LockOutput();
cmdline.Remove(0, cmdline.Length);
cmdline.Append(history[historyLine]);
cp = cmdline.Length;
UnlockOutput();
break;
case ConsoleKey.DownArrow:
if (historyLine >= history.Count)
break;
historyLine++;
LockOutput();
if (historyLine == history.Count)
{
cmdline.Remove(0, cmdline.Length);
}
else
{
cmdline.Remove(0, cmdline.Length);
cmdline.Append(history[historyLine]);
}
cp = cmdline.Length;
UnlockOutput();
break;
case ConsoleKey.LeftArrow:
if (cp > 0)
cp--;
break;
case ConsoleKey.RightArrow:
if (cp < cmdline.Length)
cp++;
break;
case ConsoleKey.Enter:
System.Console.CursorLeft = 0;
y = SetCursorTop(y);
System.Console.WriteLine("{0}{1}", prompt, cmdline);
lock (cmdline)
{
y = -1;
}
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdline.ToString()));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
AddToHistory(String.Join(" ", cmd));
return String.Empty;
}
}
AddToHistory(cmdline.ToString());
return cmdline.ToString();
default:
break;
}
}
}
}
}
}
| |
// Most of the important code for this control was
// taken from a control written by Nishant Sivakumar.
// http://www.codeproject.com/cs/combobox/DotNetMultiColumnComboBox.asp
//
// Bugfixes or Suggestions can be sent to [email protected]
using System;
using System.Windows.Forms;
using System.Collections;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
namespace gView.Framework.Offline.UI.Tools
{
public class MultiColumnComboBox : ComboBox
{
private bool _AutoComplete;
private bool _AutoDropdown;
private Color _BackColorEven = Color.White;
private Color _BackColorOdd = Color.White;
private string _ColumnNameString = "";
private int _ColumnWidthDefault = 75;
private string _ColumnWidthString = "";
private int _LinkedColumnIndex;
private TextBox _LinkedTextBox;
private int _TotalWidth = 0;
private int _ValueMemberColumnIndex = 0;
private Collection<string> _ColumnNames = new Collection<string>();
private Collection<int> _ColumnWidths = new Collection<int>();
public MultiColumnComboBox()
{
DrawMode = DrawMode.OwnerDrawVariable;
// Remove the Context Menu to disable pasting
ContextMenu = new ContextMenu();
}
public event System.EventHandler OpenSearchForm;
public bool AutoComplete
{
get
{
return _AutoComplete;
}
set
{
_AutoComplete = value;
}
}
public bool AutoDropdown
{
get
{
return _AutoDropdown;
}
set
{
_AutoDropdown = value;
}
}
public Color BackColorEven
{
get
{
return _BackColorEven;
}
set
{
_BackColorEven = value;
}
}
public Color BackColorOdd
{
get
{
return _BackColorOdd;
}
set
{
_BackColorOdd = value;
}
}
public Collection<string> ColumnNameCollection
{
get
{
return _ColumnNames;
}
}
public string ColumnNames
{
get
{
return _ColumnNameString;
}
set
{
// If the column string is blank, leave it blank.
// The default width will be used for all columns.
if (! Convert.ToBoolean(value.Trim().Length))
{
_ColumnNameString = "";
}
else if (value != null)
{
char[] delimiterChars = { ',', ';', ':' };
string[] columnNames = value.Split(delimiterChars);
if (!DesignMode)
{
_ColumnNames.Clear();
}
// After splitting the string into an array, iterate
// through the strings and check that they're all valid.
foreach (string s in columnNames)
{
// Does it have length?
if (Convert.ToBoolean(s.Trim().Length))
{
if (!DesignMode)
{
_ColumnNames.Add(s.Trim());
}
}
else // The value is blank
{
throw new NotSupportedException("Column names can not be blank.");
}
}
_ColumnNameString = value;
}
}
}
public Collection<int> ColumnWidthCollection
{
get
{
return _ColumnWidths;
}
}
public int ColumnWidthDefault
{
get
{
return _ColumnWidthDefault;
}
set
{
_ColumnWidthDefault = value;
}
}
public string ColumnWidths
{
get
{
return _ColumnWidthString;
}
set
{
// If the column string is blank, leave it blank.
// The default width will be used for all columns.
if (! Convert.ToBoolean(value.Trim().Length))
{
_ColumnWidthString = "";
}
else if (value != null)
{
char[] delimiterChars = { ',', ';', ':' };
string[] columnWidths = value.Split(delimiterChars);
string invalidValue = "";
int invalidIndex = -1;
int idx = 1;
int intValue;
// After splitting the string into an array, iterate
// through the strings and check that they're all integers
// or blanks
foreach (string s in columnWidths)
{
// If it has length, test if it's an integer
if (Convert.ToBoolean(s.Trim().Length))
{
// It's not an integer. Flag the offending value.
if (!int.TryParse(s, out intValue))
{
invalidIndex = idx;
invalidValue = s;
}
else // The value was okay. Increment the item index.
{
idx++;
}
}
else // The value is a space. Use the default width.
{
idx++;
}
}
// If an invalid value was found, raise an exception.
if (invalidIndex > -1)
{
string errMsg;
errMsg = "Invalid column width '" + invalidValue + "' located at column " + invalidIndex.ToString();
throw new ArgumentOutOfRangeException(errMsg);
}
else // The string is fine
{
_ColumnWidthString = value;
// Only set the values of the collections at runtime.
// Setting them at design time doesn't accomplish
// anything and causes errors since the collections
// don't exist at design time.
if (!DesignMode)
{
_ColumnWidths.Clear();
foreach (string s in columnWidths)
{
// Initialize a column width to an integer
if (Convert.ToBoolean(s.Trim().Length))
{
_ColumnWidths.Add(Convert.ToInt32(s));
}
else // Initialize the column to the default
{
_ColumnWidths.Add(_ColumnWidthDefault);
}
}
// If the column is bound to data, set the column widths
// for any columns that aren't explicitly set by the
// string value entered by the programmer
if (DataManager != null)
{
InitializeColumns();
}
}
}
}
}
}
public new DrawMode DrawMode
{
get
{
return base.DrawMode;
}
set
{
if (value != DrawMode.OwnerDrawVariable)
{
throw new NotSupportedException("Needs to be DrawMode.OwnerDrawVariable");
}
base.DrawMode = value;
}
}
public new ComboBoxStyle DropDownStyle
{
get
{
return base.DropDownStyle;
}
set
{
if (value != ComboBoxStyle.DropDown)
{
throw new NotSupportedException("ComboBoxStyle.DropDown is the only supported style");
}
base.DropDownStyle = value;
}
}
public int LinkedColumnIndex
{
get
{
return _LinkedColumnIndex;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("A column index can not be negative");
}
_LinkedColumnIndex = value;
}
}
public TextBox LinkedTextBox
{
get
{
return _LinkedTextBox;
}
set
{
_LinkedTextBox = value;
if (_LinkedTextBox != null)
{
// Set any default properties of the Linked Textbox here
_LinkedTextBox.ReadOnly = true;
_LinkedTextBox.TabStop = false;
}
}
}
public int TotalWidth
{
get
{
return _TotalWidth;
}
}
protected override void OnDataSourceChanged(EventArgs e)
{
base.OnDataSourceChanged(e);
InitializeColumns();
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
if (DesignMode)
return;
e.DrawBackground();
Rectangle boundsRect = e.Bounds;
int lastRight = 0;
Color brushForeColor;
if ((e.State & DrawItemState.Selected) == 0)
{
// Item is not selected. Use BackColorOdd & BackColorEven
Color backColor;
backColor = Convert.ToBoolean(e.Index % 2) ? _BackColorOdd : _BackColorEven;
using (SolidBrush brushBackColor = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(brushBackColor, e.Bounds);
}
brushForeColor = Color.Black;
}
else
{
// Item is selected. Use ForeColor = White
brushForeColor = Color.White;
}
using (Pen linePen = new Pen(SystemColors.GrayText))
{
using (SolidBrush brush = new SolidBrush(brushForeColor))
{
if (! Convert.ToBoolean(_ColumnNames.Count))
{
e.Graphics.DrawString(Convert.ToString(Items[e.Index]), Font, brush, boundsRect);
}
else
{
for (int colIndex = 0; colIndex < _ColumnNames.Count; colIndex++)
{
if (Convert.ToBoolean(_ColumnWidths[colIndex]))
{
string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], _ColumnNames[colIndex]));
boundsRect.X = lastRight;
boundsRect.Width = (int)_ColumnWidths[colIndex];
lastRight = boundsRect.Right;
e.Graphics.DrawString(item, Font, brush, boundsRect);
if (colIndex < _ColumnNames.Count - 1)
{
e.Graphics.DrawLine(linePen, boundsRect.Right, boundsRect.Top, boundsRect.Right, boundsRect.Bottom);
}
}
}
}
}
}
e.DrawFocusRectangle();
}
protected override void OnDropDown(EventArgs e)
{
base.OnDropDown(e);
if (_TotalWidth > 0)
{
this.DropDownWidth = _TotalWidth;
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
// Use the Delete or Escape Key to blank out the ComboBox and
// allow the user to type in a new value
if ((e.KeyCode == Keys.Delete) ||
(e.KeyCode == Keys.Escape))
{
SelectedIndex = -1;
Text = "";
if (_LinkedTextBox != null)
{
_LinkedTextBox.Text = "";
}
}
else if (e.KeyCode == Keys.F3)
{
// Fire the OpenSearchForm Event
if (OpenSearchForm != null)
{
OpenSearchForm(this, System.EventArgs.Empty);
}
}
}
// Some of the code for OnKeyPress was derived from some VB.NET code
// posted by Laurent Muller as a suggested improvement for another control.
// http://www.codeproject.com/vb/net/autocomplete_combobox.asp?df=100&forumid=3716&select=579095#xx579095xx
protected override void OnKeyPress(KeyPressEventArgs e)
{
int idx = -1;
string toFind;
DroppedDown = _AutoDropdown;
if (!Char.IsControl(e.KeyChar))
{
if (_AutoComplete)
{
toFind = Text.Substring(0, SelectionStart) + e.KeyChar;
idx = FindStringExact(toFind);
if (idx == -1)
{
// An exact match for the whole string was not found
// Find a substring instead.
idx = FindString(toFind);
}
else
{
// An exact match was found. Close the dropdown.
DroppedDown = false;
}
if (idx != -1) // The substring was found.
{
SelectedIndex = idx;
SelectionStart = toFind.Length;
SelectionLength = Text.Length - SelectionStart;
}
else // The last keystroke did not create a valid substring.
{
// If the substring is not found, cancel the keypress
e.KeyChar = (char)0;
}
}
else // AutoComplete = false. Treat it like a DropDownList by finding the
// KeyChar that was struck starting from the current index
{
idx = FindString(e.KeyChar.ToString(), SelectedIndex);
if (idx != -1)
{
SelectedIndex = idx;
}
}
}
// Do no allow the user to backspace over characters. Treat it like
// a left arrow instead. The user must not be allowed to change the
// value in the ComboBox.
if ((e.KeyChar == (char)(Keys.Back)) && // A Backspace Key is hit
(_AutoComplete) && // AutoComplete = true
(Convert.ToBoolean(SelectionStart))) // And the SelectionStart is positive
{
// Find a substring that is one character less the the current selection.
// This mimicks moving back one space with an arrow key. This substring should
// always exist since we don't allow invalid selections to be typed. If you're
// on the 3rd character of a valid code, then the first two characters have to
// be valid. Moving back to them and finding the 1st occurrence should never fail.
toFind = Text.Substring(0, SelectionStart - 1);
idx = FindString(toFind);
if (idx != -1)
{
SelectedIndex = idx;
SelectionStart = toFind.Length;
SelectionLength = Text.Length - SelectionStart;
}
}
// e.Handled is always true. We handle every keystroke programatically.
e.Handled = true;
}
protected override void OnSelectedValueChanged(EventArgs e)
{
if (_LinkedTextBox != null)
{
if (_LinkedColumnIndex < _ColumnNames.Count)
{
_LinkedTextBox.Text = Convert.ToString(FilterItemOnProperty(SelectedItem, _ColumnNames[_LinkedColumnIndex]));
}
}
}
protected override void OnValueMemberChanged(EventArgs e)
{
base.OnValueMemberChanged(e);
InitializeValueMemberColumn();
}
private void InitializeColumns()
{
if (!Convert.ToBoolean(_ColumnNameString.Length))
{
PropertyDescriptorCollection propertyDescriptorCollection = DataManager.GetItemProperties();
_TotalWidth = 0;
_ColumnNames.Clear();
for (int colIndex = 0; colIndex < propertyDescriptorCollection.Count; colIndex++)
{
_ColumnNames.Add(propertyDescriptorCollection[colIndex].Name);
// If the index is greater than the collection of explicitly
// set column widths, set any additional columns to the default
if (colIndex >= _ColumnWidths.Count)
{
_ColumnWidths.Add(_ColumnWidthDefault);
}
_TotalWidth += _ColumnWidths[colIndex];
}
}
else
{
_TotalWidth = 0;
for (int colIndex = 0; colIndex < _ColumnNames.Count; colIndex++)
{
// If the index is greater than the collection of explicitly
// set column widths, set any additional columns to the default
if (colIndex >= _ColumnWidths.Count)
{
_ColumnWidths.Add(_ColumnWidthDefault);
}
_TotalWidth += _ColumnWidths[colIndex];
}
}
// Check to see if the programmer is trying to display a column
// in the linked textbox that is greater than the columns in the
// ComboBox. I handle this error by resetting it to zero.
if (_LinkedColumnIndex >= _ColumnNames.Count)
{
_LinkedColumnIndex = 0; // Or replace this with an OutOfBounds Exception
}
}
private void InitializeValueMemberColumn()
{
int colIndex = 0;
foreach (String columnName in _ColumnNames)
{
if (String.Compare(columnName, ValueMember, true, CultureInfo.CurrentUICulture) == 0)
{
_ValueMemberColumnIndex = colIndex;
break;
}
colIndex++;
}
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Rfc2251.RfcFilter.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.LDAP.VQ.Asn1;
using Novell.Directory.LDAP.VQ.Utilclass;
namespace Novell.Directory.LDAP.VQ.Rfc2251
{
/// <summary> Represents an Ldap Filter.
///
/// This filter object can be created from a String or can be built up
/// programatically by adding filter components one at a time. Existing filter
/// components can be iterated though.
///
/// Each filter component has an integer identifier defined in this class.
/// The following are basic filter components: {@link #EQUALITY_MATCH},
/// {@link #GREATER_OR_EQUAL}, {@link #LESS_OR_EQUAL}, {@link #SUBSTRINGS},
/// {@link #PRESENT}, {@link #APPROX_MATCH}, {@link #EXTENSIBLE_MATCH}.
///
/// More filters can be nested together into more complex filters with the
/// following filter components: {@link #AND}, {@link #OR}, {@link #NOT}
///
/// Substrings can have three components:
/// <pre>
/// Filter ::= CHOICE {
/// and [0] SET OF Filter,
/// or [1] SET OF Filter,
/// not [2] Filter,
/// equalityMatch [3] AttributeValueAssertion,
/// substrings [4] SubstringFilter,
/// greaterOrEqual [5] AttributeValueAssertion,
/// lessOrEqual [6] AttributeValueAssertion,
/// present [7] AttributeDescription,
/// approxMatch [8] AttributeValueAssertion,
/// extensibleMatch [9] MatchingRuleAssertion }
/// </pre>
/// </summary>
public class RfcFilter:Asn1Choice
{
//*************************************************************************
// Public variables for Filter
//*************************************************************************
/// <summary> Identifier for AND component.</summary>
public const int AND = LdapSearchRequest.AND;
/// <summary> Identifier for OR component.</summary>
public const int OR = LdapSearchRequest.OR;
/// <summary> Identifier for NOT component.</summary>
public const int NOT = LdapSearchRequest.NOT;
/// <summary> Identifier for EQUALITY_MATCH component.</summary>
public const int EQUALITY_MATCH = LdapSearchRequest.EQUALITY_MATCH;
/// <summary> Identifier for SUBSTRINGS component.</summary>
public const int SUBSTRINGS = LdapSearchRequest.SUBSTRINGS;
/// <summary> Identifier for GREATER_OR_EQUAL component.</summary>
public const int GREATER_OR_EQUAL = LdapSearchRequest.GREATER_OR_EQUAL;
/// <summary> Identifier for LESS_OR_EQUAL component.</summary>
public const int LESS_OR_EQUAL = LdapSearchRequest.LESS_OR_EQUAL;
/// <summary> Identifier for PRESENT component.</summary>
public const int PRESENT = LdapSearchRequest.PRESENT;
/// <summary> Identifier for APPROX_MATCH component.</summary>
public const int APPROX_MATCH = LdapSearchRequest.APPROX_MATCH;
/// <summary> Identifier for EXTENSIBLE_MATCH component.</summary>
public const int EXTENSIBLE_MATCH = LdapSearchRequest.EXTENSIBLE_MATCH;
/// <summary> Identifier for INITIAL component.</summary>
public const int INITIAL = LdapSearchRequest.INITIAL;
/// <summary> Identifier for ANY component.</summary>
public const int ANY = LdapSearchRequest.ANY;
/// <summary> Identifier for FINAL component.</summary>
public const int FINAL = LdapSearchRequest.FINAL;
//*************************************************************************
// Private variables for Filter
//*************************************************************************
private FilterTokenizer ft;
private System.Collections.Stack filterStack;
private bool finalFound;
//*************************************************************************
// Constructor for Filter
//*************************************************************************
/// <summary> Constructs a Filter object by parsing an RFC 2254 Search Filter String.</summary>
public RfcFilter(String filter):base(null)
{
ChoiceValue = parse(filter);
return ;
}
/// <summary> Constructs a Filter object that will be built up piece by piece. </summary>
public RfcFilter():base(null)
{
filterStack = new System.Collections.Stack();
//The choice value must be set later: setChoiceValue(rootFilterTag)
return ;
}
//*************************************************************************
// Helper methods for RFC 2254 Search Filter parsing.
//*************************************************************************
/// <summary> Parses an RFC 2251 filter string into an ASN.1 Ldap Filter object.</summary>
private Asn1Tagged parse(String filterExpr)
{
if ((object) filterExpr == null || filterExpr.Equals(""))
{
filterExpr = new System.Text.StringBuilder("(objectclass=*)").ToString();
}
int idx;
if ((idx = filterExpr.IndexOf((Char) '\\')) != - 1)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(filterExpr);
int i = idx;
while (i < (sb.Length - 1))
{
char c = sb[i++];
if (c == '\\')
{
// found '\' (backslash)
// If V2 escape, turn to a V3 escape
c = sb[i];
if (c == '*' || c == '(' || c == ')' || c == '\\')
{
// Ldap v2 filter, convert them into hex chars
sb.Remove(i, i + 1 - i);
sb.Insert(i, Convert.ToString((int) c, 16));
i += 2;
}
}
}
filterExpr = sb.ToString();
}
// missing opening and closing parentheses, must be V2, add parentheses
if ((filterExpr[0] != '(') && (filterExpr[filterExpr.Length - 1] != ')'))
{
filterExpr = "(" + filterExpr + ")";
}
char ch = filterExpr[0];
int len = filterExpr.Length;
// missing opening parenthesis ?
if (ch != '(')
{
throw new LdapLocalException(ExceptionMessages.MISSING_LEFT_PAREN, LdapException.FILTER_ERROR);
}
// missing closing parenthesis ?
if (filterExpr[len - 1] != ')')
{
throw new LdapLocalException(ExceptionMessages.MISSING_RIGHT_PAREN, LdapException.FILTER_ERROR);
}
// unmatched parentheses ?
int parenCount = 0;
for (int i = 0; i < len; i++)
{
if (filterExpr[i] == '(')
{
parenCount++;
}
if (filterExpr[i] == ')')
{
parenCount--;
}
}
if (parenCount > 0)
{
throw new LdapLocalException(ExceptionMessages.MISSING_RIGHT_PAREN, LdapException.FILTER_ERROR);
}
if (parenCount < 0)
{
throw new LdapLocalException(ExceptionMessages.MISSING_LEFT_PAREN, LdapException.FILTER_ERROR);
}
ft = new FilterTokenizer(this, filterExpr);
return parseFilter();
}
/// <summary> Parses an RFC 2254 filter</summary>
private Asn1Tagged parseFilter()
{
ft.getLeftParen();
Asn1Tagged filter = parseFilterComp();
ft.getRightParen();
return filter;
}
/// <summary> RFC 2254 filter helper method. Will Parse a filter component.</summary>
private Asn1Tagged parseFilterComp()
{
Asn1Tagged tag = null;
int filterComp = ft.OpOrAttr;
switch (filterComp)
{
case AND:
case OR:
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilterList(), false);
break;
case NOT:
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilter(), true);
break;
default:
int filterType = ft.FilterType;
String value_Renamed = ft.Value;
switch (filterType)
{
case GREATER_OR_EQUAL:
case LESS_OR_EQUAL:
case APPROX_MATCH:
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterType), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
break;
case EQUALITY_MATCH:
if (value_Renamed.Equals("*"))
{
// present
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(ft.Attr), false);
}
else if (value_Renamed.IndexOf((Char) '*') != - 1)
{
// substrings parse:
// [initial], *any*, [final] into an Asn1SequenceOf
SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*", true);
// SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*");//, true);
Asn1SequenceOf seq = new Asn1SequenceOf(5);
int tokCnt = sub.Count;
int cnt = 0;
String lastTok = new System.Text.StringBuilder("").ToString();
while (sub.HasMoreTokens())
{
String subTok = sub.NextToken();
cnt++;
if (subTok.Equals("*"))
{
// if previous token was '*', and since the current
// token is a '*', we need to insert 'any'
if (lastTok.Equals(subTok))
{
// '**'
seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString("")), false));
}
}
else
{
// value (RfcLdapString)
if (cnt == 1)
{
// initial
seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, INITIAL), new RfcLdapString(unescapeString(subTok)), false));
}
else if (cnt < tokCnt)
{
// any
seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString(subTok)), false));
}
else
{
// final
seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, FINAL), new RfcLdapString(unescapeString(subTok)), false));
}
}
lastTok = subTok;
}
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(ft.Attr), seq), false);
}
else
{
// simple
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EQUALITY_MATCH), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false);
}
break;
case EXTENSIBLE_MATCH:
String type = null, matchingRule = null;
bool dnAttributes = false;
// SupportClass.Tokenizer st = new StringTokenizer(ft.Attr, ":", true);
SupportClass.Tokenizer st = new SupportClass.Tokenizer(ft.Attr, ":");//, true);
bool first = true;
while (st.HasMoreTokens())
{
String s = st.NextToken().Trim();
if (first && !s.Equals(":"))
{
type = s;
}
// dn must be lower case to be considered dn of the Entry.
else if (s.Equals("dn"))
{
dnAttributes = true;
}
else if (!s.Equals(":"))
{
matchingRule = s;
}
first = false;
}
tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((object) type == null)?null:new RfcAttributeDescription(type), new RfcAssertionValue(unescapeString(value_Renamed)), (dnAttributes == false)?null:new Asn1Boolean(true)), false);
break;
}
break;
}
return tag;
}
/// <summary> Must have 1 or more Filters</summary>
private Asn1SetOf parseFilterList()
{
Asn1SetOf set_Renamed = new Asn1SetOf();
set_Renamed.add(parseFilter()); // must have at least 1 filter
while (ft.peekChar() == '(')
{
// check for more filters
set_Renamed.add(parseFilter());
}
return set_Renamed;
}
/// <summary> Convert hex character to an integer. Return -1 if char is something
/// other than a hex char.
/// </summary>
internal static int hex2int(char c)
{
return (c >= '0' && c <= '9')?c - '0':(c >= 'A' && c <= 'F')?c - 'A' + 10:(c >= 'a' && c <= 'f')?c - 'a' + 10:- 1;
}
/// <summary> Replace escaped hex digits with the equivalent binary representation.
/// Assume either V2 or V3 escape mechanisms:
/// V2: \*, \(, \), \\.
/// V3: \2A, \28, \29, \5C, \00.
///
/// </summary>
/// <param name="string"> A part of the input filter string to be converted.
///
/// </param>
/// <returns> octet-string encoding of the specified string.
/// </returns>
private sbyte[] unescapeString(String string_Renamed)
{
// give octets enough space to grow
sbyte[] octets = new sbyte[string_Renamed.Length * 3];
// index for string and octets
int iString, iOctets;
// escape==true means we are in an escape sequence.
bool escape = false;
// escStart==true means we are reading the first character of an escape.
bool escStart = false;
int ival, length = string_Renamed.Length;
sbyte[] utf8Bytes;
char ch; // Character we are adding to the octet string
char[] ca = new char[1]; // used while converting multibyte UTF-8 char
char temp = (char) (0); // holds the value of the escaped sequence
// loop through each character of the string and copy them into octets
// converting escaped sequences when needed
for (iString = 0, iOctets = 0; iString < length; iString++)
{
ch = string_Renamed[iString];
if (escape)
{
if ((ival = hex2int(ch)) < 0)
{
// Invalid escape value(not a hex character)
throw new LdapLocalException(ExceptionMessages.INVALID_ESCAPE, new object[]{ch}, LdapException.FILTER_ERROR);
}
else
{
// V3 escaped: \\**
if (escStart)
{
temp = (char) (ival << 4); // high bits of escaped char
escStart = false;
}
else
{
temp |= (char) (ival); // all bits of escaped char
octets[iOctets++] = (sbyte) temp;
escStart = escape = false;
}
}
}
else if (ch == '\\')
{
escStart = escape = true;
}
else
{
try
{
// place the character into octets.
if ((ch >= 0x01 && ch <= 0x27) || (ch >= 0x2B && ch <= 0x5B) || (ch >= 0x5D))
{
// found valid char
if (ch <= 0x7f)
{
// char = %x01-27 / %x2b-5b / %x5d-7f
octets[iOctets++] = (sbyte) ch;
}
else
{
// char > 0x7f, could be encoded in 2 or 3 bytes
ca[0] = ch;
System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
byte[] ibytes = encoder.GetBytes(new String(ca));
utf8Bytes=SupportClass.ToSByteArray(ibytes);
// utf8Bytes = new System.String(ca).getBytes("UTF-8");
// copy utf8 encoded character into octets
Array.Copy((Array) (utf8Bytes), 0, (Array) octets, iOctets, utf8Bytes.Length);
iOctets = iOctets + utf8Bytes.Length;
}
escape = false;
}
else
{
// found invalid character
String escString = "";
ca[0] = ch;
System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
byte[] ibytes = encoder.GetBytes(new String(ca));
utf8Bytes=SupportClass.ToSByteArray(ibytes);
// utf8Bytes = new System.String(ca).getBytes("UTF-8");
for (int i = 0; i < utf8Bytes.Length; i++)
{
sbyte u = utf8Bytes[i];
if ((u >= 0) && (u < 0x10))
{
escString = escString + "\\0" + Convert.ToString(u & 0xff, 16);
}
else
{
escString = escString + "\\" + Convert.ToString(u & 0xff, 16);
}
}
throw new LdapLocalException(ExceptionMessages.INVALID_CHAR_IN_FILTER, new object[]{ch, escString}, LdapException.FILTER_ERROR);
}
}
catch (System.IO.IOException ue)
{
throw new Exception("UTF-8 String encoding not supported by JVM");
}
}
}
// Verify that any escape sequence completed
if (escStart || escape)
{
throw new LdapLocalException(ExceptionMessages.SHORT_ESCAPE, LdapException.FILTER_ERROR);
}
sbyte[] toReturn = new sbyte[iOctets];
// Array.Copy((System.Array)SupportClass.ToByteArray(octets), 0, (System.Array)SupportClass.ToByteArray(toReturn), 0, iOctets);
Array.Copy((Array)octets, 0, (Array)toReturn, 0, iOctets);
octets = null;
return toReturn;
}
/* **********************************************************************
* The following methods aid in building filters sequentially,
* and is used by DSMLHandler:
***********************************************************************/
/// <summary> Called by sequential filter building methods to add to a filter
/// component.
///
/// Verifies that the specified Asn1Object can be added, then adds the
/// object to the filter.
/// </summary>
/// <param name="current"> Filter component to be added to the filter
/// @throws LdapLocalException Occurs when an invalid component is added, or
/// when the component is out of sequence.
/// </param>
private void addObject(Asn1Object current)
{
if (filterStack == null)
{
filterStack = new System.Collections.Stack();
}
if (choiceValue() == null)
{
//ChoiceValue is the root Asn1 node
ChoiceValue = current;
}
else
{
Asn1Tagged topOfStack = (Asn1Tagged) filterStack.Peek();
Asn1Object value_Renamed = topOfStack.taggedValue();
if (value_Renamed == null)
{
topOfStack.TaggedValue = current;
filterStack.Push(current);
// filterStack.Add(current);
}
else if (value_Renamed is Asn1SetOf)
{
((Asn1SetOf) value_Renamed).add(current);
//don't add this to the stack:
}
else if (value_Renamed is Asn1Set)
{
((Asn1Set) value_Renamed).add(current);
//don't add this to the stack:
}
else if (value_Renamed.getIdentifier().Tag == LdapSearchRequest.NOT)
{
throw new LdapLocalException("Attemp to create more than one 'not' sub-filter", LdapException.FILTER_ERROR);
}
}
int type = current.getIdentifier().Tag;
if (type == AND || type == OR || type == NOT)
{
// filterStack.Add(current);
filterStack.Push(current);
}
return ;
}
/// <summary> Creates and addes a substrings filter component.
///
/// startSubstrings must be immediatly followed by at least one
/// {@link #addSubstring} method and one {@link #endSubstrings} method
/// @throws Novell.Directory.Ldap.LdapLocalException
/// Occurs when this component is created out of sequence.
/// </summary>
public virtual void startSubstrings(String attrName)
{
finalFound = false;
Asn1SequenceOf seq = new Asn1SequenceOf(5);
Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(attrName), seq), false);
addObject(current);
SupportClass.StackPush(filterStack, seq);
return ;
}
/// <summary> Adds a Substring component of initial, any or final substring matching.
///
/// This method can be invoked only if startSubString was the last filter-
/// building method called. A substring is not required to have an 'INITIAL'
/// substring. However, when a filter contains an 'INITIAL' substring only
/// one can be added, and it must be the first substring added. Any number of
/// 'ANY' substrings can be added. A substring is not required to have a
/// 'FINAL' substrings either. However, when a filter does contain a 'FINAL'
/// substring only one can be added, and it must be the last substring added.
///
/// </summary>
/// <param name="type">Substring type: INITIAL | ANY | FINAL]
/// </param>
/// <param name="value">Value to use for matching
/// @throws LdapLocalException Occurs if this method is called out of
/// sequence or the type added is out of sequence.
/// </param>
[CLSCompliant(false)]
public virtual void addSubstring(int type, sbyte[] value_Renamed)
{
try
{
Asn1SequenceOf substringSeq = (Asn1SequenceOf) filterStack.Peek();
if (type != INITIAL && type != ANY && type != FINAL)
{
throw new LdapLocalException("Attempt to add an invalid " + "substring type", LdapException.FILTER_ERROR);
}
if (type == INITIAL && substringSeq.size() != 0)
{
throw new LdapLocalException("Attempt to add an initial " + "substring match after the first substring", LdapException.FILTER_ERROR);
}
if (finalFound)
{
throw new LdapLocalException("Attempt to add a substring " + "match after a final substring match", LdapException.FILTER_ERROR);
}
if (type == FINAL)
{
finalFound = true;
}
substringSeq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, type), new RfcLdapString(value_Renamed), false));
}
catch (InvalidCastException e)
{
throw new LdapLocalException("A call to addSubstring occured " + "without calling startSubstring", LdapException.FILTER_ERROR);
}
return ;
}
/// <summary> Completes a SubString filter component.
///
/// @throws LdapLocalException Occurs when this is called out of sequence,
/// or the substrings filter is empty.
/// </summary>
public virtual void endSubstrings()
{
try
{
finalFound = false;
Asn1SequenceOf substringSeq = (Asn1SequenceOf) filterStack.Peek();
if (substringSeq.size() == 0)
{
throw new LdapLocalException("Empty substring filter", LdapException.FILTER_ERROR);
}
}
catch (InvalidCastException e)
{
throw new LdapLocalException("Missmatched ending of substrings", LdapException.FILTER_ERROR);
}
filterStack.Pop();
return ;
}
/// <summary> Creates and adds an AttributeValueAssertion to the filter.
///
/// </summary>
/// <param name="rfcType">Filter type: EQUALITY_MATCH | GREATER_OR_EQUAL
/// | LESS_OR_EQUAL | APPROX_MATCH ]
/// </param>
/// <param name="attrName">Name of the attribute to be asserted
/// </param>
/// <param name="value">Value of the attribute to be asserted
/// @throws LdapLocalException
/// Occurs when the filter type is not a valid attribute assertion.
/// </param>
[CLSCompliant(false)]
public virtual void addAttributeValueAssertion(int rfcType, String attrName, sbyte[] value_Renamed)
{
if (filterStack != null && !(filterStack.Count == 0) && filterStack.Peek() is Asn1SequenceOf)
{
//If a sequenceof is on the stack then substring is left on the stack
throw new LdapLocalException("Cannot insert an attribute assertion in a substring", LdapException.FILTER_ERROR);
}
if ((rfcType != EQUALITY_MATCH) && (rfcType != GREATER_OR_EQUAL) && (rfcType != LESS_OR_EQUAL) && (rfcType != APPROX_MATCH))
{
throw new LdapLocalException("Invalid filter type for AttributeValueAssertion", LdapException.FILTER_ERROR);
}
Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), new RfcAttributeValueAssertion(new RfcAttributeDescription(attrName), new RfcAssertionValue(value_Renamed)), false);
addObject(current);
return ;
}
/// <summary> Creates and adds a present matching to the filter.
///
/// </summary>
/// <param name="attrName">Name of the attribute to check for presence.
/// @throws LdapLocalException
/// Occurs if addPresent is called out of sequence.
/// </param>
public virtual void addPresent(String attrName)
{
Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(attrName), false);
addObject(current);
return ;
}
/// <summary> Adds an extensible match to the filter.
///
/// </summary>
/// <param name="">matchingRule
/// OID or name of the matching rule to use for comparison
/// </param>
/// <param name="attrName"> Name of the attribute to match.
/// </param>
/// <param name="value"> Value of the attribute to match against.
/// </param>
/// <param name="useDNMatching">Indicates whether DN matching should be used.
/// @throws LdapLocalException
/// Occurs when addExtensibleMatch is called out of sequence.
/// </param>
[CLSCompliant(false)]
public virtual void addExtensibleMatch(String matchingRule, String attrName, sbyte[] value_Renamed, bool useDNMatching)
{
Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((object) attrName == null)?null:new RfcAttributeDescription(attrName), new RfcAssertionValue(value_Renamed), (useDNMatching == false)?null:new Asn1Boolean(true)), false);
addObject(current);
return ;
}
/// <summary> Creates and adds the Asn1Tagged value for a nestedFilter: AND, OR, or
/// NOT.
///
/// Note that a Not nested filter can only have one filter, where AND
/// and OR do not
///
/// </summary>
/// <param name="rfcType">Filter type:
/// [AND | OR | NOT]
/// @throws Novell.Directory.Ldap.LdapLocalException
/// </param>
public virtual void startNestedFilter(int rfcType)
{
Asn1Object current;
if (rfcType == AND || rfcType == OR)
{
current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), new Asn1SetOf(), false);
}
else if (rfcType == NOT)
{
current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), null, true);
}
else
{
throw new LdapLocalException("Attempt to create a nested filter other than AND, OR or NOT", LdapException.FILTER_ERROR);
}
addObject(current);
return ;
}
/// <summary> Completes a nested filter and checks for the valid filter type.</summary>
/// <param name="rfcType"> Type of filter to complete.
/// @throws Novell.Directory.Ldap.LdapLocalException Occurs when the specified
/// type differs from the current filter component.
/// </param>
public virtual void endNestedFilter(int rfcType)
{
if (rfcType == NOT)
{
//if this is a Not than Not should be the second thing on the stack
filterStack.Pop();
}
int topOfStackType = ((Asn1Object) filterStack.Peek()).getIdentifier().Tag;
if (topOfStackType != rfcType)
{
throw new LdapLocalException("Missmatched ending of nested filter", LdapException.FILTER_ERROR);
}
filterStack.Pop();
return ;
}
/// <summary> Creates an iterator over the preparsed segments of a filter.
///
/// The first object returned by an iterator is an integer indicating the
/// type of filter components. Subseqence values are returned. If a
/// component is of type 'AND' or 'OR' or 'NOT' then the value
/// returned is another iterator. This iterator is used by ToString.
///
/// </summary>
/// <returns> Iterator over filter segments
/// </returns>
public virtual System.Collections.IEnumerator getFilterIterator()
{
return new FilterIterator(this, (Asn1Tagged) choiceValue());
}
/// <summary> Creates and returns a String representation of this filter.</summary>
public virtual String filterToString()
{
System.Text.StringBuilder filter = new System.Text.StringBuilder();
stringFilter(getFilterIterator(), filter);
return filter.ToString();
}
/// <summary> Uses a filterIterator to create a string representation of a filter.
///
/// </summary>
/// <param name="itr">Iterator of filter components
/// </param>
/// <param name="filter">Buffer to place a string representation of the filter
/// </param>
/// <seealso cref="FilterIterator">
/// </seealso>
private static void stringFilter(System.Collections.IEnumerator itr, System.Text.StringBuilder filter)
{
int op = - 1;
filter.Append('(');
while (itr.MoveNext())
{
object filterpart = itr.Current;
if (filterpart is Int32)
{
op = ((Int32) filterpart);
switch (op)
{
case AND:
filter.Append('&');
break;
case OR:
filter.Append('|');
break;
case NOT:
filter.Append('!');
break;
case EQUALITY_MATCH: {
filter.Append((String) itr.Current);
filter.Append('=');
sbyte[] value_Renamed = (sbyte[]) itr.Current;
filter.Append(byteString(value_Renamed));
break;
}
case GREATER_OR_EQUAL: {
filter.Append((String) itr.Current);
filter.Append(">=");
sbyte[] value_Renamed = (sbyte[]) itr.Current;
filter.Append(byteString(value_Renamed));
break;
}
case LESS_OR_EQUAL: {
filter.Append((String) itr.Current);
filter.Append("<=");
sbyte[] value_Renamed = (sbyte[]) itr.Current;
filter.Append(byteString(value_Renamed));
break;
}
case PRESENT:
filter.Append((String) itr.Current);
filter.Append("=*");
break;
case APPROX_MATCH:
filter.Append((String) itr.Current);
filter.Append("~=");
sbyte[] value_Renamed2 = (sbyte[]) itr.Current;
filter.Append(byteString(value_Renamed2));
break;
case EXTENSIBLE_MATCH:
String oid = (String) itr.Current;
filter.Append((String) itr.Current);
filter.Append(':');
filter.Append(oid);
filter.Append(":=");
filter.Append((String) itr.Current);
break;
case SUBSTRINGS: {
filter.Append((String) itr.Current);
filter.Append('=');
bool noStarLast = false;
while (itr.MoveNext())
{
op = ((Int32) itr.Current);
switch (op)
{
case INITIAL:
filter.Append((String) itr.Current);
filter.Append('*');
noStarLast = false;
break;
case ANY:
if (noStarLast)
filter.Append('*');
filter.Append((String) itr.Current);
filter.Append('*');
noStarLast = false;
break;
case FINAL:
if (noStarLast)
filter.Append('*');
filter.Append((String) itr.Current);
break;
}
}
break;
}
}
}
else if (filterpart is System.Collections.IEnumerator)
{
stringFilter((System.Collections.IEnumerator) filterpart, filter);
}
}
filter.Append(')');
}
/// <summary> Convert a UTF8 encoded string, or binary data, into a String encoded for
/// a string filter.
/// </summary>
private static String byteString(sbyte[] value_Renamed)
{
String toReturn = null;
if (Base64.isValidUTF8(value_Renamed, true))
{
try
{
System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");
char[] dchar = encoder.GetChars(SupportClass.ToByteArray(value_Renamed));
toReturn = new String(dchar);
// toReturn = new String(value_Renamed, "UTF-8");
}
catch (System.IO.IOException e)
{
throw new Exception("Default JVM does not support UTF-8 encoding" + e);
}
}
else
{
System.Text.StringBuilder binary = new System.Text.StringBuilder();
for (int i = 0; i < value_Renamed.Length; i++)
{
//TODO repair binary output
//Every octet needs to be escaped
if (value_Renamed[i] >= 0)
{
//one character hex string
binary.Append("\\0");
binary.Append(Convert.ToString(value_Renamed[i], 16));
}
else
{
//negative (eight character) hex string
binary.Append("\\" + Convert.ToString(value_Renamed[i], 16).Substring(6));
}
}
toReturn = binary.ToString();
}
return toReturn;
}
/// <summary> This inner class wrappers the Search Filter with an iterator.
/// This iterator will give access to all the individual components
/// preparsed. The first call to next will return an Integer identifying
/// the type of filter component. Then the component values will be returned
/// AND, NOT, and OR components values will be returned as Iterators.
/// </summary>
private class FilterIterator : System.Collections.IEnumerator
{
public void Reset(){}
private void InitBlock(RfcFilter enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private RfcFilter enclosingInstance;
/// <summary> Returns filter identifiers and components of a filter.
///
/// The first object returned is an Integer identifying
/// its type.
/// </summary>
public virtual object Current
{
get
{
object toReturn = null;
if (!tagReturned)
{
tagReturned = true;
toReturn = root.getIdentifier().Tag;
}
else
{
Asn1Object asn1 = root.taggedValue();
if (asn1 is RfcLdapString)
{
//one value to iterate
hasMore = false;
toReturn = ((RfcLdapString) asn1).stringValue();
}
else if (asn1 is RfcSubstringFilter)
{
RfcSubstringFilter sub = (RfcSubstringFilter) asn1;
if (index == - 1)
{
//return attribute name
index = 0;
RfcAttributeDescription attr = (RfcAttributeDescription) sub.get_Renamed(0);
toReturn = attr.stringValue();
}
else if (index % 2 == 0)
{
//return substring identifier
Asn1SequenceOf substrs = (Asn1SequenceOf) sub.get_Renamed(1);
toReturn = ((Asn1Tagged) substrs.get_Renamed(index / 2)).getIdentifier().Tag;
index++;
}
else
{
//return substring value
Asn1SequenceOf substrs = (Asn1SequenceOf) sub.get_Renamed(1);
Asn1Tagged tag = (Asn1Tagged) substrs.get_Renamed(index / 2);
RfcLdapString value_Renamed = (RfcLdapString) tag.taggedValue();
toReturn = value_Renamed.stringValue();
index++;
}
if (index / 2 >= ((Asn1SequenceOf) sub.get_Renamed(1)).size())
{
hasMore = false;
}
}
else if (asn1 is RfcAttributeValueAssertion)
{
// components: =,>=,<=,~=
RfcAttributeValueAssertion assertion = (RfcAttributeValueAssertion) asn1;
if (index == - 1)
{
toReturn = assertion.AttributeDescription;
index = 1;
}
else if (index == 1)
{
toReturn = assertion.AssertionValue;
index = 2;
hasMore = false;
}
}
else if (asn1 is RfcMatchingRuleAssertion)
{
//Extensible match
RfcMatchingRuleAssertion exMatch = (RfcMatchingRuleAssertion) asn1;
if (index == - 1)
{
index = 0;
}
toReturn = ((Asn1OctetString) ((Asn1Tagged) exMatch.get_Renamed(index++)).taggedValue()).stringValue();
if (index > 2)
{
hasMore = false;
}
}
else if (asn1 is Asn1SetOf)
{
//AND and OR nested components
Asn1SetOf set_Renamed = (Asn1SetOf) asn1;
if (index == - 1)
{
index = 0;
}
toReturn = new FilterIterator(enclosingInstance,(Asn1Tagged) set_Renamed.get_Renamed(index++));
if (index >= set_Renamed.size())
{
hasMore = false;
}
}
else if (asn1 is Asn1Tagged)
{
//NOT nested component.
toReturn = new FilterIterator(enclosingInstance,(Asn1Tagged) asn1);
hasMore = false;
}
}
return toReturn;
}
}
public RfcFilter Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Asn1Tagged root;
/// <summary>indicates if the identifier for a component has been returned yet </summary>
internal bool tagReturned = false;
/// <summary>indexes the several parts a component may have </summary>
internal int index = - 1;
private bool hasMore = true;
public FilterIterator(RfcFilter enclosingInstance, Asn1Tagged root)
{
InitBlock(enclosingInstance);
this.root = root;
}
public virtual bool MoveNext()
{
return hasMore;
}
public void remove()
{
throw new NotSupportedException("Remove is not supported on a filter iterator");
}
}
/// <summary> This inner class will tokenize the components of an RFC 2254 search filter.</summary>
internal class FilterTokenizer
{
private void InitBlock(RfcFilter enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private RfcFilter enclosingInstance;
/// <summary> Reads either an operator, or an attribute, whichever is
/// next in the filter string.
///
///
/// If the next component is an attribute, it is read and stored in the
/// attr field of this class which may be retrieved with getAttr()
/// and a -1 is returned. Otherwise, the int value of the operator read is
/// returned.
/// </summary>
virtual public int OpOrAttr
{
get
{
int index;
if (offset >= filterLength)
{
//"Unexpected end of filter",
throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR);
}
int ret;
int testChar = filter[offset];
if (testChar == '&')
{
offset++;
ret = AND;
}
else if (testChar == '|')
{
offset++;
ret = OR;
}
else if (testChar == '!')
{
offset++;
ret = NOT;
}
else
{
if (filter.Substring(offset).StartsWith(":=") == true)
{
throw new LdapLocalException(ExceptionMessages.NO_MATCHING_RULE, LdapException.FILTER_ERROR);
}
if (filter.Substring(offset).StartsWith("::=") == true || filter.Substring(offset).StartsWith(":::=") == true)
{
throw new LdapLocalException(ExceptionMessages.NO_DN_NOR_MATCHING_RULE, LdapException.FILTER_ERROR);
}
// get first component of 'item' (attr or :dn or :matchingrule)
String delims = "=~<>()";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (delims.IndexOf((Char) filter[offset]) == - 1 && filter.Substring(offset).StartsWith(":=") == false)
{
sb.Append(filter[offset++]);
}
attr = sb.ToString().Trim();
// is there an attribute name specified in the filter ?
if (attr.Length == 0 || attr[0] == ';')
{
throw new LdapLocalException(ExceptionMessages.NO_ATTRIBUTE_NAME, LdapException.FILTER_ERROR);
}
for (index = 0; index < attr.Length; index++)
{
char atIndex = attr[index];
if (!(Char.IsLetterOrDigit(atIndex) || atIndex == '-' || atIndex == '.' || atIndex == ';' || atIndex == ':'))
{
if (atIndex == '\\')
{
throw new LdapLocalException(ExceptionMessages.INVALID_ESC_IN_DESCR, LdapException.FILTER_ERROR);
}
else
{
throw new LdapLocalException(ExceptionMessages.INVALID_CHAR_IN_DESCR, new object[]{atIndex}, LdapException.FILTER_ERROR);
}
}
}
// is there an option specified in the filter ?
index = attr.IndexOf((Char) ';');
if (index != - 1 && index == attr.Length - 1)
{
throw new LdapLocalException(ExceptionMessages.NO_OPTION, LdapException.FILTER_ERROR);
}
ret = - 1;
}
return ret;
}
}
/// <summary> Reads an RFC 2251 filter type from the filter string and returns its
/// int value.
/// </summary>
virtual public int FilterType
{
get
{
if (offset >= filterLength)
{
//"Unexpected end of filter",
throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR);
}
int ret;
if (filter.Substring(offset).StartsWith(">="))
{
offset += 2;
ret = GREATER_OR_EQUAL;
}
else if (filter.Substring(offset).StartsWith("<="))
{
offset += 2;
ret = LESS_OR_EQUAL;
}
else if (filter.Substring(offset).StartsWith("~="))
{
offset += 2;
ret = APPROX_MATCH;
}
else if (filter.Substring(offset).StartsWith(":="))
{
offset += 2;
ret = EXTENSIBLE_MATCH;
}
else if (filter[offset] == '=')
{
offset++;
ret = EQUALITY_MATCH;
}
else
{
//"Invalid comparison operator",
throw new LdapLocalException(ExceptionMessages.INVALID_FILTER_COMPARISON, LdapException.FILTER_ERROR);
}
return ret;
}
}
/// <summary> Reads a value from a filter string.</summary>
virtual public String Value
{
get
{
if (offset >= filterLength)
{
//"Unexpected end of filter",
throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR);
}
int idx = filter.IndexOf((Char) ')', offset);
if (idx == - 1)
{
idx = filterLength;
}
String ret = filter.Substring(offset, (idx) - (offset));
offset = idx;
return ret;
}
}
/// <summary> Returns the current attribute identifier.</summary>
virtual public String Attr
{
get
{
return attr;
}
}
public RfcFilter Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
//*************************************************************************
// Private variables
//*************************************************************************
private String filter; // The filter string to parse
private String attr; // Name of the attribute just parsed
private int offset; // Offset pointer into the filter string
private int filterLength; // Length of the filter string to parse
//*************************************************************************
// Constructor
//*************************************************************************
/// <summary> Constructs a FilterTokenizer for a filter.</summary>
public FilterTokenizer(RfcFilter enclosingInstance, String filter)
{
InitBlock(enclosingInstance);
this.filter = filter;
offset = 0;
filterLength = filter.Length;
return ;
}
//*************************************************************************
// Tokenizer methods
//*************************************************************************
/// <summary> Reads the current char and throws an Exception if it is not a left
/// parenthesis.
/// </summary>
public void getLeftParen()
{
if (offset >= filterLength)
{
//"Unexpected end of filter",
throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR);
}
if (filter[offset++] != '(')
{
//"Missing left paren",
throw new LdapLocalException(ExceptionMessages.EXPECTING_LEFT_PAREN, new object[]{filter[offset -= 1]}, LdapException.FILTER_ERROR);
}
return ;
}
/// <summary> Reads the current char and throws an Exception if it is not a right
/// parenthesis.
/// </summary>
public void getRightParen()
{
if (offset >= filterLength)
{
//"Unexpected end of filter",
throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR);
}
if (filter[offset++] != ')')
{
//"Missing right paren",
throw new LdapLocalException(ExceptionMessages.EXPECTING_RIGHT_PAREN, new object[]{filter[offset - 1]}, LdapException.FILTER_ERROR);
}
return ;
}
/// <summary> Return the current char without advancing the offset pointer. This is
/// used by ParseFilterList when determining if there are any more
/// Filters in the list.
/// </summary>
public char peekChar()
{
if (offset >= filterLength)
{
//"Unexpected end of filter",
throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR);
}
return filter[offset];
}
}
}
}
| |
/*!
@file
@author Generate utility by Albert Semenov
@date 01/2009
@module
*/
using System;
using System.Runtime.InteropServices;
namespace MyGUI.Sharp
{
public class ItemBox :
DDContainer
{
#region ItemBox
protected override string GetWidgetType() { return "ItemBox"; }
internal static BaseWidget RequestWrapItemBox(BaseWidget _parent, IntPtr _widget)
{
ItemBox widget = new ItemBox();
widget.WrapWidget(_parent, _widget);
return widget;
}
internal static BaseWidget RequestCreateItemBox(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name)
{
ItemBox widget = new ItemBox();
widget.CreateWidgetImpl(_parent, _style, _skin, _coord, _align, _layer, _name);
return widget;
}
#endregion
//InsertPoint
#region Event NotifyItem
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseNotifyItem(IntPtr _native, bool _advise);
public delegate void HandleNotifyItem(
ItemBox _sender,
ref IBNotifyItemData _info);
private HandleNotifyItem mEventNotifyItem;
public event HandleNotifyItem EventNotifyItem
{
add
{
if (ExportEventNotifyItem.mDelegate == null)
{
ExportEventNotifyItem.mDelegate = new ExportEventNotifyItem.ExportHandle(OnExportNotifyItem);
ExportEventNotifyItem.ExportItemBoxEvent_DelegateNotifyItem(ExportEventNotifyItem.mDelegate);
}
if (mEventNotifyItem == null)
ExportItemBoxEvent_AdviseNotifyItem(Native, true);
mEventNotifyItem += value;
}
remove
{
mEventNotifyItem -= value;
if (mEventNotifyItem == null)
ExportItemBoxEvent_AdviseNotifyItem(Native, false);
}
}
private struct ExportEventNotifyItem
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateNotifyItem(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
[In] ref IBNotifyItemData _info);
public static ExportHandle mDelegate;
}
private static void OnExportNotifyItem(
IntPtr _sender,
ref IBNotifyItemData _info)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventNotifyItem != null)
sender.mEventNotifyItem(
sender ,
ref _info);
}
#endregion
#region Event MouseItemActivate
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseMouseItemActivate(IntPtr _native, bool _advise);
public delegate void HandleMouseItemActivate(
ItemBox _sender,
uint _index);
private HandleMouseItemActivate mEventMouseItemActivate;
public event HandleMouseItemActivate EventMouseItemActivate
{
add
{
if (ExportEventMouseItemActivate.mDelegate == null)
{
ExportEventMouseItemActivate.mDelegate = new ExportEventMouseItemActivate.ExportHandle(OnExportMouseItemActivate);
ExportEventMouseItemActivate.ExportItemBoxEvent_DelegateMouseItemActivate(ExportEventMouseItemActivate.mDelegate);
}
if (mEventMouseItemActivate == null)
ExportItemBoxEvent_AdviseMouseItemActivate(Native, true);
mEventMouseItemActivate += value;
}
remove
{
mEventMouseItemActivate -= value;
if (mEventMouseItemActivate == null)
ExportItemBoxEvent_AdviseMouseItemActivate(Native, false);
}
}
private struct ExportEventMouseItemActivate
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateMouseItemActivate(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
uint _index);
public static ExportHandle mDelegate;
}
private static void OnExportMouseItemActivate(
IntPtr _sender,
uint _index)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventMouseItemActivate != null)
sender.mEventMouseItemActivate(
sender ,
_index);
}
#endregion
#region Event ChangeItemPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseChangeItemPosition(IntPtr _native, bool _advise);
public delegate void HandleChangeItemPosition(
ItemBox _sender,
uint _index);
private HandleChangeItemPosition mEventChangeItemPosition;
public event HandleChangeItemPosition EventChangeItemPosition
{
add
{
if (ExportEventChangeItemPosition.mDelegate == null)
{
ExportEventChangeItemPosition.mDelegate = new ExportEventChangeItemPosition.ExportHandle(OnExportChangeItemPosition);
ExportEventChangeItemPosition.ExportItemBoxEvent_DelegateChangeItemPosition(ExportEventChangeItemPosition.mDelegate);
}
if (mEventChangeItemPosition == null)
ExportItemBoxEvent_AdviseChangeItemPosition(Native, true);
mEventChangeItemPosition += value;
}
remove
{
mEventChangeItemPosition -= value;
if (mEventChangeItemPosition == null)
ExportItemBoxEvent_AdviseChangeItemPosition(Native, false);
}
}
private struct ExportEventChangeItemPosition
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateChangeItemPosition(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
uint _index);
public static ExportHandle mDelegate;
}
private static void OnExportChangeItemPosition(
IntPtr _sender,
uint _index)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventChangeItemPosition != null)
sender.mEventChangeItemPosition(
sender ,
_index);
}
#endregion
#region Event SelectItemAccept
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseSelectItemAccept(IntPtr _native, bool _advise);
public delegate void HandleSelectItemAccept(
ItemBox _sender,
uint _index);
private HandleSelectItemAccept mEventSelectItemAccept;
public event HandleSelectItemAccept EventSelectItemAccept
{
add
{
if (ExportEventSelectItemAccept.mDelegate == null)
{
ExportEventSelectItemAccept.mDelegate = new ExportEventSelectItemAccept.ExportHandle(OnExportSelectItemAccept);
ExportEventSelectItemAccept.ExportItemBoxEvent_DelegateSelectItemAccept(ExportEventSelectItemAccept.mDelegate);
}
if (mEventSelectItemAccept == null)
ExportItemBoxEvent_AdviseSelectItemAccept(Native, true);
mEventSelectItemAccept += value;
}
remove
{
mEventSelectItemAccept -= value;
if (mEventSelectItemAccept == null)
ExportItemBoxEvent_AdviseSelectItemAccept(Native, false);
}
}
private struct ExportEventSelectItemAccept
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateSelectItemAccept(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
uint _index);
public static ExportHandle mDelegate;
}
private static void OnExportSelectItemAccept(
IntPtr _sender,
uint _index)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventSelectItemAccept != null)
sender.mEventSelectItemAccept(
sender ,
_index);
}
#endregion
#region Request DrawItem
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseDrawItem(IntPtr _native, bool _advise);
public delegate void HandleDrawItem(
ItemBox _sender,
Widget _item,
ref IBDrawItemInfo _info);
private HandleDrawItem mEventDrawItem;
public event HandleDrawItem RequestDrawItem
{
add
{
if (ExportEventDrawItem.mDelegate == null)
{
ExportEventDrawItem.mDelegate = new ExportEventDrawItem.ExportHandle(OnExportDrawItem);
ExportEventDrawItem.ExportItemBoxEvent_DelegateDrawItem(ExportEventDrawItem.mDelegate);
}
if (mEventDrawItem == null)
ExportItemBoxEvent_AdviseDrawItem(Native, true);
mEventDrawItem += value;
}
remove
{
mEventDrawItem -= value;
if (mEventDrawItem == null)
ExportItemBoxEvent_AdviseDrawItem(Native, false);
}
}
private struct ExportEventDrawItem
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateDrawItem(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
IntPtr _item,
[In] ref IBDrawItemInfo _info);
public static ExportHandle mDelegate;
}
private static void OnExportDrawItem(
IntPtr _sender,
IntPtr _item,
ref IBDrawItemInfo _info)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventDrawItem != null)
sender.mEventDrawItem(
sender ,
(Widget)BaseWidget.GetByNative(_item),
ref _info);
}
#endregion
#region Request CoordItem
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseCoordItem(IntPtr _native, bool _advise);
public delegate void HandleCoordItem(
ItemBox _sender,
ref IntCoord _coord,
bool _drag);
private HandleCoordItem mEventCoordItem;
public event HandleCoordItem RequestCoordItem
{
add
{
if (ExportEventCoordItem.mDelegate == null)
{
ExportEventCoordItem.mDelegate = new ExportEventCoordItem.ExportHandle(OnExportCoordItem);
ExportEventCoordItem.ExportItemBoxEvent_DelegateCoordItem(ExportEventCoordItem.mDelegate);
}
if (mEventCoordItem == null)
ExportItemBoxEvent_AdviseCoordItem(Native, true);
mEventCoordItem += value;
}
remove
{
mEventCoordItem -= value;
if (mEventCoordItem == null)
ExportItemBoxEvent_AdviseCoordItem(Native, false);
}
}
private struct ExportEventCoordItem
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateCoordItem(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
ref IntCoord _coord,
[MarshalAs(UnmanagedType.U1)] bool _drag);
public static ExportHandle mDelegate;
}
private static void OnExportCoordItem(
IntPtr _sender,
ref IntCoord _coord,
bool _drag)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventCoordItem != null)
sender.mEventCoordItem(
sender ,
ref _coord,
_drag);
}
#endregion
#region Request CreateWidgetItem
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBoxEvent_AdviseCreateWidgetItem(IntPtr _native, bool _advise);
public delegate void HandleCreateWidgetItem(
ItemBox _sender,
Widget _item);
private HandleCreateWidgetItem mEventCreateWidgetItem;
public event HandleCreateWidgetItem RequestCreateWidgetItem
{
add
{
if (ExportEventCreateWidgetItem.mDelegate == null)
{
ExportEventCreateWidgetItem.mDelegate = new ExportEventCreateWidgetItem.ExportHandle(OnExportCreateWidgetItem);
ExportEventCreateWidgetItem.ExportItemBoxEvent_DelegateCreateWidgetItem(ExportEventCreateWidgetItem.mDelegate);
}
if (mEventCreateWidgetItem == null)
ExportItemBoxEvent_AdviseCreateWidgetItem(Native, true);
mEventCreateWidgetItem += value;
}
remove
{
mEventCreateWidgetItem -= value;
if (mEventCreateWidgetItem == null)
ExportItemBoxEvent_AdviseCreateWidgetItem(Native, false);
}
}
private struct ExportEventCreateWidgetItem
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportItemBoxEvent_DelegateCreateWidgetItem(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender,
IntPtr _item);
public static ExportHandle mDelegate;
}
private static void OnExportCreateWidgetItem(
IntPtr _sender,
IntPtr _item)
{
ItemBox sender = (ItemBox)BaseWidget.GetByNative(_sender);
if (sender.mEventCreateWidgetItem != null)
sender.mEventCreateWidgetItem(
sender ,
(Widget)BaseWidget.GetByNative(_item));
}
#endregion
#region Method GetWidgetByIndex
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportItemBox_GetWidgetByIndex__index(IntPtr _native,
uint _index);
public Widget GetWidgetByIndex(
uint _index)
{
return (Widget)BaseWidget.GetByNative(ExportItemBox_GetWidgetByIndex__index(Native,
_index));
}
#endregion
#region Method GetIndexByWidget
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportItemBox_GetIndexByWidget__widget(IntPtr _native,
IntPtr _widget);
public uint GetIndexByWidget(
Widget _widget)
{
return ExportItemBox_GetIndexByWidget__widget(Native,
_widget.Native);
}
#endregion
#region Method ClearIndexSelected
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_ClearIndexSelected(IntPtr _native);
public void ClearIndexSelected( )
{
ExportItemBox_ClearIndexSelected(Native);
}
#endregion
#region Method RedrawAllItems
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_RedrawAllItems(IntPtr _native);
public void RedrawAllItems( )
{
ExportItemBox_RedrawAllItems(Native);
}
#endregion
#region Method RedrawItemAt
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_RedrawItemAt__index(IntPtr _native,
uint _index);
public void RedrawItemAt(
uint _index)
{
ExportItemBox_RedrawItemAt__index(Native,
_index);
}
#endregion
#region Method RemoveAllItems
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_RemoveAllItems(IntPtr _native);
public void RemoveAllItems( )
{
ExportItemBox_RemoveAllItems(Native);
}
#endregion
#region Method RemoveItemAt
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_RemoveItemAt__index(IntPtr _native,
uint _index);
public void RemoveItemAt(
uint _index)
{
ExportItemBox_RemoveItemAt__index(Native,
_index);
}
#endregion
#region Method AddItem
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_AddItem(IntPtr _native);
public void AddItem( )
{
ExportItemBox_AddItem(Native);
}
#endregion
#region Method InsertItemAt
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_InsertItemAt__index(IntPtr _native,
uint _index);
public void InsertItemAt(
uint _index)
{
ExportItemBox_InsertItemAt__index(Native,
_index);
}
#endregion
#region Property ViewOffset
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportItemBox_GetViewOffset(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_SetViewOffset(IntPtr _widget, [In] ref IntPoint _value);
public IntPoint ViewOffset
{
get { return (IntPoint)Marshal.PtrToStructure(ExportItemBox_GetViewOffset(Native), typeof(IntPoint)); }
set { ExportItemBox_SetViewOffset(Native, ref value); }
}
#endregion
#region Property WidgetDrag
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportItemBox_GetWidgetDrag(IntPtr _native);
public Widget WidgetDrag
{
get { return (Widget)BaseWidget.GetByNative(ExportItemBox_GetWidgetDrag(Native)); }
}
#endregion
#region Property VerticalAlignment
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportItemBox_GetVerticalAlignment(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_SetVerticalAlignment(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool VerticalAlignment
{
get { return ExportItemBox_GetVerticalAlignment(Native); }
set { ExportItemBox_SetVerticalAlignment(Native, value); }
}
#endregion
#region Property IndexSelected
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportItemBox_GetIndexSelected(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportItemBox_SetIndexSelected(IntPtr _widget, uint _value);
public uint IndexSelected
{
get { return ExportItemBox_GetIndexSelected(Native); }
set { ExportItemBox_SetIndexSelected(Native, value); }
}
#endregion
#region Property ItemCount
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportItemBox_GetItemCount(IntPtr _native);
public uint ItemCount
{
get { return ExportItemBox_GetItemCount(Native); }
}
#endregion
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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.Data;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Net;
namespace Reporting.Data
{
/// <summary>
/// FileDirDataReader handles reading log files
/// </summary>
public class FileDirDataReader : IDataReader
{
FileDirConnection _fdconn;
FileDirCommand _fdcmd;
System.Data.CommandBehavior _behavior;
IEnumerator _ie; // enumerator thru rows
string _FilePattern; // FilePattern from _fdcmd
string _DirectoryPattern; // DirectoryPattern from _fdcmd
bool _TrimEmpty; // Directories with no files will be omitted from result set
// file data
object[] _Data; // data values of the columns
ArrayList _RowData; // row data
// column information; this is fixed for all instances
static string[] _Names; // names of the columns
static Type[] _Types; // types of the columns
// the location of the columns
static readonly int COLUMN_NAME=0;
static readonly int COLUMN_SIZE=1;
static readonly int COLUMN_CREATIONTIME=2;
static readonly int COLUMN_LASTACCESSTIME=3;
static readonly int COLUMN_LASTWRITETIME=4;
static readonly int COLUMN_ID=5;
static readonly int COLUMN_PARENTID=6;
static readonly int COLUMN_ISDIRECTORY=7;
static readonly int COLUMN_EXTENSION=8;
static readonly int COLUMN_FULLNAME=9;
static readonly int COLUMN_COUNT=10;
static FileDirDataReader()
{
// Add the names (fixed for type of DataReader depending on the columns parameter)
Type dttype = DateTime.MinValue.GetType(); // work variable for getting the type
Type stype = "".GetType();
Type itype = int.MinValue.GetType();
Type ltype = long.MinValue.GetType();
Type btype = new bool().GetType();
_Names = new string[COLUMN_COUNT];
_Names[COLUMN_NAME]="Name";
_Names[COLUMN_SIZE]="Size";
_Names[COLUMN_CREATIONTIME]="CreationTime";
_Names[COLUMN_LASTACCESSTIME]="LastAccessTime";
_Names[COLUMN_LASTWRITETIME]="LastWriteTime";
_Names[COLUMN_ID]="ID";
_Names[COLUMN_PARENTID]="ParentID";
_Names[COLUMN_ISDIRECTORY]="IsDirectory";
_Names[COLUMN_EXTENSION]="Extension";
_Names[COLUMN_FULLNAME]="FullName";
_Types = new Type[COLUMN_COUNT];
_Types[COLUMN_NAME]=stype;
_Types[COLUMN_SIZE]=ltype;
_Types[COLUMN_CREATIONTIME]=dttype;
_Types[COLUMN_LASTACCESSTIME]=dttype;
_Types[COLUMN_LASTWRITETIME]=dttype;
_Types[COLUMN_ID]=itype;
_Types[COLUMN_PARENTID]=itype;
_Types[COLUMN_ISDIRECTORY]=btype;
_Types[COLUMN_EXTENSION]=stype;
_Types[COLUMN_FULLNAME]=stype;
}
public FileDirDataReader(System.Data.CommandBehavior behavior, FileDirConnection conn, FileDirCommand cmd)
{
_fdconn = conn;
_fdcmd = cmd;
_behavior = behavior;
_FilePattern = _fdcmd.FilePattern;
_DirectoryPattern = _fdcmd.DirectoryPattern;
_TrimEmpty = _fdcmd.TrimEmpty;
_Data = new object[_Names.Length]; // allocate enough room for data
if (behavior == CommandBehavior.SchemaOnly)
return;
string dir = _fdcmd.Directory;
if (dir == null)
throw new Exception("Directory parameter must be specified.");
// Populate the data array
_RowData = new ArrayList();
PopulateData(new DirectoryInfo(dir), -1);
_ie = _RowData.GetEnumerator();
}
long PopulateData(DirectoryInfo di, int parent)
{
long size=0;
// Create a new row for this directory
object[] prow = new object[_Names.Length];
_RowData.Add(prow);
int rowcount = _RowData.Count - 1;
prow[COLUMN_NAME] = di.Name;
prow[COLUMN_ISDIRECTORY] = true;
prow[COLUMN_ID] = rowcount;
prow[COLUMN_PARENTID] = parent >= 0? (object) parent: (object) null;
prow[COLUMN_CREATIONTIME] = di.CreationTime;
prow[COLUMN_LASTACCESSTIME] = di.LastAccessTime;
prow[COLUMN_LASTWRITETIME] = di.LastWriteTime;
prow[COLUMN_EXTENSION] = di.Extension;
prow[COLUMN_FULLNAME] = di.FullName;
parent = rowcount; // set the new parent
FileInfo[] afi = _FilePattern == null? di.GetFiles(): di.GetFiles(_FilePattern);
foreach (FileInfo fi in afi)
{
// Create a new row for this file
object[] row = new object[_Names.Length];
_RowData.Add(row);
row[COLUMN_NAME] = fi.Name;
row[COLUMN_ISDIRECTORY] = false;
row[COLUMN_ID] = _RowData.Count - 1;
row[COLUMN_PARENTID] = (object) parent;
row[COLUMN_CREATIONTIME] = fi.CreationTime;
row[COLUMN_LASTACCESSTIME] = fi.LastAccessTime;
row[COLUMN_LASTWRITETIME] = fi.LastWriteTime;
row[COLUMN_EXTENSION] = fi.Extension;
row[COLUMN_FULLNAME] = fi.FullName;
row[COLUMN_SIZE] = fi.Length;
size += fi.Length;
}
DirectoryInfo[] adi = _DirectoryPattern == null? di.GetDirectories(): di.GetDirectories(_DirectoryPattern);
foreach (DirectoryInfo sdi in adi)
{
size += PopulateData(sdi, parent);
}
prow[COLUMN_SIZE] = size;
// If a directory has no files below it we (optionally) can omit the directory as well
if (_TrimEmpty && parent >= 0 && _RowData.Count - 1 == rowcount)
{
_RowData.RemoveAt(rowcount);
}
return size;
}
#region IDataReader Members
public int RecordsAffected
{
get
{
return 0;
}
}
public bool IsClosed
{
get
{
return _ie == null;
}
}
public bool NextResult()
{
return false;
}
public void Close()
{
_ie = null;
_RowData = null;
_Data = null;
}
public bool Read()
{
if (_ie == null || !_ie.MoveNext())
return false;
_Data = _ie.Current as object[];
return true;
}
public int Depth
{
get
{
return 0;
}
}
public DataTable GetSchemaTable()
{
return null;
}
#endregion
#region IDisposable Members
public void Dispose()
{
this.Close();
}
#endregion
#region IDataRecord Members
public int GetInt32(int i)
{
return Convert.ToInt32(_Data[i]);
}
public object this[string name]
{
get
{
int ci = this.GetOrdinal(name);
return _Data[ci];
}
}
object System.Data.IDataRecord.this[int i]
{
get
{
return _Data[i];
}
}
public object GetValue(int i)
{
return _Data[i];
}
public bool IsDBNull(int i)
{
return _Data[i] == null;
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException("GetBytes not implemented.");
}
public byte GetByte(int i)
{
return Convert.ToByte(_Data[i]);
}
public Type GetFieldType(int i)
{
return _Types[i];
}
public decimal GetDecimal(int i)
{
return Convert.ToDecimal(_Data[i]);
}
public int GetValues(object[] values)
{
int i;
for (i=0; i < values.Length; i++)
{
values[i] = i >= _Data.Length? System.DBNull.Value: _Data[i];
}
return Math.Min(values.Length, _Data.Length);
}
public string GetName(int i)
{
return _Names[i] as string;
}
public int FieldCount
{
get
{
return _Data.Length;
}
}
public long GetInt64(int i)
{
return Convert.ToInt64(_Data[i]);
}
public double GetDouble(int i)
{
return Convert.ToDouble(_Data[i]);
}
public bool GetBoolean(int i)
{
return Convert.ToBoolean(_Data[i]);
}
public Guid GetGuid(int i)
{
throw new NotImplementedException("GetGuid not implemented.");
}
public DateTime GetDateTime(int i)
{
return Convert.ToDateTime(_Data[i]);
}
public int GetOrdinal(string name)
{
int ci=0;
// do case sensitive lookup
foreach (string cname in _Names)
{
if (cname == name)
return ci;
ci++;
}
// do case insensitive lookup
ci=0;
name = name.ToLower();
foreach (string cname in _Names)
{
if (cname.ToLower() == name)
return ci;
ci++;
}
throw new ArgumentException(string.Format("Column '{0}' not known.", name));
}
public string GetDataTypeName(int i)
{
Type t = _Types[i] as Type;
return t.ToString();
}
public float GetFloat(int i)
{
return Convert.ToSingle(_Data[i]);
}
public IDataReader GetData(int i)
{
throw new NotImplementedException("GetData not implemented.");
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException("GetChars not implemented.");
}
public string GetString(int i)
{
return Convert.ToString(_Data[i]);
}
public char GetChar(int i)
{
return Convert.ToChar(_Data[i]);
}
public short GetInt16(int i)
{
return Convert.ToInt16(_Data[i]);
}
#endregion
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.10.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google App State API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/games/services/web/api/states'>Google App State API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20160310 (434)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/games/services/web/api/states'>
* https://developers.google.com/games/services/web/api/states</a>
* <tr><th>Discovery Name<td>appstate
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google App State API can be found at
* <a href='https://developers.google.com/games/services/web/api/states'>https://developers.google.com/games/services/web/api/states</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.AppState.v1
{
/// <summary>The AppState Service.</summary>
public class AppStateService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public AppStateService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public AppStateService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
states = new StatesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "appstate"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/appstate/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "appstate/v1/"; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Google App State API.</summary>
public class Scope
{
/// <summary>View and manage your data for this application</summary>
public static string Appstate = "https://www.googleapis.com/auth/appstate";
}
private readonly StatesResource states;
/// <summary>Gets the States resource.</summary>
public virtual StatesResource States
{
get { return states; }
}
}
///<summary>A base abstract class for AppState requests.</summary>
public abstract class AppStateBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new AppStateBaseServiceRequest instance.</summary>
protected AppStateBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes AppState parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "states" collection of methods.</summary>
public class StatesResource
{
private const string Resource = "states";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public StatesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Clears (sets to empty) the data for the passed key if and only if the passed version matches the
/// currently stored version. This method results in a conflict error on version mismatch.</summary>
/// <param name="stateKey">The key for the data to be retrieved.</param>
public virtual ClearRequest Clear(int stateKey)
{
return new ClearRequest(service, stateKey);
}
/// <summary>Clears (sets to empty) the data for the passed key if and only if the passed version matches the
/// currently stored version. This method results in a conflict error on version mismatch.</summary>
public class ClearRequest : AppStateBaseServiceRequest<Google.Apis.AppState.v1.Data.WriteResult>
{
/// <summary>Constructs a new Clear request.</summary>
public ClearRequest(Google.Apis.Services.IClientService service, int stateKey)
: base(service)
{
StateKey = stateKey;
InitParameters();
}
/// <summary>The key for the data to be retrieved.</summary>
/// [minimum: 0]
/// [maximum: 3]
[Google.Apis.Util.RequestParameterAttribute("stateKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual int StateKey { get; private set; }
/// <summary>The version of the data to be cleared. Version strings are returned by the server.</summary>
[Google.Apis.Util.RequestParameterAttribute("currentDataVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CurrentDataVersion { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "clear"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "states/{stateKey}/clear"; }
}
/// <summary>Initializes Clear parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"stateKey", new Google.Apis.Discovery.Parameter
{
Name = "stateKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"currentDataVersion", new Google.Apis.Discovery.Parameter
{
Name = "currentDataVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes a key and the data associated with it. The key is removed and no longer counts against the
/// key quota. Note that since this method is not safe in the face of concurrent modifications, it should only
/// be used for development and testing purposes. Invoking this method in shipping code can result in data loss
/// and data corruption.</summary>
/// <param name="stateKey">The key for the data to be retrieved.</param>
public virtual DeleteRequest Delete(int stateKey)
{
return new DeleteRequest(service, stateKey);
}
/// <summary>Deletes a key and the data associated with it. The key is removed and no longer counts against the
/// key quota. Note that since this method is not safe in the face of concurrent modifications, it should only
/// be used for development and testing purposes. Invoking this method in shipping code can result in data loss
/// and data corruption.</summary>
public class DeleteRequest : AppStateBaseServiceRequest<string>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, int stateKey)
: base(service)
{
StateKey = stateKey;
InitParameters();
}
/// <summary>The key for the data to be retrieved.</summary>
/// [minimum: 0]
/// [maximum: 3]
[Google.Apis.Util.RequestParameterAttribute("stateKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual int StateKey { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "states/{stateKey}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"stateKey", new Google.Apis.Discovery.Parameter
{
Name = "stateKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Retrieves the data corresponding to the passed key. If the key does not exist on the server, an
/// HTTP 404 will be returned.</summary>
/// <param name="stateKey">The key for the data to be retrieved.</param>
public virtual GetRequest Get(int stateKey)
{
return new GetRequest(service, stateKey);
}
/// <summary>Retrieves the data corresponding to the passed key. If the key does not exist on the server, an
/// HTTP 404 will be returned.</summary>
public class GetRequest : AppStateBaseServiceRequest<Google.Apis.AppState.v1.Data.GetResponse>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, int stateKey)
: base(service)
{
StateKey = stateKey;
InitParameters();
}
/// <summary>The key for the data to be retrieved.</summary>
/// [minimum: 0]
/// [maximum: 3]
[Google.Apis.Util.RequestParameterAttribute("stateKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual int StateKey { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "states/{stateKey}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"stateKey", new Google.Apis.Discovery.Parameter
{
Name = "stateKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists all the states keys, and optionally the state data.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists all the states keys, and optionally the state data.</summary>
public class ListRequest : AppStateBaseServiceRequest<Google.Apis.AppState.v1.Data.ListResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Whether to include the full data in addition to the version number</summary>
/// [default: false]
[Google.Apis.Util.RequestParameterAttribute("includeData", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> IncludeData { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "states"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"includeData", new Google.Apis.Discovery.Parameter
{
Name = "includeData",
IsRequired = false,
ParameterType = "query",
DefaultValue = "false",
Pattern = null,
});
}
}
/// <summary>Update the data associated with the input key if and only if the passed version matches the
/// currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is
/// 128KB.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="stateKey">The key for the data to be retrieved.</param>
public virtual UpdateRequest Update(Google.Apis.AppState.v1.Data.UpdateRequest body, int stateKey)
{
return new UpdateRequest(service, body, stateKey);
}
/// <summary>Update the data associated with the input key if and only if the passed version matches the
/// currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is
/// 128KB.</summary>
public class UpdateRequest : AppStateBaseServiceRequest<Google.Apis.AppState.v1.Data.WriteResult>
{
/// <summary>Constructs a new Update request.</summary>
public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.AppState.v1.Data.UpdateRequest body, int stateKey)
: base(service)
{
StateKey = stateKey;
Body = body;
InitParameters();
}
/// <summary>The key for the data to be retrieved.</summary>
/// [minimum: 0]
/// [maximum: 3]
[Google.Apis.Util.RequestParameterAttribute("stateKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual int StateKey { get; private set; }
/// <summary>The version of the app state your application is attempting to update. If this does not match
/// the current version, this method will return a conflict error. If there is no data stored on the server
/// for this key, the update will succeed irrespective of the value of this parameter.</summary>
[Google.Apis.Util.RequestParameterAttribute("currentStateVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CurrentStateVersion { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.AppState.v1.Data.UpdateRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "update"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PUT"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "states/{stateKey}"; }
}
/// <summary>Initializes Update parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"stateKey", new Google.Apis.Discovery.Parameter
{
Name = "stateKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"currentStateVersion", new Google.Apis.Discovery.Parameter
{
Name = "currentStateVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.AppState.v1.Data
{
/// <summary>This is a JSON template for an app state resource.</summary>
public class GetResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The current app state version.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("currentStateVersion")]
public virtual string CurrentStateVersion { get; set; }
/// <summary>The requested data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("data")]
public virtual string Data { get; set; }
/// <summary>Uniquely identifies the type of this resource. Value is always the fixed string
/// appstate#getResponse.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The key for the data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stateKey")]
public virtual System.Nullable<int> StateKey { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This is a JSON template to convert a list-response for app state.</summary>
public class ListResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The app state data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<GetResponse> Items { get; set; }
/// <summary>Uniquely identifies the type of this resource. Value is always the fixed string
/// appstate#listResponse.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The maximum number of keys allowed for this user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maximumKeyCount")]
public virtual System.Nullable<int> MaximumKeyCount { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This is a JSON template for a requests which update app state</summary>
public class UpdateRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The new app state data that your application is trying to update with.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("data")]
public virtual string Data { get; set; }
/// <summary>Uniquely identifies the type of this resource. Value is always the fixed string
/// appstate#updateRequest.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This is a JSON template for an app state write result.</summary>
public class WriteResult : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The version of the data for this key on the server.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("currentStateVersion")]
public virtual string CurrentStateVersion { get; set; }
/// <summary>Uniquely identifies the type of this resource. Value is always the fixed string
/// appstate#writeResult.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The written key.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stateKey")]
public virtual System.Nullable<int> StateKey { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
//
// MetaPixel.cs
//
// Author:
// Stephane Delcroix <sdelcroix*novell.com>
//
// Copyright (C) 2008 Novell, Inc.
// Copyright (C) 2008 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections;
using Gtk;
using FSpot;
using FSpot.Extensions;
using FSpot.Widgets;
using FSpot.Filters;
using FSpot.UI.Dialog;
using Hyena;
using Mono.Unix;
namespace MetaPixelExtension {
public class MetaPixel: ICommand
{
[Glade.Widget] Gtk.Dialog metapixel_dialog;
[Glade.Widget] Gtk.HBox tagentry_box;
[Glade.Widget] Gtk.SpinButton icon_x_size;
[Glade.Widget] Gtk.SpinButton icon_y_size;
[Glade.Widget] Gtk.RadioButton tags_radio;
[Glade.Widget] Gtk.RadioButton current_radio;
FSpot.Widgets.TagEntry miniatures_tags;
string minidir_tmp;
public void Run (object o, EventArgs e) {
Log.Information ("Executing MetaPixel extension");
if (App.Instance.Organizer.SelectedPhotos ().Length == 0) {
InfoDialog (Catalog.GetString ("No selection available"),
Catalog.GetString ("This tool requires an active selection. Please select one or more pictures and try again"),
Gtk.MessageType.Error);
return;
} else {
//Check for MetaPixel executable
string output = "";
try {
System.Diagnostics.Process mp_check = new System.Diagnostics.Process ();
mp_check.StartInfo.RedirectStandardOutput = true;
mp_check.StartInfo.UseShellExecute = false;
mp_check.StartInfo.FileName = "metapixel";
mp_check.StartInfo.Arguments = "--version";
mp_check.Start ();
mp_check.WaitForExit ();
StreamReader sroutput = mp_check.StandardOutput;
output = sroutput.ReadLine ();
} catch (System.Exception) {
}
if (!System.Text.RegularExpressions.Regex.IsMatch (output, "^metapixel")) {
InfoDialog (Catalog.GetString ("Metapixel not available"),
Catalog.GetString ("The metapixel executable was not found in path. Please check that you have it installed and that you have permissions to execute it"),
Gtk.MessageType.Error);
return;
}
ShowDialog ();
}
}
public void ShowDialog () {
Glade.XML xml = new Glade.XML (null, "MetaPixel.glade", "metapixel_dialog", "f-spot");
xml.Autoconnect (this);
metapixel_dialog.Modal = false;
metapixel_dialog.TransientFor = null;
miniatures_tags = new FSpot.Widgets.TagEntry (App.Instance.Database.Tags, false);
miniatures_tags.UpdateFromTagNames (new string []{});
tagentry_box.Add (miniatures_tags);
metapixel_dialog.Response += on_dialog_response;
current_radio.Active = true;
tags_radio.Toggled += HandleTagsRadioToggled;
HandleTagsRadioToggled (null, null);
metapixel_dialog.ShowAll ();
}
void on_dialog_response (object obj, ResponseArgs args) {
if (args.ResponseId == ResponseType.Ok) {
create_mosaics ();
}
metapixel_dialog.Destroy ();
}
void create_mosaics () {
//Prepare the query
Db db = App.Instance.Database;
FSpot.PhotoQuery mini_query = new FSpot.PhotoQuery (db.Photos);
Photo [] photos;
if (tags_radio.Active) {
//Build tag array
ArrayList taglist = new ArrayList ();
foreach (string tag_name in miniatures_tags.GetTypedTagNames ()) {
Tag t = db.Tags.GetTagByName (tag_name);
if (t != null)
taglist.Add(t);
}
mini_query.Terms = FSpot.OrTerm.FromTags ((Tag []) taglist.ToArray (typeof (Tag)));
photos = mini_query.Photos;
} else {
photos = App.Instance.Organizer.Query.Photos;
}
if (photos.Length == 0) {
//There is no photo for the selected tags! :(
InfoDialog (Catalog.GetString ("No photos for the selection"),
Catalog.GetString ("The tags selected provided no pictures. Please select different tags"),
Gtk.MessageType.Error);
return;
}
//Create minis
ProgressDialog progress_dialog = null;
progress_dialog = new ProgressDialog (Catalog.GetString ("Creating miniatures"),
ProgressDialog.CancelButtonType.Stop,
photos.Length, metapixel_dialog);
minidir_tmp = System.IO.Path.GetTempFileName ();
System.IO.File.Delete (minidir_tmp);
System.IO.Directory.CreateDirectory (minidir_tmp);
minidir_tmp += "/";
//Call MetaPixel to create the minis
foreach (Photo p in photos) {
if (progress_dialog.Update (String.Format (Catalog.GetString ("Preparing photo \"{0}\""), p.Name))) {
progress_dialog.Destroy ();
DeleteTmp ();
return;
}
//FIXME should switch to retry/skip
if (!GLib.FileFactory.NewForUri (p.DefaultVersion.Uri).Exists) {
Log.WarningFormat (String.Format ("Couldn't access photo {0} while creating miniatures", p.DefaultVersion.Uri.LocalPath));
continue;
}
//FIXME Check if the picture's format is supproted (jpg, gif)
FilterSet filters = new FilterSet ();
filters.Add (new JpegFilter ());
FilterRequest freq = new FilterRequest (p.DefaultVersion.Uri);
filters.Convert (freq);
//We use photo id for minis, instead of photo names, to avoid duplicates
string minifile = minidir_tmp + p.Id.ToString() + System.IO.Path.GetExtension (p.DefaultVersion.Uri.ToString ());
string prepare_command = String.Format ("--prepare -w {0} -h {1} {2} {3} {4}tables.mxt",
icon_x_size.Text, //Minis width
icon_y_size.Text, //Minis height
GLib.Shell.Quote (freq.Current.LocalPath), //Source image
GLib.Shell.Quote (minifile), //Dest image
minidir_tmp); //Table file
Log.Debug ("Executing: metapixel " + prepare_command);
System.Diagnostics.Process mp_prep = System.Diagnostics.Process.Start ("metapixel", prepare_command);
mp_prep.WaitForExit ();
if (!System.IO.File.Exists (minifile)) {
Log.DebugFormat ("No mini? No party! {0}", minifile);
continue;
}
} //Finished preparing!
if (progress_dialog != null)
progress_dialog.Destroy ();
progress_dialog = null;
progress_dialog = new ProgressDialog (Catalog.GetString ("Creating photomosaics"),
ProgressDialog.CancelButtonType.Stop,
App.Instance.Organizer.SelectedPhotos ().Length, metapixel_dialog);
//Now create the mosaics!
uint error_count = 0;
foreach (Photo p in App.Instance.Organizer.SelectedPhotos ()) {
if (progress_dialog.Update (String.Format (Catalog.GetString ("Processing \"{0}\""), p.Name))) {
progress_dialog.Destroy ();
DeleteTmp ();
return;
}
//FIXME should switch to retry/skip
if (!GLib.FileFactory.NewForUri (p.DefaultVersion.Uri).Exists) {
Log.WarningFormat (String.Format ("Couldn't access photo {0} while creating mosaics", p.DefaultVersion.Uri.LocalPath));
error_count ++;
continue;
}
//FIXME Check if the picture's format is supproted (jpg, gif)
FilterSet filters = new FilterSet ();
filters.Add (new JpegFilter ());
FilterRequest freq = new FilterRequest (p.DefaultVersion.Uri);
filters.Convert (freq);
string name = GetVersionName (p);
System.Uri mosaic = GetUriForVersionName (p, name);
string mosaic_command = String.Format ("--metapixel -l {0} {1} {2}",
minidir_tmp,
GLib.Shell.Quote (freq.Current.LocalPath),
GLib.Shell.Quote (mosaic.LocalPath));
Log.Debug ("Executing: metapixel " + mosaic_command);
System.Diagnostics.Process mp_exe = System.Diagnostics.Process.Start ("metapixel", mosaic_command);
mp_exe.WaitForExit ();
if (!GLib.FileFactory.NewForUri (mosaic).Exists) {
Log.Warning ("Error in processing image " + p.Name);
error_count ++;
continue;
}
p.DefaultVersionId = p.AddVersion (mosaic, name, true);
p.Changes.DataChanged = true;
Core.Database.Photos.Commit (p);
} //Finished creating mosaics
if (progress_dialog != null)
progress_dialog.Destroy ();
string final_message = "Your mosaics have been generated as new versions of the pictures you selected";
if (error_count > 0)
final_message += String.Format (".\n{0} images out of {1} had errors",
error_count, App.Instance.Organizer.SelectedPhotos ().Length);
InfoDialog (Catalog.GetString ("PhotoMosaics generated!"),
Catalog.GetString (final_message),
(error_count == 0 ? Gtk.MessageType.Info : Gtk.MessageType.Warning));
DeleteTmp ();
}
private void HandleTagsRadioToggled (object o, EventArgs e) {
miniatures_tags.Sensitive = tags_radio.Active;
}
private static string GetVersionName (Photo p)
{
return GetVersionName (p, 1);
}
private static string GetVersionName (Photo p, int i)
{
string name = Catalog.GetPluralString ("PhotoMosaic", "PhotoMosaic ({0})", i);
name = String.Format (name, i);
if (p.VersionNameExists (name))
return GetVersionName (p, i + 1);
return name;
}
private System.Uri GetUriForVersionName (Photo p, string version_name)
{
string name_without_ext = System.IO.Path.GetFileNameWithoutExtension (p.Name);
return new System.Uri (System.IO.Path.Combine (DirectoryPath (p), name_without_ext
+ " (" + version_name + ")" + ".jpg"));
}
private static string DirectoryPath (Photo p)
{
System.Uri uri = p.VersionUri (Photo.OriginalVersionId);
return uri.Scheme + "://" + uri.Host + System.IO.Path.GetDirectoryName (uri.AbsolutePath);
}
private void DeleteTmp ()
{
//Clean temp workdir
DirectoryInfo dir = new DirectoryInfo(minidir_tmp);
FileInfo[] tmpfiles = dir.GetFiles();
foreach (FileInfo f in tmpfiles) {
if (System.IO.File.Exists (minidir_tmp + f.Name)) {
System.IO.File.Delete (minidir_tmp + f.Name);
}
}
if (System.IO.Directory.Exists (minidir_tmp)) {
System.IO.Directory.Delete(minidir_tmp);
}
}
private void InfoDialog (string title, string msg, Gtk.MessageType type) {
HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent,
type, ButtonsType.Ok, title, msg);
md.Run ();
md.Destroy ();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Net.Mail;
using System.Text;
namespace System.Net.Http.Headers
{
internal static class HeaderUtilities
{
private const string qualityName = "q";
internal const string ConnectionClose = "close";
internal static readonly TransferCodingHeaderValue TransferEncodingChunked =
new TransferCodingHeaderValue("chunked");
internal static readonly NameValueWithParametersHeaderValue ExpectContinue =
new NameValueWithParametersHeaderValue("100-continue");
internal const string BytesUnit = "bytes";
// Validator
internal static readonly Action<HttpHeaderValueCollection<string>, string> TokenValidator = ValidateToken;
internal static void SetQuality(ObjectCollection<NameValueHeaderValue> parameters, double? value)
{
Debug.Assert(parameters != null);
NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName);
if (value.HasValue)
{
// Note that even if we check the value here, we can't prevent a user from adding an invalid quality
// value using Parameters.Add(). Even if we would prevent the user from adding an invalid value
// using Parameters.Add() he could always add invalid values using HttpHeaders.AddWithoutValidation().
// So this check is really for convenience to show users that they're trying to add an invalid
// value.
if ((value < 0) || (value > 1))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo);
if (qualityParameter != null)
{
qualityParameter.Value = qualityString;
}
else
{
parameters.Add(new NameValueHeaderValue(qualityName, qualityString));
}
}
else
{
// Remove quality parameter
if (qualityParameter != null)
{
parameters.Remove(qualityParameter);
}
}
}
internal static double? GetQuality(ObjectCollection<NameValueHeaderValue> parameters)
{
Debug.Assert(parameters != null);
NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName);
if (qualityParameter != null)
{
// Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal
// separator is considered invalid (even if the current culture would allow it).
double qualityValue = 0;
if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint,
NumberFormatInfo.InvariantInfo, out qualityValue))
{
return qualityValue;
}
// If the stored value is an invalid quality value, just return null and log a warning.
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_invalid_quality, qualityParameter.Value));
}
return null;
}
internal static void CheckValidToken(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
if (HttpRuleParser.GetTokenLength(value, 0) != value.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static void CheckValidComment(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
int length = 0;
if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static void CheckValidQuotedString(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
int length = 0;
if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y) where T : class
{
return AreEqualCollections(x, y, null);
}
internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y, IEqualityComparer<T> comparer) where T : class
{
if (x == null)
{
return (y == null) || (y.Count == 0);
}
if (y == null)
{
return (x.Count == 0);
}
if (x.Count != y.Count)
{
return false;
}
if (x.Count == 0)
{
return true;
}
// We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually
// headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive.
bool[] alreadyFound = new bool[x.Count];
int i = 0;
foreach (var xItem in x)
{
Debug.Assert(xItem != null);
i = 0;
bool found = false;
foreach (var yItem in y)
{
if (!alreadyFound[i])
{
if (((comparer == null) && xItem.Equals(yItem)) ||
((comparer != null) && comparer.Equals(xItem, yItem)))
{
alreadyFound[i] = true;
found = true;
break;
}
}
i++;
}
if (!found)
{
return false;
}
}
// Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'.
// Otherwise the two collections can't be equal and we should not get here.
Debug.Assert(Contract.ForAll(alreadyFound, value => { return value; }),
"Expected all values in 'alreadyFound' to be true since collections are considered equal.");
return true;
}
internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues,
out bool separatorFound)
{
Debug.Assert(input != null);
Debug.Assert(startIndex <= input.Length); // it's OK if index == value.Length.
separatorFound = false;
int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
if ((current == input.Length) || (input[current] != ','))
{
return current;
}
// If we have a separator, skip the separator and all following whitespace. If we support
// empty values, continue until the current character is neither a separator nor a whitespace.
separatorFound = true;
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if (skipEmptyValues)
{
while ((current < input.Length) && (input[current] == ','))
{
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
return current;
}
internal static DateTimeOffset? GetDateTimeOffsetValue(string headerName, HttpHeaders store)
{
Debug.Assert(store != null);
object storedValue = store.GetParsedValues(headerName);
if (storedValue != null)
{
return (DateTimeOffset)storedValue;
}
return null;
}
internal static TimeSpan? GetTimeSpanValue(string headerName, HttpHeaders store)
{
Debug.Assert(store != null);
object storedValue = store.GetParsedValues(headerName);
if (storedValue != null)
{
return (TimeSpan)storedValue;
}
return null;
}
internal static bool TryParseInt32(string value, out int result) =>
TryParseInt32(value, 0, value.Length, out result);
internal static bool TryParseInt32(string value, int offset, int length, out int result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available
{
if (offset < 0 || length < 0 || offset > value.Length - length)
{
result = 0;
return false;
}
int tmpResult = 0;
int pos = offset, endPos = offset + length;
while (pos < endPos)
{
char c = value[pos++];
int digit = c - '0';
if ((uint)digit > 9 || // invalid digit
tmpResult > int.MaxValue / 10 || // will overflow when shifting digits
(tmpResult == int.MaxValue / 10 && digit > 7)) // will overflow when adding in digit
{
goto ReturnFalse; // Remove goto once https://github.com/dotnet/coreclr/issues/9692 is addressed
}
tmpResult = (tmpResult * 10) + digit;
}
result = tmpResult;
return true;
ReturnFalse:
result = 0;
return false;
}
internal static bool TryParseInt64(string value, int offset, int length, out long result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available
{
if (offset < 0 || length < 0 || offset > value.Length - length)
{
result = 0;
return false;
}
long tmpResult = 0;
int pos = offset, endPos = offset + length;
while (pos < endPos)
{
char c = value[pos++];
int digit = c - '0';
if ((uint)digit > 9 || // invalid digit
tmpResult > long.MaxValue / 10 || // will overflow when shifting digits
(tmpResult == long.MaxValue / 10 && digit > 7)) // will overflow when adding in digit
{
goto ReturnFalse; // Remove goto once https://github.com/dotnet/coreclr/issues/9692 is addressed
}
tmpResult = (tmpResult * 10) + digit;
}
result = tmpResult;
return true;
ReturnFalse:
result = 0;
return false;
}
internal static string DumpHeaders(params HttpHeaders[] headers)
{
// Return all headers as string similar to:
// {
// HeaderName1: Value1
// HeaderName1: Value2
// HeaderName2: Value1
// ...
// }
StringBuilder sb = new StringBuilder();
sb.Append("{\r\n");
for (int i = 0; i < headers.Length; i++)
{
if (headers[i] != null)
{
foreach (var header in headers[i])
{
foreach (var headerValue in header.Value)
{
sb.Append(" ");
sb.Append(header.Key);
sb.Append(": ");
sb.Append(headerValue);
sb.Append("\r\n");
}
}
}
}
sb.Append('}');
return sb.ToString();
}
internal static bool IsValidEmailAddress(string value)
{
try
{
#if uap
new MailAddress(value);
#else
MailAddressParser.ParseAddress(value);
#endif
return true;
}
catch (FormatException e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_wrong_email_format, value, e.Message));
}
return false;
}
private static void ValidateToken(HttpHeaderValueCollection<string> collection, string value)
{
CheckValidToken(value, "item");
}
}
}
| |
namespace IdSharp.Tagging.ID3v2.Frames
{
using IdSharp.Tagging.ID3v2;
using IdSharp.Tagging.ID3v2.Frames.Items;
using IdSharp.Tagging.ID3v2.Frames.Lists;
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
internal sealed class SynchronizedText : ISynchronizedText, IFrame, INotifyPropertyChanged, ITextEncoding
{
public event PropertyChangedEventHandler PropertyChanged;
public SynchronizedText()
{
this.m_FrameHeader = new IdSharp.Tagging.ID3v2.FrameHeader();
this.m_SynchronizedTextItemBindingList = new SynchronizedTextItemBindingList();
}
private void FirePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler1 = this.PropertyChanged;
if (handler1 != null)
{
handler1(this, new PropertyChangedEventArgs(propertyName));
}
}
public byte[] GetBytes(ID3v2TagVersion tagVersion)
{
if (this.Items.Count == 0)
{
return new byte[0];
}
using (MemoryStream stream1 = new MemoryStream())
{
stream1.WriteByte((byte) this.TextEncoding);
Utils.Write(stream1, Utils.ISO88591GetBytes(this.LanguageCode));
stream1.WriteByte((byte) this.TimestampFormat);
stream1.WriteByte((byte) this.ContentType);
Utils.Write(stream1, Utils.GetStringBytes(tagVersion, this.TextEncoding, this.ContentDescriptor, true));
foreach (ISynchronizedTextItem item1 in this.Items)
{
Utils.Write(stream1, Utils.GetStringBytes(tagVersion, this.TextEncoding, item1.Text, true));
Utils.Write(stream1, Utils.Get4Bytes(item1.Timestamp));
}
return this.m_FrameHeader.GetBytes(stream1, tagVersion, this.GetFrameID(tagVersion));
}
}
public string GetFrameID(ID3v2TagVersion tagVersion)
{
switch (tagVersion)
{
case ID3v2TagVersion.ID3v22:
return "SLT";
case ID3v2TagVersion.ID3v23:
case ID3v2TagVersion.ID3v24:
return "SYLT";
}
throw new ArgumentException("Unknown tag version");
}
public void Read(TagReadingInfo tagReadingInfo, Stream stream)
{
this.Items.Clear();
this.m_FrameHeader.Read(tagReadingInfo, ref stream);
int num1 = this.m_FrameHeader.FrameSizeExcludingAdditions;
if (num1 >= 1)
{
this.TextEncoding = (EncodingType) Utils.ReadByte(stream, ref num1);
if (num1 >= 3)
{
this.LanguageCode = Utils.ReadString(EncodingType.ISO88591, stream, 3);
num1 -= 3;
if (num1 >= 2)
{
this.TimestampFormat = (IdSharp.Tagging.ID3v2.TimestampFormat) Utils.ReadByte(stream, ref num1);
this.ContentType = (TextContentType) Utils.ReadByte(stream, ref num1);
if (num1 > 0)
{
this.ContentDescriptor = Utils.ReadString(this.TextEncoding, stream, ref num1);
while (num1 > 0)
{
string text1 = Utils.ReadString(this.TextEncoding, stream, ref num1);
if (num1 >= 4)
{
SynchronizedTextItem item1 = new SynchronizedTextItem();
item1.Text = text1;
item1.Timestamp = Utils.ReadInt32(stream);
num1 -= 4;
this.Items.Add(item1);
}
}
}
else
{
this.ContentDescriptor = "";
}
}
else
{
this.TimestampFormat = IdSharp.Tagging.ID3v2.TimestampFormat.Milliseconds;
this.ContentType = TextContentType.Other;
this.ContentDescriptor = "";
}
}
else
{
this.LanguageCode = "eng";
this.TimestampFormat = IdSharp.Tagging.ID3v2.TimestampFormat.Milliseconds;
this.ContentType = TextContentType.Other;
this.ContentDescriptor = "";
}
}
else
{
this.TextEncoding = EncodingType.ISO88591;
this.LanguageCode = "eng";
this.TimestampFormat = IdSharp.Tagging.ID3v2.TimestampFormat.Milliseconds;
this.ContentType = TextContentType.Other;
this.ContentDescriptor = "";
}
if (num1 > 0)
{
stream.Seek((long) num1, SeekOrigin.Current);
}
}
public string ContentDescriptor
{
get
{
return this.m_ContentDescriptor;
}
set
{
this.m_ContentDescriptor = value;
this.FirePropertyChanged("ContentDescriptor");
}
}
public TextContentType ContentType
{
get
{
return this.m_ContentType;
}
set
{
this.m_ContentType = value;
this.FirePropertyChanged("ContentType");
}
}
public IFrameHeader FrameHeader
{
get
{
return this.m_FrameHeader;
}
}
public BindingList<ISynchronizedTextItem> Items
{
get
{
return this.m_SynchronizedTextItemBindingList;
}
}
public string LanguageCode
{
get
{
return this.m_LanguageCode;
}
set
{
this.m_LanguageCode = value;
this.FirePropertyChanged("LanguageCode");
}
}
public EncodingType TextEncoding
{
get
{
return this.m_TextEncoding;
}
set
{
this.m_TextEncoding = value;
this.FirePropertyChanged("TextEncoding");
}
}
public IdSharp.Tagging.ID3v2.TimestampFormat TimestampFormat
{
get
{
return this.m_TimestampFormat;
}
set
{
this.m_TimestampFormat = value;
this.FirePropertyChanged("TimestampFormat");
}
}
private string m_ContentDescriptor;
private TextContentType m_ContentType;
private IdSharp.Tagging.ID3v2.FrameHeader m_FrameHeader;
private string m_LanguageCode;
private SynchronizedTextItemBindingList m_SynchronizedTextItemBindingList;
private EncodingType m_TextEncoding;
private IdSharp.Tagging.ID3v2.TimestampFormat m_TimestampFormat;
}
}
| |
using Lucene.Net.Diagnostics;
using System.Diagnostics;
using System;
namespace 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.
*/
// javadocs
using IBits = Lucene.Net.Util.IBits;
/// <summary>
/// <see cref="AtomicReader"/> is an abstract class, providing an interface for accessing an
/// index. Search of an index is done entirely through this abstract interface,
/// so that any subclass which implements it is searchable. <see cref="IndexReader"/>s implemented
/// by this subclass do not consist of several sub-readers,
/// they are atomic. They support retrieval of stored fields, doc values, terms,
/// and postings.
///
/// <para/>For efficiency, in this API documents are often referred to via
/// <i>document numbers</i>, non-negative integers which each name a unique
/// document in the index. These document numbers are ephemeral -- they may change
/// as documents are added to and deleted from an index. Clients should thus not
/// rely on a given document having the same number between sessions.
///
/// <para/>
/// <b>NOTE</b>: <see cref="IndexReader"/>
/// instances are completely thread
/// safe, meaning multiple threads can call any of its methods,
/// concurrently. If your application requires external
/// synchronization, you should <b>not</b> synchronize on the
/// <see cref="IndexReader"/> instance; use your own
/// (non-Lucene) objects instead.
/// </summary>
public abstract class AtomicReader : IndexReader
{
private readonly AtomicReaderContext readerContext; // LUCENENET: marked readonly
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
protected AtomicReader()
: base()
{
readerContext = new AtomicReaderContext(this);
}
public sealed override IndexReaderContext Context
{
get
{
EnsureOpen();
return readerContext;
}
}
/// <summary>
/// LUCENENET specific propety that allows access to
/// the context as <see cref="AtomicReaderContext"/>,
/// which prevents the need to cast.
/// </summary>
public AtomicReaderContext AtomicContext
{
get
{
EnsureOpen();
return readerContext;
}
}
/// <summary>
/// Returns true if there are norms stored for this <paramref name="field"/>.
/// </summary>
[Obsolete("(4.0) use FieldInfos and check FieldInfo.HasNorms for the field instead.")]
public bool HasNorms(string field)
{
EnsureOpen();
// note: using normValues(field) != null would potentially cause i/o
FieldInfo fi = FieldInfos.FieldInfo(field);
return fi != null && fi.HasNorms;
}
/// <summary>
/// Returns <see cref="Index.Fields"/> for this reader.
/// this property may return <c>null</c> if the reader has no
/// postings.
/// </summary>
public abstract Fields Fields { get; }
public override sealed int DocFreq(Term term)
{
Fields fields = Fields;
if (fields is null)
{
return 0;
}
Terms terms = fields.GetTerms(term.Field);
if (terms is null)
{
return 0;
}
TermsEnum termsEnum = terms.GetEnumerator();
if (termsEnum.SeekExact(term.Bytes))
{
return termsEnum.DocFreq;
}
else
{
return 0;
}
}
/// <summary>
/// Returns the number of documents containing the <paramref name="term"/>.
/// This method returns 0 if the term or
/// field does not exist. This method does not take into
/// account deleted documents that have not yet been merged
/// away.
/// </summary>
public override sealed long TotalTermFreq(Term term)
{
Fields fields = Fields;
if (fields is null)
{
return 0;
}
Terms terms = fields.GetTerms(term.Field);
if (terms is null)
{
return 0;
}
TermsEnum termsEnum = terms.GetEnumerator();
if (termsEnum.SeekExact(term.Bytes))
{
return termsEnum.TotalTermFreq;
}
else
{
return 0;
}
}
public override sealed long GetSumDocFreq(string field)
{
Terms terms = GetTerms(field);
if (terms is null)
{
return 0;
}
return terms.SumDocFreq;
}
public override sealed int GetDocCount(string field)
{
Terms terms = GetTerms(field);
if (terms is null)
{
return 0;
}
return terms.DocCount;
}
public override sealed long GetSumTotalTermFreq(string field)
{
Terms terms = GetTerms(field);
if (terms is null)
{
return 0;
}
return terms.SumTotalTermFreq;
}
/// <summary>
/// This may return <c>null</c> if the field does not exist. </summary>
public Terms GetTerms(string field) // LUCENENET specific: Renamed from Terms()
{
Fields fields = Fields;
if (fields is null)
{
return null;
}
return fields.GetTerms(field);
}
/// <summary>
/// Returns <see cref="DocsEnum"/> for the specified term.
/// This will return <c>null</c> if either the field or
/// term does not exist.
/// </summary>
/// <seealso cref="TermsEnum.Docs(IBits, DocsEnum)"/>
public DocsEnum GetTermDocsEnum(Term term) // LUCENENET specific: Renamed from TermDocsEnum()
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(term.Field != null);
Debugging.Assert(term.Bytes != null);
}
Fields fields = Fields;
if (fields != null)
{
Terms terms = fields.GetTerms(term.Field);
if (terms != null)
{
TermsEnum termsEnum = terms.GetEnumerator();
if (termsEnum.SeekExact(term.Bytes))
{
return termsEnum.Docs(LiveDocs, null);
}
}
}
return null;
}
/// <summary>
/// Returns <see cref="DocsAndPositionsEnum"/> for the specified
/// term. This will return <c>null</c> if the
/// field or term does not exist or positions weren't indexed. </summary>
/// <seealso cref="TermsEnum.DocsAndPositions(IBits, DocsAndPositionsEnum)"/>
public DocsAndPositionsEnum GetTermPositionsEnum(Term term) // LUCENENET specific: Renamed from TermPositionsEnum()
{
if (Debugging.AssertsEnabled) Debugging.Assert(term.Field != null);
if (Debugging.AssertsEnabled) Debugging.Assert(term.Bytes != null);
Fields fields = Fields;
if (fields != null)
{
Terms terms = fields.GetTerms(term.Field);
if (terms != null)
{
TermsEnum termsEnum = terms.GetEnumerator();
if (termsEnum.SeekExact(term.Bytes))
{
return termsEnum.DocsAndPositions(LiveDocs, null);
}
}
}
return null;
}
/// <summary>
/// Returns <see cref="NumericDocValues"/> for this field, or
/// null if no <see cref="NumericDocValues"/> were indexed for
/// this field. The returned instance should only be
/// used by a single thread.
/// </summary>
public abstract NumericDocValues GetNumericDocValues(string field);
/// <summary>
/// Returns <see cref="BinaryDocValues"/> for this field, or
/// <c>null</c> if no <see cref="BinaryDocValues"/> were indexed for
/// this field. The returned instance should only be
/// used by a single thread.
/// </summary>
public abstract BinaryDocValues GetBinaryDocValues(string field);
/// <summary>
/// Returns <see cref="SortedDocValues"/> for this field, or
/// <c>null</c> if no <see cref="SortedDocValues"/> were indexed for
/// this field. The returned instance should only be
/// used by a single thread.
/// </summary>
public abstract SortedDocValues GetSortedDocValues(string field);
/// <summary>
/// Returns <see cref="SortedSetDocValues"/> for this field, or
/// <c>null</c> if no <see cref="SortedSetDocValues"/> were indexed for
/// this field. The returned instance should only be
/// used by a single thread.
/// </summary>
public abstract SortedSetDocValues GetSortedSetDocValues(string field);
/// <summary>
/// Returns a <see cref="IBits"/> at the size of <c>reader.MaxDoc</c>,
/// with turned on bits for each docid that does have a value for this field,
/// or <c>null</c> if no <see cref="DocValues"/> were indexed for this field. The
/// returned instance should only be used by a single thread.
/// </summary>
public abstract IBits GetDocsWithField(string field);
/// <summary>
/// Returns <see cref="NumericDocValues"/> representing norms
/// for this field, or <c>null</c> if no <see cref="NumericDocValues"/>
/// were indexed. The returned instance should only be
/// used by a single thread.
/// </summary>
public abstract NumericDocValues GetNormValues(string field);
/// <summary>
/// Get the <see cref="Index.FieldInfos"/> describing all fields in
/// this reader.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract FieldInfos FieldInfos { get; }
/// <summary>
/// Returns the <see cref="IBits"/> representing live (not
/// deleted) docs. A set bit indicates the doc ID has not
/// been deleted. If this method returns <c>null</c> it means
/// there are no deleted documents (all documents are
/// live).
/// <para/>
/// The returned instance has been safely published for
/// use by multiple threads without additional
/// synchronization.
/// </summary>
public abstract IBits LiveDocs { get; }
/// <summary>
/// Checks consistency of this reader.
/// <para/>
/// Note that this may be costly in terms of I/O, e.g.
/// may involve computing a checksum value against large data files.
/// <para/>
/// @lucene.internal
/// </summary>
public abstract void CheckIntegrity();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Reflection.Metadata.Ecma335
{
/// <summary>
/// Encodes instructions.
/// </summary>
public readonly struct InstructionEncoder
{
/// <summary>
/// Underlying builder where encoded instructions are written to.
/// </summary>
public BlobBuilder CodeBuilder { get; }
/// <summary>
/// Builder tracking labels, branches and exception handlers.
/// </summary>
/// <remarks>
/// If null the encoder doesn't support construction of control flow.
/// </remarks>
public ControlFlowBuilder ControlFlowBuilder { get; }
/// <summary>
/// Creates an encoder backed by code and control-flow builders.
/// </summary>
/// <param name="codeBuilder">Builder to write encoded instructions to.</param>
/// <param name="controlFlowBuilder">
/// Builder tracking labels, branches and exception handlers.
/// Must be specified to be able to use some of the control-flow factory methods of <see cref="InstructionEncoder"/>,
/// such as <see cref="Branch(ILOpCode, LabelHandle)"/>, <see cref="DefineLabel"/>, <see cref="MarkLabel(LabelHandle)"/> etc.
/// </param>
public InstructionEncoder(BlobBuilder codeBuilder, ControlFlowBuilder controlFlowBuilder = null)
{
if (codeBuilder == null)
{
Throw.BuilderArgumentNull();
}
CodeBuilder = codeBuilder;
ControlFlowBuilder = controlFlowBuilder;
}
/// <summary>
/// Offset of the next encoded instruction.
/// </summary>
public int Offset => CodeBuilder.Count;
/// <summary>
/// Encodes specified op-code.
/// </summary>
public void OpCode(ILOpCode code)
{
if (unchecked((byte)code) == (ushort)code)
{
CodeBuilder.WriteByte((byte)code);
}
else
{
// IL opcodes that occupy two bytes are written to
// the byte stream with the high-order byte first,
// in contrast to the little-endian format of the
// numeric arguments and tokens.
CodeBuilder.WriteUInt16BE((ushort)code);
}
}
/// <summary>
/// Encodes a token.
/// </summary>
public void Token(EntityHandle handle)
{
Token(MetadataTokens.GetToken(handle));
}
/// <summary>
/// Encodes a token.
/// </summary>
public void Token(int token)
{
CodeBuilder.WriteInt32(token);
}
/// <summary>
/// Encodes <code>ldstr</code> instruction and its operand.
/// </summary>
public void LoadString(UserStringHandle handle)
{
OpCode(ILOpCode.Ldstr);
Token(MetadataTokens.GetToken(handle));
}
/// <summary>
/// Encodes <code>call</code> instruction and its operand.
/// </summary>
public void Call(EntityHandle methodHandle)
{
if (methodHandle.Kind != HandleKind.MethodDefinition &&
methodHandle.Kind != HandleKind.MethodSpecification &&
methodHandle.Kind != HandleKind.MemberReference)
{
Throw.InvalidArgument_Handle(nameof(methodHandle));
}
OpCode(ILOpCode.Call);
Token(methodHandle);
}
/// <summary>
/// Encodes <code>call</code> instruction and its operand.
/// </summary>
public void Call(MethodDefinitionHandle methodHandle)
{
OpCode(ILOpCode.Call);
Token(methodHandle);
}
/// <summary>
/// Encodes <code>call</code> instruction and its operand.
/// </summary>
public void Call(MethodSpecificationHandle methodHandle)
{
OpCode(ILOpCode.Call);
Token(methodHandle);
}
/// <summary>
/// Encodes <code>call</code> instruction and its operand.
/// </summary>
public void Call(MemberReferenceHandle methodHandle)
{
OpCode(ILOpCode.Call);
Token(methodHandle);
}
/// <summary>
/// Encodes <code>calli</code> instruction and its operand.
/// </summary>
public void CallIndirect(StandaloneSignatureHandle signature)
{
OpCode(ILOpCode.Calli);
Token(signature);
}
/// <summary>
/// Encodes <see cref="int"/> constant load instruction.
/// </summary>
public void LoadConstantI4(int value)
{
ILOpCode code;
switch (value)
{
case -1: code = ILOpCode.Ldc_i4_m1; break;
case 0: code = ILOpCode.Ldc_i4_0; break;
case 1: code = ILOpCode.Ldc_i4_1; break;
case 2: code = ILOpCode.Ldc_i4_2; break;
case 3: code = ILOpCode.Ldc_i4_3; break;
case 4: code = ILOpCode.Ldc_i4_4; break;
case 5: code = ILOpCode.Ldc_i4_5; break;
case 6: code = ILOpCode.Ldc_i4_6; break;
case 7: code = ILOpCode.Ldc_i4_7; break;
case 8: code = ILOpCode.Ldc_i4_8; break;
default:
if (unchecked((sbyte)value == value))
{
OpCode(ILOpCode.Ldc_i4_s);
CodeBuilder.WriteSByte((sbyte)value);
}
else
{
OpCode(ILOpCode.Ldc_i4);
CodeBuilder.WriteInt32(value);
}
return;
}
OpCode(code);
}
/// <summary>
/// Encodes <see cref="long"/> constant load instruction.
/// </summary>
public void LoadConstantI8(long value)
{
OpCode(ILOpCode.Ldc_i8);
CodeBuilder.WriteInt64(value);
}
/// <summary>
/// Encodes <see cref="float"/> constant load instruction.
/// </summary>
public void LoadConstantR4(float value)
{
OpCode(ILOpCode.Ldc_r4);
CodeBuilder.WriteSingle(value);
}
/// <summary>
/// Encodes <see cref="double"/> constant load instruction.
/// </summary>
public void LoadConstantR8(double value)
{
OpCode(ILOpCode.Ldc_r8);
CodeBuilder.WriteDouble(value);
}
/// <summary>
/// Encodes local variable load instruction.
/// </summary>
/// <param name="slotIndex">Index of the local variable slot.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="slotIndex"/> is negative.</exception>
public void LoadLocal(int slotIndex)
{
switch (slotIndex)
{
case 0: OpCode(ILOpCode.Ldloc_0); break;
case 1: OpCode(ILOpCode.Ldloc_1); break;
case 2: OpCode(ILOpCode.Ldloc_2); break;
case 3: OpCode(ILOpCode.Ldloc_3); break;
default:
if (unchecked((uint)slotIndex) <= byte.MaxValue)
{
OpCode(ILOpCode.Ldloc_s);
CodeBuilder.WriteByte((byte)slotIndex);
}
else if (slotIndex > 0)
{
OpCode(ILOpCode.Ldloc);
CodeBuilder.WriteInt32(slotIndex);
}
else
{
Throw.ArgumentOutOfRange(nameof(slotIndex));
}
break;
}
}
/// <summary>
/// Encodes local variable store instruction.
/// </summary>
/// <param name="slotIndex">Index of the local variable slot.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="slotIndex"/> is negative.</exception>
public void StoreLocal(int slotIndex)
{
switch (slotIndex)
{
case 0: OpCode(ILOpCode.Stloc_0); break;
case 1: OpCode(ILOpCode.Stloc_1); break;
case 2: OpCode(ILOpCode.Stloc_2); break;
case 3: OpCode(ILOpCode.Stloc_3); break;
default:
if (unchecked((uint)slotIndex) <= byte.MaxValue)
{
OpCode(ILOpCode.Stloc_s);
CodeBuilder.WriteByte((byte)slotIndex);
}
else if (slotIndex > 0)
{
OpCode(ILOpCode.Stloc);
CodeBuilder.WriteInt32(slotIndex);
}
else
{
Throw.ArgumentOutOfRange(nameof(slotIndex));
}
break;
}
}
/// <summary>
/// Encodes local variable address load instruction.
/// </summary>
/// <param name="slotIndex">Index of the local variable slot.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="slotIndex"/> is negative.</exception>
public void LoadLocalAddress(int slotIndex)
{
if (unchecked((uint)slotIndex) <= byte.MaxValue)
{
OpCode(ILOpCode.Ldloca_s);
CodeBuilder.WriteByte((byte)slotIndex);
}
else if (slotIndex > 0)
{
OpCode(ILOpCode.Ldloca);
CodeBuilder.WriteInt32(slotIndex);
}
else
{
Throw.ArgumentOutOfRange(nameof(slotIndex));
}
}
/// <summary>
/// Encodes argument load instruction.
/// </summary>
/// <param name="argumentIndex">Index of the argument.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="argumentIndex"/> is negative.</exception>
public void LoadArgument(int argumentIndex)
{
switch (argumentIndex)
{
case 0: OpCode(ILOpCode.Ldarg_0); break;
case 1: OpCode(ILOpCode.Ldarg_1); break;
case 2: OpCode(ILOpCode.Ldarg_2); break;
case 3: OpCode(ILOpCode.Ldarg_3); break;
default:
if (unchecked((uint)argumentIndex) <= byte.MaxValue)
{
OpCode(ILOpCode.Ldarg_s);
CodeBuilder.WriteByte((byte)argumentIndex);
}
else if (argumentIndex > 0)
{
OpCode(ILOpCode.Ldarg);
CodeBuilder.WriteInt32(argumentIndex);
}
else
{
Throw.ArgumentOutOfRange(nameof(argumentIndex));
}
break;
}
}
/// <summary>
/// Encodes argument address load instruction.
/// </summary>
/// <param name="argumentIndex">Index of the argument.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="argumentIndex"/> is negative.</exception>
public void LoadArgumentAddress(int argumentIndex)
{
if (unchecked((uint)argumentIndex) <= byte.MaxValue)
{
OpCode(ILOpCode.Ldarga_s);
CodeBuilder.WriteByte((byte)argumentIndex);
}
else if (argumentIndex > 0)
{
OpCode(ILOpCode.Ldarga);
CodeBuilder.WriteInt32(argumentIndex);
}
else
{
Throw.ArgumentOutOfRange(nameof(argumentIndex));
}
}
/// <summary>
/// Encodes argument store instruction.
/// </summary>
/// <param name="argumentIndex">Index of the argument.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="argumentIndex"/> is negative.</exception>
public void StoreArgument(int argumentIndex)
{
if (unchecked((uint)argumentIndex) <= byte.MaxValue)
{
OpCode(ILOpCode.Starg_s);
CodeBuilder.WriteByte((byte)argumentIndex);
}
else if (argumentIndex > 0)
{
OpCode(ILOpCode.Starg);
CodeBuilder.WriteInt32(argumentIndex);
}
else
{
Throw.ArgumentOutOfRange(nameof(argumentIndex));
}
}
/// <summary>
/// Defines a label that can later be used to mark and refer to a location in the instruction stream.
/// </summary>
/// <returns>Label handle.</returns>
/// <exception cref="InvalidOperationException"><see cref="ControlFlowBuilder"/> is null.</exception>
public LabelHandle DefineLabel()
{
return GetBranchBuilder().AddLabel();
}
/// <summary>
/// Encodes a branch instruction.
/// </summary>
/// <param name="code">Branch instruction to encode.</param>
/// <param name="label">Label of the target location in instruction stream.</param>
/// <exception cref="ArgumentException"><paramref name="code"/> is not a branch instruction.</exception>
/// <exception cref="ArgumentException"><paramref name="label"/> was not defined by this encoder.</exception>
/// <exception cref="InvalidOperationException"><see cref="ControlFlowBuilder"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="label"/> has default value.</exception>
public void Branch(ILOpCode code, LabelHandle label)
{
// throws if code is not a branch:
int size = code.GetBranchOperandSize();
GetBranchBuilder().AddBranch(Offset, label, code);
OpCode(code);
// -1 points in the middle of the branch instruction and is thus invalid.
// We want to produce invalid IL so that if the caller doesn't patch the branches
// the branch instructions will be invalid in an obvious way.
if (size == 1)
{
CodeBuilder.WriteSByte(-1);
}
else
{
Debug.Assert(size == 4);
CodeBuilder.WriteInt32(-1);
}
}
/// <summary>
/// Associates specified label with the current IL offset.
/// </summary>
/// <param name="label">Label to mark.</param>
/// <remarks>
/// A single label may be marked multiple times, the last offset wins.
/// </remarks>
/// <exception cref="InvalidOperationException"><see cref="ControlFlowBuilder"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="label"/> was not defined by this encoder.</exception>
/// <exception cref="ArgumentNullException"><paramref name="label"/> has default value.</exception>
public void MarkLabel(LabelHandle label)
{
GetBranchBuilder().MarkLabel(Offset, label);
}
private ControlFlowBuilder GetBranchBuilder()
{
if (ControlFlowBuilder == null)
{
Throw.ControlFlowBuilderNotAvailable();
}
return ControlFlowBuilder;
}
}
}
| |
// <copyright file="PlayGamesHelperObject.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.OurUtils
{
using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class PlayGamesHelperObject : MonoBehaviour
{
// our (singleton) instance
private static PlayGamesHelperObject instance = null;
// are we a dummy instance (used in the editor?)
private static bool sIsDummy = false;
// queue of actions to run on the game thread
private static List<System.Action> sQueue = new List<Action>();
// member variable used to copy actions from the sQueue and
// execute them on the game thread. It is a member variable
// to help minimize memory allocations.
List<System.Action> localQueue = new List<System.Action>();
// flag that alerts us that we should check the queue
// (we do this just so we don't have to lock() the queue every
// frame to check if it's empty or not).
private volatile static bool sQueueEmpty = true;
// callback for application pause and focus events
private static List<Action<bool>> sPauseCallbackList =
new List<Action<bool>>();
private static List<Action<bool>> sFocusCallbackList =
new List<Action<bool>>();
// Call this once from the game thread
public static void CreateObject()
{
if (instance != null)
{
return;
}
if (Application.isPlaying)
{
// add an invisible game object to the scene
GameObject obj = new GameObject("PlayGames_QueueRunner");
DontDestroyOnLoad(obj);
instance = obj.AddComponent<PlayGamesHelperObject>();
}
else
{
instance = new PlayGamesHelperObject();
sIsDummy = true;
}
}
public void Awake()
{
DontDestroyOnLoad(gameObject);
}
public void OnDisable()
{
if (instance == this)
{
instance = null;
}
}
public static void RunCoroutine(IEnumerator action)
{
if (instance != null)
{
RunOnGameThread(()=>instance.StartCoroutine(action));
}
}
public static void RunOnGameThread(System.Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
if (sIsDummy)
{
return;
}
lock (sQueue)
{
sQueue.Add(action);
sQueueEmpty = false;
}
}
public void Update()
{
if (sIsDummy || sQueueEmpty)
{
return;
}
// first copy the shared queue into a local queue
localQueue.Clear();
lock (sQueue)
{
// transfer the whole queue to our local queue
localQueue.AddRange(sQueue);
sQueue.Clear();
sQueueEmpty = true;
}
// execute queued actions (from local queue)
// use a loop to avoid extra memory allocations using the
// forEach
for (int i = 0; i < localQueue.Count; i++)
{
localQueue[i].Invoke();
}
}
public void OnApplicationFocus(bool focused)
{
foreach (Action<bool> cb in sFocusCallbackList)
{
try
{
cb(focused);
}
catch (Exception e)
{
Debug.LogError("Exception in OnApplicationFocus:" +
e.Message + "\n" + e.StackTrace);
}
}
}
public void OnApplicationPause(bool paused)
{
foreach (Action<bool> cb in sPauseCallbackList)
{
try
{
cb(paused);
}
catch (Exception e)
{
Debug.LogError("Exception in OnApplicationPause:" +
e.Message + "\n" + e.StackTrace);
}
}
}
/// <summary>
/// Adds a callback that is called when the Unity method OnApplicationFocus
/// is called.
/// </summary>
/// <see cref="OnApplicationFocus"/>
/// <param name="callback">Callback.</param>
public static void AddFocusCallback(Action<bool> callback)
{
if (!sFocusCallbackList.Contains(callback))
{
sFocusCallbackList.Add(callback);
}
}
/// <summary>
/// Removes the callback from the list to call when handling OnApplicationFocus
/// is called.
/// </summary>
/// <returns><c>true</c>, if focus callback was removed, <c>false</c> otherwise.</returns>
/// <param name="callback">Callback.</param>
public static bool RemoveFocusCallback(Action<bool> callback)
{
return sFocusCallbackList.Remove(callback);
}
/// <summary>
/// Adds a callback that is called when the Unity method OnApplicationPause
/// is called.
/// </summary>
/// <see cref="OnApplicationPause"/>
/// <param name="callback">Callback.</param>
public static void AddPauseCallback(Action<bool> callback)
{
if (!sPauseCallbackList.Contains(callback))
{
sPauseCallbackList.Add(callback);
}
}
/// <summary>
/// Removes the callback from the list to call when handling OnApplicationPause
/// is called.
/// </summary>
/// <returns><c>true</c>, if focus callback was removed, <c>false</c> otherwise.</returns>
/// <param name="callback">Callback.</param>
public static bool RemovePauseCallback(Action<bool> callback)
{
return sPauseCallbackList.Remove(callback);
}
}
}
#endif
| |
//
// ContextBackendHandler.cs
//
// Author:
// Lluis Sanchez <[email protected]>
// Alex Corrado <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using System.Drawing;
using System.Collections.Generic;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using CGSize = System.Drawing.SizeF;
using MonoMac.CoreGraphics;
using MonoMac.AppKit;
#else
using CoreGraphics;
using AppKit;
#endif
namespace Xwt.Mac
{
class CGContextBackend {
public CGContext Context;
public CGSize Size;
public CGAffineTransform? InverseViewTransform;
public Stack<ContextStatus> StatusStack = new Stack<ContextStatus> ();
public ContextStatus CurrentStatus = new ContextStatus ();
public double ScaleFactor = 1;
}
class ContextStatus
{
public object Pattern;
}
public class MacContextBackendHandler: ContextBackendHandler
{
const double degrees = System.Math.PI / 180d;
public override double GetScaleFactor (object backend)
{
var ct = (CGContextBackend) backend;
return ct.ScaleFactor;
}
public override void Save (object backend)
{
var ct = (CGContextBackend) backend;
ct.Context.SaveState ();
ct.StatusStack.Push (ct.CurrentStatus);
var newStatus = new ContextStatus ();
newStatus.Pattern = ct.CurrentStatus.Pattern;
ct.CurrentStatus = newStatus;
}
public override void Restore (object backend)
{
var ct = (CGContextBackend) backend;
ct.Context.RestoreState ();
ct.CurrentStatus = ct.StatusStack.Pop ();
}
public override void SetGlobalAlpha (object backend, double alpha)
{
((CGContextBackend)backend).Context.SetAlpha ((float)alpha);
}
public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2)
{
CGContext ctx = ((CGContextBackend)backend).Context;
ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), false);
}
public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2)
{
CGContext ctx = ((CGContextBackend)backend).Context;
ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), true);
}
public override void Clip (object backend)
{
((CGContextBackend)backend).Context.Clip ();
}
public override void ClipPreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
using (CGPath oldPath = ctx.CopyPath ()) {
ctx.Clip ();
ctx.AddPath (oldPath);
}
}
public override void ClosePath (object backend)
{
((CGContextBackend)backend).Context.ClosePath ();
}
public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3)
{
((CGContextBackend)backend).Context.AddCurveToPoint ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3);
}
public override void Fill (object backend)
{
CGContextBackend gc = (CGContextBackend)backend;
CGContext ctx = gc.Context;
SetupContextForDrawing (ctx);
if (gc.CurrentStatus.Pattern is GradientInfo) {
MacGradientBackendHandler.Draw (ctx, ((GradientInfo)gc.CurrentStatus.Pattern));
}
else if (gc.CurrentStatus.Pattern is ImagePatternInfo) {
SetupPattern (gc);
ctx.DrawPath (CGPathDrawingMode.Fill);
}
else {
ctx.DrawPath (CGPathDrawingMode.Fill);
}
}
public override void FillPreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
using (CGPath oldPath = ctx.CopyPath ()) {
Fill (backend);
ctx.AddPath (oldPath);
}
}
public override void LineTo (object backend, double x, double y)
{
((CGContextBackend)backend).Context.AddLineToPoint ((float)x, (float)y);
}
public override void MoveTo (object backend, double x, double y)
{
((CGContextBackend)backend).Context.MoveTo ((float)x, (float)y);
}
public override void NewPath (object backend)
{
((CGContextBackend)backend).Context.BeginPath ();
}
public override void Rectangle (object backend, double x, double y, double width, double height)
{
((CGContextBackend)backend).Context.AddRect (new CGRect ((nfloat)x, (nfloat)y, (nfloat)width, (nfloat)height));
}
public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3)
{
CGContext ctx = ((CGContextBackend)backend).Context;
CGPoint p = ctx.GetPathCurrentPoint ();
ctx.AddCurveToPoint ((float)(p.X + dx1), (float)(p.Y + dy1), (float)(p.X + dx2), (float)(p.Y + dy2), (float)(p.X + dx3), (float)(p.Y + dy3));
}
public override void RelLineTo (object backend, double dx, double dy)
{
CGContext ctx = ((CGContextBackend)backend).Context;
CGPoint p = ctx.GetPathCurrentPoint ();
ctx.AddLineToPoint ((float)(p.X + dx), (float)(p.Y + dy));
}
public override void RelMoveTo (object backend, double dx, double dy)
{
CGContext ctx = ((CGContextBackend)backend).Context;
CGPoint p = ctx.GetPathCurrentPoint ();
ctx.MoveTo ((float)(p.X + dx), (float)(p.Y + dy));
}
public override void Stroke (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
ctx.DrawPath (CGPathDrawingMode.Stroke);
}
public override void StrokePreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
using (CGPath oldPath = ctx.CopyPath ()) {
ctx.DrawPath (CGPathDrawingMode.Stroke);
ctx.AddPath (oldPath);
}
}
public override void SetColor (object backend, Xwt.Drawing.Color color)
{
CGContextBackend gc = (CGContextBackend)backend;
gc.CurrentStatus.Pattern = null;
CGContext ctx = gc.Context;
ctx.SetFillColorSpace (Util.DeviceRGBColorSpace);
ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace);
ctx.SetFillColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
ctx.SetStrokeColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
}
public override void SetLineWidth (object backend, double width)
{
((CGContextBackend)backend).Context.SetLineWidth ((float)width);
}
public override void SetLineDash (object backend, double offset, params double[] pattern)
{
var array = new nfloat[pattern.Length];
for (int n=0; n<pattern.Length; n++)
array [n] = (float) pattern[n];
((CGContextBackend)backend).Context.SetLineDash ((nfloat)offset, array);
}
public override void SetPattern (object backend, object p)
{
CGContextBackend gc = (CGContextBackend)backend;
var toolkit = ApplicationContext.Toolkit;
gc.CurrentStatus.Pattern = toolkit.GetSafeBackend (p);
}
void SetupPattern (CGContextBackend gc)
{
gc.Context.SetPatternPhase (new CGSize (0, 0));
if (gc.CurrentStatus.Pattern is GradientInfo)
return;
if (gc.CurrentStatus.Pattern is ImagePatternInfo) {
var pi = (ImagePatternInfo) gc.CurrentStatus.Pattern;
var bounds = new CGRect (CGPoint.Empty, new CGSize (pi.Image.Size.Width, pi.Image.Size.Height));
var t = CGAffineTransform.Multiply (CGAffineTransform.MakeScale (1f, -1f), gc.Context.GetCTM ());
CGPattern pattern;
if (pi.Image is CustomImage) {
pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => {
c.TranslateCTM (0, bounds.Height);
c.ScaleCTM (1f, -1f);
((CustomImage)pi.Image).DrawInContext (c);
});
} else {
var empty = CGRect.Empty;
CGImage cgimg = pi.Image.AsCGImage (ref empty, null, null);
pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height,
CGPatternTiling.ConstantSpacing, true, c => c.DrawImage (bounds, cgimg));
}
CGContext ctx = gc.Context;
var alpha = new[] { (nfloat)pi.Alpha };
ctx.SetFillColorSpace (Util.PatternColorSpace);
ctx.SetStrokeColorSpace (Util.PatternColorSpace);
ctx.SetFillPattern (pattern, alpha);
ctx.SetStrokePattern (pattern, alpha);
}
}
public override void DrawTextLayout (object backend, TextLayout layout, double x, double y)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
var li = ApplicationContext.Toolkit.GetSafeBackend (layout);
MacTextLayoutBackendHandler.Draw (ctx, li, x, y);
}
public override void DrawImage (object backend, ImageDescription img, double x, double y)
{
var srcRect = new Rectangle (Point.Zero, img.Size);
var destRect = new Rectangle (x, y, img.Size.Width, img.Size.Height);
DrawImage (backend, img, srcRect, destRect);
}
public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect)
{
CGContext ctx = ((CGContextBackend)backend).Context;
NSImage image = img.ToNSImage ();
ctx.SaveState ();
ctx.SetAlpha ((float)img.Alpha);
double rx = destRect.Width / srcRect.Width;
double ry = destRect.Height / srcRect.Height;
ctx.AddRect (new CGRect ((nfloat)destRect.X, (nfloat)destRect.Y, (nfloat)destRect.Width, (nfloat)destRect.Height));
ctx.Clip ();
ctx.TranslateCTM ((float)(destRect.X - (srcRect.X * rx)), (float)(destRect.Y - (srcRect.Y * ry)));
ctx.ScaleCTM ((float)rx, (float)ry);
if (image is CustomImage) {
((CustomImage)image).DrawInContext ((CGContextBackend)backend);
} else {
var rr = new CGRect (0, 0, image.Size.Width, image.Size.Height);
ctx.ScaleCTM (1f, -1f);
ctx.DrawImage (new CGRect (0, -image.Size.Height, image.Size.Width, image.Size.Height), image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null));
}
ctx.RestoreState ();
}
public override void Rotate (object backend, double angle)
{
((CGContextBackend)backend).Context.RotateCTM ((float)(angle * degrees));
}
public override void Scale (object backend, double scaleX, double scaleY)
{
((CGContextBackend)backend).Context.ScaleCTM ((float)scaleX, (float)scaleY);
}
public override void Translate (object backend, double tx, double ty)
{
((CGContextBackend)backend).Context.TranslateCTM ((float)tx, (float)ty);
}
public override void ModifyCTM (object backend, Matrix m)
{
CGAffineTransform t = new CGAffineTransform ((float)m.M11, (float)m.M12,
(float)m.M21, (float)m.M22,
(float)m.OffsetX, (float)m.OffsetY);
((CGContextBackend)backend).Context.ConcatCTM (t);
}
public override Matrix GetCTM (object backend)
{
CGAffineTransform t = GetContextTransform ((CGContextBackend)backend);
Matrix ctm = new Matrix (t.xx, t.yx, t.xy, t.yy, t.x0, t.y0);
return ctm;
}
public override object CreatePath ()
{
return new CGPath ();
}
public override object CopyPath (object backend)
{
return ((CGContextBackend)backend).Context.CopyPath ();
}
public override void AppendPath (object backend, object otherBackend)
{
CGContext dest = ((CGContextBackend)backend).Context;
CGContextBackend src = otherBackend as CGContextBackend;
if (src != null) {
using (var path = src.Context.CopyPath ())
dest.AddPath (path);
} else {
dest.AddPath ((CGPath)otherBackend);
}
}
public override bool IsPointInFill (object backend, double x, double y)
{
return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Fill);
}
public override bool IsPointInStroke (object backend, double x, double y)
{
return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Stroke);
}
public override void Dispose (object backend)
{
((CGContextBackend)backend).Context.Dispose ();
}
static CGAffineTransform GetContextTransform (CGContextBackend gc)
{
CGAffineTransform t = gc.Context.GetCTM ();
// The CTM returned above actually includes the full view transform.
// We only want the transform that is applied to the context, so concat
// the inverse of the view transform to nullify that part.
if (gc.InverseViewTransform.HasValue)
t.Multiply (gc.InverseViewTransform.Value);
return t;
}
static void SetupContextForDrawing (CGContext ctx)
{
if (ctx.IsPathEmpty ())
return;
// setup pattern drawing to better match the behavior of Cairo
var drawPoint = ctx.GetCTM ().TransformPoint (ctx.GetPathBoundingBox ().Location);
var patternPhase = new CGSize (drawPoint.X, drawPoint.Y);
if (patternPhase != CGSize.Empty)
ctx.SetPatternPhase (patternPhase);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract class AbstractCodeActionTest
{
protected abstract string GetLanguage();
protected abstract ParseOptions GetScriptOptions();
protected abstract TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions);
protected abstract object CreateCodeRefactoringProvider(Workspace workspace);
protected virtual void TestMissing(
string initial,
Func<dynamic, dynamic> nodeLocator = null)
{
TestMissing(initial, null, nodeLocator);
TestMissing(initial, GetScriptOptions(), nodeLocator);
}
protected virtual void TestMissing(
string initial,
ParseOptions parseOptions,
Func<dynamic, dynamic> nodeLocator = null)
{
TestMissing(initial, parseOptions, null, nodeLocator);
}
protected void TestMissing(
string initialMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
Func<dynamic, dynamic> nodeLocator = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator);
Assert.Null(codeIssueOrRefactoring);
}
}
protected void Test(
string initial,
string expected,
int index = 0,
bool compareTokens = true,
Func<dynamic, dynamic> nodeLocator = null,
IDictionary<OptionKey, object> options = null)
{
Test(initial, expected, null, index, compareTokens, nodeLocator, options);
Test(initial, expected, GetScriptOptions(), index, compareTokens, nodeLocator, options);
}
protected void Test(
string initial,
string expected,
ParseOptions parseOptions,
int index = 0,
bool compareTokens = true,
Func<dynamic, dynamic> nodeLocator = null,
IDictionary<OptionKey, object> options = null)
{
Test(initial, expected, parseOptions, null, index, compareTokens, nodeLocator, options);
}
private void ApplyOptionsToWorkspace(Workspace workspace, IDictionary<OptionKey, object> options)
{
var optionService = workspace.Services.GetService<IOptionService>();
var optionSet = optionService.GetOptions();
foreach (var option in options)
{
optionSet = optionSet.WithChangedOption(option.Key, option.Value);
}
optionService.SetOptions(optionSet);
}
protected void Test(
string initialMarkup,
string expectedMarkup,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
int index = 0,
bool compareTokens = true,
Func<dynamic, dynamic> nodeLocator = null,
IDictionary<OptionKey, object> options = null)
{
string expected;
IDictionary<string, IList<TextSpan>> spanMap;
MarkupTestFile.GetSpans(expectedMarkup.NormalizeLineEndings(), out expected, out spanMap);
var conflictSpans = spanMap.GetOrAdd("Conflict", _ => new List<TextSpan>());
var renameSpans = spanMap.GetOrAdd("Rename", _ => new List<TextSpan>());
var warningSpans = spanMap.GetOrAdd("Warning", _ => new List<TextSpan>());
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
if (options != null)
{
ApplyOptionsToWorkspace(workspace, options);
}
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator);
TestActions(
workspace, expected, index,
codeIssueOrRefactoring.Actions.ToList(),
conflictSpans, renameSpans, warningSpans,
compareTokens: compareTokens);
}
}
internal ICodeRefactoring GetCodeRefactoring(
TestWorkspace workspace,
Func<dynamic, dynamic> nodeLocator)
{
return GetCodeRefactorings(workspace, nodeLocator).FirstOrDefault();
}
private IEnumerable<ICodeRefactoring> GetCodeRefactorings(
TestWorkspace workspace,
Func<dynamic, dynamic> nodeLocator)
{
var provider = CreateCodeRefactoringProvider(workspace);
return SpecializedCollections.SingletonEnumerable(
GetCodeRefactoring((CodeRefactoringProvider)provider, workspace));
}
protected virtual IEnumerable<SyntaxNode> GetNodes(SyntaxNode root, TextSpan span)
{
IEnumerable<SyntaxNode> nodes;
nodes = root.FindToken(span.Start, findInsideTrivia: true).GetAncestors<SyntaxNode>().Where(a => span.Contains(a.Span)).Reverse();
return nodes;
}
private CodeRefactoring GetCodeRefactoring(
CodeRefactoringProvider provider,
TestWorkspace workspace)
{
var document = GetDocument(workspace);
var span = workspace.Documents.Single(d => !d.IsLinkFile).SelectedSpans.Single();
var actions = new List<CodeAction>();
var context = new CodeRefactoringContext(document, span, (a) => actions.Add(a), CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
return actions.Count > 0 ? new CodeRefactoring(provider, actions) : null;
}
protected void TestSmartTagText(
string initialMarkup,
string displayText,
int index = 0,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var refactoring = GetCodeRefactoring(workspace, nodeLocator: null);
Assert.Equal(displayText, refactoring.Actions.ElementAt(index).Title);
}
}
protected void TestExactActionSetOffered(
string initialMarkup,
IEnumerable<string> expectedActionSet,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator: null);
var actualActionSet = codeIssueOrRefactoring.Actions.Select(a => a.Title);
Assert.True(actualActionSet.SequenceEqual(expectedActionSet),
"Expected: " + string.Join(", ", expectedActionSet) +
"\nActual: " + string.Join(", ", actualActionSet));
}
}
protected void TestActionCount(
string initialMarkup,
int count,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssueOrRefactoring = GetCodeRefactoring(workspace, nodeLocator: null);
Assert.Equal(count, codeIssueOrRefactoring.Actions.Count());
}
}
protected void TestActions(
TestWorkspace workspace,
string expectedText,
int index,
IList<CodeAction> actions,
IList<TextSpan> expectedConflictSpans = null,
IList<TextSpan> expectedRenameSpans = null,
IList<TextSpan> expectedWarningSpans = null,
string expectedPreviewContents = null,
bool compareTokens = true,
bool compareExpectedTextAfterApply = false)
{
var operations = VerifyInputsAndGetOperations(index, actions);
VerifyPreviewContents(workspace, expectedPreviewContents, operations);
// Test annotations from the operation's new solution
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
var oldSolution = workspace.CurrentSolution;
var newSolutionFromOperation = applyChangesOperation.ChangedSolution;
var documentFromOperation = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolutionFromOperation);
var fixedRootFromOperation = documentFromOperation.GetSyntaxRootAsync().Result;
TestAnnotations(expectedText, expectedConflictSpans, fixedRootFromOperation, ConflictAnnotation.Kind, compareTokens);
TestAnnotations(expectedText, expectedRenameSpans, fixedRootFromOperation, RenameAnnotation.Kind, compareTokens);
TestAnnotations(expectedText, expectedWarningSpans, fixedRootFromOperation, WarningAnnotation.Kind, compareTokens);
// Test final text
string actualText;
if (compareExpectedTextAfterApply)
{
applyChangesOperation.Apply(workspace, CancellationToken.None);
var newSolutionAfterApply = workspace.CurrentSolution;
var documentFromAfterApply = SolutionUtilities.GetSingleChangedDocument(oldSolution, newSolutionAfterApply);
var fixedRootFromAfterApply = documentFromAfterApply.GetSyntaxRootAsync().Result;
actualText = compareTokens ? fixedRootFromAfterApply.ToString() : fixedRootFromAfterApply.ToFullString();
}
else
{
actualText = compareTokens ? fixedRootFromOperation.ToString() : fixedRootFromOperation.ToFullString();
}
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
}
else
{
Assert.Equal(expectedText, actualText);
}
}
protected void TestActionsOnLinkedFiles(
TestWorkspace workspace,
string expectedText,
int index,
IList<CodeAction> actions,
string expectedPreviewContents = null,
bool compareTokens = true)
{
var operations = VerifyInputsAndGetOperations(index, actions);
VerifyPreviewContents(workspace, expectedPreviewContents, operations);
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
applyChangesOperation.Apply(workspace, CancellationToken.None);
foreach (var document in workspace.Documents)
{
var fixedRoot = workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync().Result;
var actualText = compareTokens ? fixedRoot.ToString() : fixedRoot.ToFullString();
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
}
else
{
Assert.Equal(expectedText, actualText);
}
}
}
private static IEnumerable<CodeActionOperation> VerifyInputsAndGetOperations(int index, IList<CodeAction> actions)
{
Assert.NotNull(actions);
Assert.InRange(index, 0, actions.Count - 1);
var action = actions[index];
return action.GetOperationsAsync(CancellationToken.None).Result;
}
private static void VerifyPreviewContents(TestWorkspace workspace, string expectedPreviewContents, IEnumerable<CodeActionOperation> operations)
{
if (expectedPreviewContents != null)
{
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var content = editHandler.GetPreviews(workspace, operations, CancellationToken.None).TakeNextPreviewAsync().PumpingWaitResult();
var diffView = content as IWpfDifferenceViewer;
Assert.NotNull(diffView);
var previewContents = diffView.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
diffView.Close();
Assert.Equal(expectedPreviewContents, previewContents);
}
}
private void TestAnnotations(
string expectedText,
IList<TextSpan> expectedSpans,
SyntaxNode fixedRoot,
string annotationKind,
bool compareTokens)
{
expectedSpans = expectedSpans ?? new List<TextSpan>();
var annotatedTokens = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).Select(n => (SyntaxToken)n).ToList();
Assert.Equal(expectedSpans.Count, annotatedTokens.Count);
if (expectedSpans.Count > 0)
{
var expectedTokens = TokenUtilities.GetTokens(TokenUtilities.GetSyntaxRoot(expectedText, GetLanguage()));
var actualTokens = TokenUtilities.GetTokens(fixedRoot);
for (var i = 0; i < Math.Min(expectedTokens.Count, actualTokens.Count); i++)
{
var expectedToken = expectedTokens[i];
var actualToken = actualTokens[i];
var actualIsConflict = annotatedTokens.Contains(actualToken);
var expectedIsConflict = expectedSpans.Contains(expectedToken.Span);
Assert.Equal(expectedIsConflict, actualIsConflict);
}
}
}
protected static Document GetDocument(TestWorkspace workspace)
{
return workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
}
protected void TestAddDocument(
string initial,
string expected,
IList<string> expectedContainers,
string expectedDocumentName,
int index = 0,
bool compareTokens = true)
{
TestAddDocument(initial, expected, index, expectedContainers, expectedDocumentName, null, null, compareTokens);
TestAddDocument(initial, expected, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens);
}
private void TestAddDocument(
string initialMarkup,
string expected,
int index,
IList<string> expectedContainers,
string expectedDocumentName,
ParseOptions parseOptions,
CompilationOptions compilationOptions,
bool compareTokens)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var codeIssue = GetCodeRefactoring(workspace, nodeLocator: null);
TestAddDocument(workspace, expected, index, expectedContainers, expectedDocumentName,
codeIssue.Actions.ToList(), compareTokens);
}
}
private void TestAddDocument(
TestWorkspace workspace,
string expected,
int index,
IList<string> expectedFolders,
string expectedDocumentName,
IList<CodeAction> fixes,
bool compareTokens)
{
Assert.NotNull(fixes);
Assert.InRange(index, 0, fixes.Count - 1);
var operations = fixes[index].GetOperationsAsync(CancellationToken.None).Result;
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
var oldSolution = workspace.CurrentSolution;
var newSolution = applyChangesOperation.ChangedSolution;
var addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(
expected, addedDocument.GetTextAsync().Result.ToString(), GetLanguage());
}
else
{
Assert.Equal(expected, addedDocument.GetTextAsync().Result.ToString());
}
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var content = editHandler.GetPreviews(workspace, operations, CancellationToken.None).TakeNextPreviewAsync().PumpingWaitResult();
var textView = content as IWpfTextView;
Assert.NotNull(textView);
textView.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_IO_BinaryReader_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.IO.BinaryReader);
args = new Type[]{};
method = type.GetMethod("ReadChar", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadChar_0);
args = new Type[]{};
method = type.GetMethod("ReadByte", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadByte_1);
args = new Type[]{};
method = type.GetMethod("ReadSByte", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadSByte_2);
args = new Type[]{};
method = type.GetMethod("ReadBoolean", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadBoolean_3);
args = new Type[]{};
method = type.GetMethod("ReadInt16", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadInt16_4);
args = new Type[]{};
method = type.GetMethod("ReadUInt16", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadUInt16_5);
args = new Type[]{};
method = type.GetMethod("ReadInt32", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadInt32_6);
args = new Type[]{};
method = type.GetMethod("ReadUInt32", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadUInt32_7);
args = new Type[]{};
method = type.GetMethod("ReadInt64", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadInt64_8);
args = new Type[]{};
method = type.GetMethod("ReadUInt64", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadUInt64_9);
args = new Type[]{};
method = type.GetMethod("ReadSingle", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadSingle_10);
args = new Type[]{};
method = type.GetMethod("ReadDouble", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadDouble_11);
args = new Type[]{};
method = type.GetMethod("ReadDecimal", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadDecimal_12);
args = new Type[]{};
method = type.GetMethod("ReadString", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, ReadString_13);
args = new Type[]{typeof(System.IO.Stream)};
method = type.GetConstructor(flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Ctor_0);
}
static StackObject* ReadChar_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadChar();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = (int)result_of_this_method;
return __ret + 1;
}
static StackObject* ReadByte_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadByte();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadSByte_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadSByte();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadBoolean_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadBoolean();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* ReadInt16_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadInt16();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadUInt16_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadUInt16();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadInt32_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadInt32();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadUInt32_7(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadUInt32();
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = (int)result_of_this_method;
return __ret + 1;
}
static StackObject* ReadInt64_8(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadInt64();
__ret->ObjectType = ObjectTypes.Long;
*(long*)&__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadUInt64_9(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadUInt64();
__ret->ObjectType = ObjectTypes.Long;
*(ulong*)&__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadSingle_10(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadSingle();
__ret->ObjectType = ObjectTypes.Float;
*(float*)&__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadDouble_11(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadDouble();
__ret->ObjectType = ObjectTypes.Double;
*(double*)&__ret->Value = result_of_this_method;
return __ret + 1;
}
static StackObject* ReadDecimal_12(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadDecimal();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* ReadString_13(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.BinaryReader instance_of_this_method = (System.IO.BinaryReader)typeof(System.IO.BinaryReader).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.ReadString();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.Stream @input = (System.IO.Stream)typeof(System.IO.Stream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = new System.IO.BinaryReader(@input);
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
}
}
| |
#if !(UNITY_4 || UNITY_5)
using System;
using System.Collections;
using ColossalFramework;
using ColossalFramework.Math;
using ColossalFramework.UI;
using ICities;
using UnityEngine;
using TerrainLib;
namespace TerrainGen {
public class TerraGen {
private static TerrainGen i;
private TerraGen() {}
public static TerrainGen tg { get {
if (i==null)
i = new TerrainGen();
return i;
}}
}
public class TerrainGen : ThreadingExtensionBase {
private System.Random r;
private SquareDiamond sdTerrain;
private SquareDiamond sdResources;
public SquareDiamond.InitMode InitNorth = SquareDiamond.InitMode.INIT_RANDOM;
public SquareDiamond.InitMode InitWest = SquareDiamond.InitMode.INIT_RANDOM;
public SquareDiamond.InitMode InitNorthWest = SquareDiamond.InitMode.INIT_RANDOM;
public SquareDiamond.InitMode InitCenter = SquareDiamond.InitMode.INIT_RANDOM;
public bool RandomResourcesInit = true;
private double frand() {
if (r==null)
r = new System.Random();
return (r.NextDouble () * 2.0) - 1.0;
}
public void FlattenTerrain() {
byte[] map = new byte[1081*1081*2];
for (int i=0; i<1081*1081*2; i+=2) {
map[i] = 0;
map[i+1] = 15;
}
SimulationManager.instance.AddAction(LoadHeightMap(map));
}
public void DoTerrain(int smoothness, float scale, float offset, int blur) {
if ( sdTerrain == null )
sdTerrain = new SquareDiamond(1024, new System.Random());
sdTerrain.Generate(smoothness, (double)scale, InitNorthWest, InitNorth, InitWest, InitCenter);
if ( blur >= 3 )
sdTerrain.Blur(blur);
int[] hmap = new int[1081*1081];
for (int y=0; y<1081; y++) {
for(int x=0; x<1081; x++) {
// Offset 28 px 1081-1024/2
float pt = (float)sdTerrain.Point(x-28,y-28);
int pos = x+y*1081;
int val = (int)((pt+1.0+(double)offset)*32768);
val = Mathf.Clamp (val, 0, 65535);
hmap[pos] = val;
}
}
// doRiver();
byte[] map = new byte[1081*1081*2];
for (int y=0; y<1081; y++) {
for(int x=0; x<1081; x++) {
int pos = x+y*1081;
byte[] bytes = BitConverter.GetBytes(hmap[pos]);
if (!BitConverter.IsLittleEndian)
Array.Reverse(bytes);
map[pos*2] = bytes[0];
map[1+pos*2] = bytes[1];
}
}
SimulationManager.instance.AddAction(LoadHeightMap(map));
}
public void DoResources(int smoothness, float scale, float offset, int blur, float forestlvl, float orelvl) {
if ( sdResources == null)
sdResources = new SquareDiamond(512, new System.Random());
if ( RandomResourcesInit == true ) {
sdResources.Generate(smoothness, (double)scale,
SquareDiamond.InitMode.INIT_RANDOM, SquareDiamond.InitMode.INIT_RANDOM,
SquareDiamond.InitMode.INIT_RANDOM, SquareDiamond.InitMode.INIT_RANDOM);
} else {
sdResources.Generate(smoothness, (double)scale, InitNorthWest, InitNorth, InitWest, InitCenter);
}
NaturalResourceManager m = NaturalResourceManager.instance;
// forest level from 0.0 to 1.0
// in reality max 0.7 (and 3 * 0.1 for other three natural resources makes 1).
orelvl *= 3;
forestlvl *= 0.7f;
float gap = (1.0f - forestlvl ) / 3;
float oregap = gap * orelvl;
forestlvl /= 2;
for (int y=0; y<512; y++) {
for (int x=0; x<512; x++) {
int pos = x * 512 + y;
double pt = sdResources.Point(x, y) + 1.0 / 2.0;
m.m_naturalResources[pos].m_oil = 0;
m.m_naturalResources[pos].m_ore = 0;
m.m_naturalResources[pos].m_fertility = 0;
m.m_naturalResources[pos].m_forest = 0;
m.m_naturalResources[pos].m_tree = 0;
if ( pt < gap ) {
m.m_naturalResources[pos].m_fertility = 255;
} else if ( pt > gap+forestlvl && pt < gap+forestlvl+oregap ) {
m.m_naturalResources[pos].m_ore = 255;
} else if ( pt > gap+forestlvl+oregap+forestlvl ) {
m.m_naturalResources[pos].m_oil = 255;
} else {
m.m_naturalResources[pos].m_forest = 255;
m.m_naturalResources[pos].m_tree = 120; // ??
}
m.m_naturalResources[pos].m_modified = 0xff;
}
}
}
public void DoTrees(bool follow, int treeNum, bool inside25, int density) {
SquareDiamond sd;
if (follow) {
sd = sdResources;
} else {
sd = new SquareDiamond(512, new System.Random());
sd.Generate(9, 1.0, SquareDiamond.InitMode.INIT_RANDOM, SquareDiamond.InitMode.INIT_RANDOM, SquareDiamond.InitMode.INIT_RANDOM, SquareDiamond.InitMode.INIT_RANDOM);
sd.Blur(3);
}
TreeInfo tree;
NaturalResourceManager m = NaturalResourceManager.instance;
TreeCollection tc = GameObject.FindObjectOfType<TreeCollection>();
int numTrees = tc.m_prefabs.Length;
// TODO: Do something with TerrainManager.instance.GetShorePos() and HasWater()
int start = 0;
int end = 512;
if (inside25 == true) {
// Create trees only inside center 25 tiles.
start = (512/9)*2;
end = 512-(512/9)*2;
}
int matches = 0;
for (int y=start; y<end; y++) {
for (int x=start; x<end; x++) {
int pos = x * 512 + y;
double pt = sd.Point(x, y);
if ( follow ? m.m_naturalResources[pos].m_forest == 255 : (pt > 0.0 && pt < 0.5) ) {
matches++;
}
}
}
int max = TreeManager.MAX_MAP_TREES/matches > density ? density : TreeManager.MAX_MAP_TREES/matches;
for (int y=start; y<end; y++) {
for (int x=start; x<end; x++) {
int pos = x * 512 + y;
double pt = sd.Point(x, y);
if ( follow ? m.m_naturalResources[pos].m_forest == 255 : (pt > 0.0 && pt < 0.5) ) {
for (int n=0; n<max; n++ ) {
float xscale = 33.75f; // 540/16=33.75
float center = 270*32;
int newx = (int)(((float)x*xscale) - center + (frand()*xscale));
int newy = (int)(((float)y*xscale) - center + (frand()*xscale));
if (treeNum == 0) {
tree = tc.m_prefabs[r.Next()&numTrees-1];
} else {
tree = tc.m_prefabs[treeNum-1];
}
SimulationManager.instance.AddAction( AddTree(newy, newx, SimulationManager.instance.m_randomizer, tree) );
}
}
}
}
}
public void DeleteAllTrees() {
int r = TreeManager.TREEGRID_RESOLUTION; // 540
TreeManager tm = TreeManager.instance;
if ( tm.m_treeCount == 0 )
return;
uint tot = 0;
for (int i=0; i<r*r; i++) {
uint id = tm.m_treeGrid[i];
if (id != 0) {
while (id != 0 && tot++ < TreeManager.MAX_MAP_TREES) {
uint next = tm.m_trees.m_buffer[id].m_nextGridTree;
SimulationManager.instance.AddAction( DelTree(id) );
id = next;
};
}
}
}
private IEnumerator DelTree(uint id) {
TreeManager.instance.ReleaseTree(id);
yield return null;
}
private IEnumerator AddTree(int x, int y, ColossalFramework.Math.Randomizer rr, TreeInfo tree) {
uint treeNum;
TreeManager.instance.CreateTree(out treeNum, ref rr, tree, new Vector3(x, 0, y), false);
yield return null;
}
private IEnumerator LoadHeightMap(byte[] map) {
Singleton<TerrainManager>.instance.SetRawHeightMap(map);
yield return null;
}
}
}
#endif
| |
//
// Mono.CSharp.Debugger/MonoSymbolTable.cs
//
// Author:
// Martin Baulig ([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.Text;
using System.IO;
//
// Parts which are actually written into the symbol file are marked with
//
// #region This is actually written to the symbol file
// #endregion
//
// Please do not modify these regions without previously talking to me.
//
// All changes to the file format must be synchronized in several places:
//
// a) The fields in these regions (and their order) must match the actual
// contents of the symbol file.
//
// This helps people to understand the symbol file format without reading
// too much source code, ie. you look at the appropriate region and then
// you know what's actually in the file.
//
// It is also required to help me enforce b).
//
// b) The regions must be kept in sync with the unmanaged code in
// mono/metadata/debug-mono-symfile.h
//
// When making changes to the file format, you must also increase two version
// numbers:
//
// i) OffsetTable.Version in this file.
// ii) MONO_SYMBOL_FILE_VERSION in mono/metadata/debug-mono-symfile.h
//
// After doing so, recompile everything, including the debugger. Symbol files
// with different versions are incompatible to each other and the debugger and
// the runtime enfore this, so you need to recompile all your assemblies after
// changing the file format.
//
namespace Mono.CompilerServices.SymbolWriter
{
public class OffsetTable
{
public const int MajorVersion = 50;
public const int MinorVersion = 0;
public const long Magic = 0x45e82623fd7fa614;
#region This is actually written to the symbol file
public int TotalFileSize;
public int DataSectionOffset;
public int DataSectionSize;
public int CompileUnitCount;
public int CompileUnitTableOffset;
public int CompileUnitTableSize;
public int SourceCount;
public int SourceTableOffset;
public int SourceTableSize;
public int MethodCount;
public int MethodTableOffset;
public int MethodTableSize;
public int TypeCount;
public int AnonymousScopeCount;
public int AnonymousScopeTableOffset;
public int AnonymousScopeTableSize;
[Flags]
public enum Flags
{
IsAspxSource = 1,
WindowsFileNames = 2
}
public Flags FileFlags;
public int LineNumberTable_LineBase = LineNumberTable.Default_LineBase;
public int LineNumberTable_LineRange = LineNumberTable.Default_LineRange;
public int LineNumberTable_OpcodeBase = LineNumberTable.Default_OpcodeBase;
#endregion
internal OffsetTable ()
{
if (Environment.NewLine == "\r\n")
FileFlags |= Flags.WindowsFileNames;
}
internal OffsetTable (BinaryReader reader, int major_version, int minor_version)
{
TotalFileSize = reader.ReadInt32 ();
DataSectionOffset = reader.ReadInt32 ();
DataSectionSize = reader.ReadInt32 ();
CompileUnitCount = reader.ReadInt32 ();
CompileUnitTableOffset = reader.ReadInt32 ();
CompileUnitTableSize = reader.ReadInt32 ();
SourceCount = reader.ReadInt32 ();
SourceTableOffset = reader.ReadInt32 ();
SourceTableSize = reader.ReadInt32 ();
MethodCount = reader.ReadInt32 ();
MethodTableOffset = reader.ReadInt32 ();
MethodTableSize = reader.ReadInt32 ();
TypeCount = reader.ReadInt32 ();
AnonymousScopeCount = reader.ReadInt32 ();
AnonymousScopeTableOffset = reader.ReadInt32 ();
AnonymousScopeTableSize = reader.ReadInt32 ();
LineNumberTable_LineBase = reader.ReadInt32 ();
LineNumberTable_LineRange = reader.ReadInt32 ();
LineNumberTable_OpcodeBase = reader.ReadInt32 ();
FileFlags = (Flags) reader.ReadInt32 ();
}
internal void Write (BinaryWriter bw, int major_version, int minor_version)
{
bw.Write (TotalFileSize);
bw.Write (DataSectionOffset);
bw.Write (DataSectionSize);
bw.Write (CompileUnitCount);
bw.Write (CompileUnitTableOffset);
bw.Write (CompileUnitTableSize);
bw.Write (SourceCount);
bw.Write (SourceTableOffset);
bw.Write (SourceTableSize);
bw.Write (MethodCount);
bw.Write (MethodTableOffset);
bw.Write (MethodTableSize);
bw.Write (TypeCount);
bw.Write (AnonymousScopeCount);
bw.Write (AnonymousScopeTableOffset);
bw.Write (AnonymousScopeTableSize);
bw.Write (LineNumberTable_LineBase);
bw.Write (LineNumberTable_LineRange);
bw.Write (LineNumberTable_OpcodeBase);
bw.Write ((int) FileFlags);
}
public override string ToString ()
{
return String.Format (
"OffsetTable [{0} - {1}:{2} - {3}:{4}:{5} - {6}:{7}:{8} - {9}]",
TotalFileSize, DataSectionOffset, DataSectionSize, SourceCount,
SourceTableOffset, SourceTableSize, MethodCount, MethodTableOffset,
MethodTableSize, TypeCount);
}
}
public class LineNumberEntry
{
#region This is actually written to the symbol file
public readonly int Row;
public int Column;
public int EndRow, EndColumn;
public readonly int File;
public readonly int Offset;
public readonly bool IsHidden; // Obsolete is never used
#endregion
public sealed class LocationComparer : IComparer<LineNumberEntry>
{
public static readonly LocationComparer Default = new LocationComparer ();
public int Compare (LineNumberEntry l1, LineNumberEntry l2)
{
return l1.Row == l2.Row ?
l1.Column.CompareTo (l2.Column) :
l1.Row.CompareTo (l2.Row);
}
}
public static readonly LineNumberEntry Null = new LineNumberEntry (0, 0, 0, 0);
public LineNumberEntry (int file, int row, int column, int offset)
: this (file, row, offset, column, false)
{
}
public LineNumberEntry (int file, int row, int offset)
: this (file, row, -1, offset, false)
{
}
public LineNumberEntry (int file, int row, int column, int offset, bool is_hidden)
: this (file, row, column, -1, -1, offset, is_hidden)
{
}
public LineNumberEntry (int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden)
{
this.File = file;
this.Row = row;
this.Column = column;
this.EndRow = end_row;
this.EndColumn = end_column;
this.Offset = offset;
this.IsHidden = is_hidden;
}
public override string ToString ()
{
return String.Format ("[Line {0}:{1,2}-{3,4}:{5}]", File, Row, Column, EndRow, EndColumn, Offset);
}
}
public class CodeBlockEntry
{
public int Index;
#region This is actually written to the symbol file
public int Parent;
public Type BlockType;
public int StartOffset;
public int EndOffset;
#endregion
public enum Type {
Lexical = 1,
CompilerGenerated = 2,
IteratorBody = 3,
IteratorDispatcher = 4
}
public CodeBlockEntry (int index, int parent, Type type, int start_offset)
{
this.Index = index;
this.Parent = parent;
this.BlockType = type;
this.StartOffset = start_offset;
}
internal CodeBlockEntry (int index, MyBinaryReader reader)
{
this.Index = index;
int type_flag = reader.ReadLeb128 ();
BlockType = (Type) (type_flag & 0x3f);
this.Parent = reader.ReadLeb128 ();
this.StartOffset = reader.ReadLeb128 ();
this.EndOffset = reader.ReadLeb128 ();
/* Reserved for future extensions. */
if ((type_flag & 0x40) != 0) {
int data_size = reader.ReadInt16 ();
reader.BaseStream.Position += data_size;
}
}
public void Close (int end_offset)
{
this.EndOffset = end_offset;
}
internal void Write (MyBinaryWriter bw)
{
bw.WriteLeb128 ((int) BlockType);
bw.WriteLeb128 (Parent);
bw.WriteLeb128 (StartOffset);
bw.WriteLeb128 (EndOffset);
}
public override string ToString ()
{
return String.Format ("[CodeBlock {0}:{1}:{2}:{3}:{4}]",
Index, Parent, BlockType, StartOffset, EndOffset);
}
}
public struct LocalVariableEntry
{
#region This is actually written to the symbol file
public readonly int Index;
public readonly string Name;
public readonly int BlockIndex;
#endregion
public LocalVariableEntry (int index, string name, int block)
{
this.Index = index;
this.Name = name;
this.BlockIndex = block;
}
internal LocalVariableEntry (MonoSymbolFile file, MyBinaryReader reader)
{
Index = reader.ReadLeb128 ();
Name = reader.ReadString ();
BlockIndex = reader.ReadLeb128 ();
}
internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
{
bw.WriteLeb128 (Index);
bw.Write (Name);
bw.WriteLeb128 (BlockIndex);
}
public override string ToString ()
{
return String.Format ("[LocalVariable {0}:{1}:{2}]",
Name, Index, BlockIndex - 1);
}
}
public struct CapturedVariable
{
#region This is actually written to the symbol file
public readonly string Name;
public readonly string CapturedName;
public readonly CapturedKind Kind;
#endregion
public enum CapturedKind : byte
{
Local,
Parameter,
This
}
public CapturedVariable (string name, string captured_name,
CapturedKind kind)
{
this.Name = name;
this.CapturedName = captured_name;
this.Kind = kind;
}
internal CapturedVariable (MyBinaryReader reader)
{
Name = reader.ReadString ();
CapturedName = reader.ReadString ();
Kind = (CapturedKind) reader.ReadByte ();
}
internal void Write (MyBinaryWriter bw)
{
bw.Write (Name);
bw.Write (CapturedName);
bw.Write ((byte) Kind);
}
public override string ToString ()
{
return String.Format ("[CapturedVariable {0}:{1}:{2}]",
Name, CapturedName, Kind);
}
}
public struct CapturedScope
{
#region This is actually written to the symbol file
public readonly int Scope;
public readonly string CapturedName;
#endregion
public CapturedScope (int scope, string captured_name)
{
this.Scope = scope;
this.CapturedName = captured_name;
}
internal CapturedScope (MyBinaryReader reader)
{
Scope = reader.ReadLeb128 ();
CapturedName = reader.ReadString ();
}
internal void Write (MyBinaryWriter bw)
{
bw.WriteLeb128 (Scope);
bw.Write (CapturedName);
}
public override string ToString ()
{
return String.Format ("[CapturedScope {0}:{1}]",
Scope, CapturedName);
}
}
public struct ScopeVariable
{
#region This is actually written to the symbol file
public readonly int Scope;
public readonly int Index;
#endregion
public ScopeVariable (int scope, int index)
{
this.Scope = scope;
this.Index = index;
}
internal ScopeVariable (MyBinaryReader reader)
{
Scope = reader.ReadLeb128 ();
Index = reader.ReadLeb128 ();
}
internal void Write (MyBinaryWriter bw)
{
bw.WriteLeb128 (Scope);
bw.WriteLeb128 (Index);
}
public override string ToString ()
{
return String.Format ("[ScopeVariable {0}:{1}]", Scope, Index);
}
}
public class AnonymousScopeEntry
{
#region This is actually written to the symbol file
public readonly int ID;
#endregion
List<CapturedVariable> captured_vars = new List<CapturedVariable> ();
List<CapturedScope> captured_scopes = new List<CapturedScope> ();
public AnonymousScopeEntry (int id)
{
this.ID = id;
}
internal AnonymousScopeEntry (MyBinaryReader reader)
{
ID = reader.ReadLeb128 ();
int num_captured_vars = reader.ReadLeb128 ();
for (int i = 0; i < num_captured_vars; i++)
captured_vars.Add (new CapturedVariable (reader));
int num_captured_scopes = reader.ReadLeb128 ();
for (int i = 0; i < num_captured_scopes; i++)
captured_scopes.Add (new CapturedScope (reader));
}
internal void AddCapturedVariable (string name, string captured_name,
CapturedVariable.CapturedKind kind)
{
captured_vars.Add (new CapturedVariable (name, captured_name, kind));
}
public CapturedVariable[] CapturedVariables {
get {
CapturedVariable[] retval = new CapturedVariable [captured_vars.Count];
captured_vars.CopyTo (retval, 0);
return retval;
}
}
internal void AddCapturedScope (int scope, string captured_name)
{
captured_scopes.Add (new CapturedScope (scope, captured_name));
}
public CapturedScope[] CapturedScopes {
get {
CapturedScope[] retval = new CapturedScope [captured_scopes.Count];
captured_scopes.CopyTo (retval, 0);
return retval;
}
}
internal void Write (MyBinaryWriter bw)
{
bw.WriteLeb128 (ID);
bw.WriteLeb128 (captured_vars.Count);
foreach (CapturedVariable cv in captured_vars)
cv.Write (bw);
bw.WriteLeb128 (captured_scopes.Count);
foreach (CapturedScope cs in captured_scopes)
cs.Write (bw);
}
public override string ToString ()
{
return String.Format ("[AnonymousScope {0}]", ID);
}
}
public class CompileUnitEntry : ICompileUnit
{
#region This is actually written to the symbol file
public readonly int Index;
int DataOffset;
#endregion
MonoSymbolFile file;
SourceFileEntry source;
List<SourceFileEntry> include_files;
List<NamespaceEntry> namespaces;
bool creating;
public static int Size {
get { return 8; }
}
CompileUnitEntry ICompileUnit.Entry {
get { return this; }
}
public CompileUnitEntry (MonoSymbolFile file, SourceFileEntry source)
{
this.file = file;
this.source = source;
this.Index = file.AddCompileUnit (this);
creating = true;
namespaces = new List<NamespaceEntry> ();
}
public void AddFile (SourceFileEntry file)
{
if (!creating)
throw new InvalidOperationException ();
if (include_files == null)
include_files = new List<SourceFileEntry> ();
include_files.Add (file);
}
public SourceFileEntry SourceFile {
get {
if (creating)
return source;
ReadData ();
return source;
}
}
public int DefineNamespace (string name, string[] using_clauses, int parent)
{
if (!creating)
throw new InvalidOperationException ();
int index = file.GetNextNamespaceIndex ();
NamespaceEntry ns = new NamespaceEntry (name, index, using_clauses, parent);
namespaces.Add (ns);
return index;
}
internal void WriteData (MyBinaryWriter bw)
{
DataOffset = (int) bw.BaseStream.Position;
bw.WriteLeb128 (source.Index);
int count_includes = include_files != null ? include_files.Count : 0;
bw.WriteLeb128 (count_includes);
if (include_files != null) {
foreach (SourceFileEntry entry in include_files)
bw.WriteLeb128 (entry.Index);
}
bw.WriteLeb128 (namespaces.Count);
foreach (NamespaceEntry ns in namespaces)
ns.Write (file, bw);
}
internal void Write (BinaryWriter bw)
{
bw.Write (Index);
bw.Write (DataOffset);
}
internal CompileUnitEntry (MonoSymbolFile file, MyBinaryReader reader)
{
this.file = file;
Index = reader.ReadInt32 ();
DataOffset = reader.ReadInt32 ();
}
public void ReadAll ()
{
ReadData ();
}
void ReadData ()
{
if (creating)
throw new InvalidOperationException ();
lock (file) {
if (namespaces != null)
return;
MyBinaryReader reader = file.BinaryReader;
int old_pos = (int) reader.BaseStream.Position;
reader.BaseStream.Position = DataOffset;
int source_idx = reader.ReadLeb128 ();
source = file.GetSourceFile (source_idx);
int count_includes = reader.ReadLeb128 ();
if (count_includes > 0) {
include_files = new List<SourceFileEntry> ();
for (int i = 0; i < count_includes; i++)
include_files.Add (file.GetSourceFile (reader.ReadLeb128 ()));
}
int count_ns = reader.ReadLeb128 ();
namespaces = new List<NamespaceEntry> ();
for (int i = 0; i < count_ns; i ++)
namespaces.Add (new NamespaceEntry (file, reader));
reader.BaseStream.Position = old_pos;
}
}
public NamespaceEntry[] Namespaces {
get {
ReadData ();
NamespaceEntry[] retval = new NamespaceEntry [namespaces.Count];
namespaces.CopyTo (retval, 0);
return retval;
}
}
public SourceFileEntry[] IncludeFiles {
get {
ReadData ();
if (include_files == null)
return new SourceFileEntry [0];
SourceFileEntry[] retval = new SourceFileEntry [include_files.Count];
include_files.CopyTo (retval, 0);
return retval;
}
}
}
public class SourceFileEntry
{
#region This is actually written to the symbol file
public readonly int Index;
int DataOffset;
#endregion
MonoSymbolFile file;
string file_name;
byte[] guid;
byte[] hash;
bool creating;
bool auto_generated;
public static int Size {
get { return 8; }
}
public SourceFileEntry (MonoSymbolFile file, string file_name)
{
this.file = file;
this.file_name = file_name;
this.Index = file.AddSource (this);
creating = true;
}
public SourceFileEntry (MonoSymbolFile file, string file_name, byte[] guid, byte[] checksum)
: this (file, file_name)
{
this.guid = guid;
this.hash = checksum;
}
public byte[] Checksum {
get {
return hash;
}
}
internal void WriteData (MyBinaryWriter bw)
{
DataOffset = (int) bw.BaseStream.Position;
bw.Write (file_name);
if (guid == null)
guid = new byte[16];
if (hash == null) {
try {
using (var fs = PclFileAccess.OpenFileStream (file_name)) {
var md5 = Microsoft.CodeAnalysis.CryptographicHashProvider.TryGetAlgorithm(System.Reflection.AssemblyHashAlgorithm.MD5);
hash = md5.ComputeHash (fs);
}
} catch {
hash = new byte [16];
}
}
bw.Write (guid);
bw.Write (hash);
bw.Write ((byte) (auto_generated ? 1 : 0));
}
internal void Write (BinaryWriter bw)
{
bw.Write (Index);
bw.Write (DataOffset);
}
internal SourceFileEntry (MonoSymbolFile file, MyBinaryReader reader)
{
this.file = file;
Index = reader.ReadInt32 ();
DataOffset = reader.ReadInt32 ();
int old_pos = (int) reader.BaseStream.Position;
reader.BaseStream.Position = DataOffset;
file_name = reader.ReadString ();
guid = reader.ReadBytes (16);
hash = reader.ReadBytes (16);
auto_generated = reader.ReadByte () == 1;
reader.BaseStream.Position = old_pos;
}
public string FileName {
get { return file_name; }
set { file_name = value; }
}
public bool AutoGenerated {
get { return auto_generated; }
}
public void SetAutoGenerated ()
{
if (!creating)
throw new InvalidOperationException ();
auto_generated = true;
file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource;
}
public bool CheckChecksum ()
{
try {
using (var fs = PclFileAccess.OpenFileStream (file_name)) {
var md5 = Microsoft.CodeAnalysis.CryptographicHashProvider.TryGetAlgorithm(System.Reflection.AssemblyHashAlgorithm.MD5);
byte[] data = md5.ComputeHash (fs);
for (int i = 0; i < 16; i++)
if (data [i] != hash [i])
return false;
return true;
}
} catch {
return false;
}
}
public override string ToString ()
{
return String.Format ("SourceFileEntry ({0}:{1})", Index, DataOffset);
}
}
public class LineNumberTable
{
protected LineNumberEntry[] _line_numbers;
public LineNumberEntry[] LineNumbers {
get { return _line_numbers; }
}
public readonly int LineBase;
public readonly int LineRange;
public readonly byte OpcodeBase;
public readonly int MaxAddressIncrement;
#region Configurable constants
public const int Default_LineBase = -1;
public const int Default_LineRange = 8;
public const byte Default_OpcodeBase = 9;
#endregion
public const byte DW_LNS_copy = 1;
public const byte DW_LNS_advance_pc = 2;
public const byte DW_LNS_advance_line = 3;
public const byte DW_LNS_set_file = 4;
public const byte DW_LNS_const_add_pc = 8;
public const byte DW_LNE_end_sequence = 1;
// MONO extensions.
public const byte DW_LNE_MONO_negate_is_hidden = 0x40;
internal const byte DW_LNE_MONO__extensions_start = 0x40;
internal const byte DW_LNE_MONO__extensions_end = 0x7f;
protected LineNumberTable (MonoSymbolFile file)
{
this.LineBase = file.OffsetTable.LineNumberTable_LineBase;
this.LineRange = file.OffsetTable.LineNumberTable_LineRange;
this.OpcodeBase = (byte) file.OffsetTable.LineNumberTable_OpcodeBase;
this.MaxAddressIncrement = (255 - OpcodeBase) / LineRange;
}
internal LineNumberTable (MonoSymbolFile file, LineNumberEntry[] lines)
: this (file)
{
this._line_numbers = lines;
}
internal void Write (MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo)
{
int start = (int) bw.BaseStream.Position;
bool last_is_hidden = false;
int last_line = 1, last_offset = 0, last_file = 1;
for (int i = 0; i < LineNumbers.Length; i++) {
int line_inc = LineNumbers [i].Row - last_line;
int offset_inc = LineNumbers [i].Offset - last_offset;
if (LineNumbers [i].File != last_file) {
bw.Write (DW_LNS_set_file);
bw.WriteLeb128 (LineNumbers [i].File);
last_file = LineNumbers [i].File;
}
if (LineNumbers [i].IsHidden != last_is_hidden) {
bw.Write ((byte) 0);
bw.Write ((byte) 1);
bw.Write (DW_LNE_MONO_negate_is_hidden);
last_is_hidden = LineNumbers [i].IsHidden;
}
if (offset_inc >= MaxAddressIncrement) {
if (offset_inc < 2 * MaxAddressIncrement) {
bw.Write (DW_LNS_const_add_pc);
offset_inc -= MaxAddressIncrement;
} else {
bw.Write (DW_LNS_advance_pc);
bw.WriteLeb128 (offset_inc);
offset_inc = 0;
}
}
if ((line_inc < LineBase) || (line_inc >= LineBase + LineRange)) {
bw.Write (DW_LNS_advance_line);
bw.WriteLeb128 (line_inc);
if (offset_inc != 0) {
bw.Write (DW_LNS_advance_pc);
bw.WriteLeb128 (offset_inc);
}
bw.Write (DW_LNS_copy);
} else {
byte opcode;
opcode = (byte) (line_inc - LineBase + (LineRange * offset_inc) +
OpcodeBase);
bw.Write (opcode);
}
last_line = LineNumbers [i].Row;
last_offset = LineNumbers [i].Offset;
}
bw.Write ((byte) 0);
bw.Write ((byte) 1);
bw.Write (DW_LNE_end_sequence);
if (hasColumnsInfo) {
for (int i = 0; i < LineNumbers.Length; i++) {
var ln = LineNumbers [i];
if (ln.Row >= 0)
bw.WriteLeb128 (ln.Column);
}
}
if (hasEndInfo) {
for (int i = 0; i < LineNumbers.Length; i++) {
var ln = LineNumbers [i];
if (ln.EndRow == -1 || ln.EndColumn == -1 || ln.Row > ln.EndRow) {
bw.WriteLeb128 (0xffffff);
} else {
bw.WriteLeb128 (ln.EndRow - ln.Row);
bw.WriteLeb128 (ln.EndColumn);
}
}
}
file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start;
}
internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo)
{
LineNumberTable lnt = new LineNumberTable (file);
lnt.DoRead (file, br, readColumnsInfo, readEndInfo);
return lnt;
}
void DoRead (MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds)
{
var lines = new List<LineNumberEntry> ();
bool is_hidden = false, modified = false;
int stm_line = 1, stm_offset = 0, stm_file = 1;
while (true) {
byte opcode = br.ReadByte ();
if (opcode == 0) {
byte size = br.ReadByte ();
long end_pos = br.BaseStream.Position + size;
opcode = br.ReadByte ();
if (opcode == DW_LNE_end_sequence) {
if (modified)
lines.Add (new LineNumberEntry (
stm_file, stm_line, -1, stm_offset, is_hidden));
break;
} else if (opcode == DW_LNE_MONO_negate_is_hidden) {
is_hidden = !is_hidden;
modified = true;
} else if ((opcode >= DW_LNE_MONO__extensions_start) &&
(opcode <= DW_LNE_MONO__extensions_end)) {
; // reserved for future extensions
} else {
throw new MonoSymbolFileException ("Unknown extended opcode {0:x}", opcode);
}
br.BaseStream.Position = end_pos;
continue;
} else if (opcode < OpcodeBase) {
switch (opcode) {
case DW_LNS_copy:
lines.Add (new LineNumberEntry (
stm_file, stm_line, -1, stm_offset, is_hidden));
modified = false;
break;
case DW_LNS_advance_pc:
stm_offset += br.ReadLeb128 ();
modified = true;
break;
case DW_LNS_advance_line:
stm_line += br.ReadLeb128 ();
modified = true;
break;
case DW_LNS_set_file:
stm_file = br.ReadLeb128 ();
modified = true;
break;
case DW_LNS_const_add_pc:
stm_offset += MaxAddressIncrement;
modified = true;
break;
default:
throw new MonoSymbolFileException (
"Unknown standard opcode {0:x} in LNT",
opcode);
}
} else {
opcode -= OpcodeBase;
stm_offset += opcode / LineRange;
stm_line += LineBase + (opcode % LineRange);
lines.Add (new LineNumberEntry (
stm_file, stm_line, -1, stm_offset, is_hidden));
modified = false;
}
}
_line_numbers = lines.ToArray ();
if (includesColumns) {
for (int i = 0; i < _line_numbers.Length; ++i) {
var ln = _line_numbers[i];
if (ln.Row >= 0)
ln.Column = br.ReadLeb128 ();
}
}
if (includesEnds) {
for (int i = 0; i < _line_numbers.Length; ++i) {
var ln = _line_numbers[i];
int row = br.ReadLeb128 ();
if (row == 0xffffff) {
ln.EndRow = -1;
ln.EndColumn = -1;
} else {
ln.EndRow = ln.Row + row;
ln.EndColumn = br.ReadLeb128 ();
}
}
}
}
public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end)
{
if (_line_numbers.Length > 1) {
start = _line_numbers [0];
end = _line_numbers [_line_numbers.Length - 1];
return true;
}
start = LineNumberEntry.Null;
end = LineNumberEntry.Null;
return false;
}
}
public class MethodEntry : IComparable
{
#region This is actually written to the symbol file
public readonly int CompileUnitIndex;
public readonly int Token;
public readonly int NamespaceID;
int DataOffset;
int LocalVariableTableOffset;
int LineNumberTableOffset;
int CodeBlockTableOffset;
int ScopeVariableTableOffset;
int RealNameOffset;
Flags flags;
#endregion
int index;
public Flags MethodFlags {
get { return flags; }
}
public readonly CompileUnitEntry CompileUnit;
LocalVariableEntry[] locals;
CodeBlockEntry[] code_blocks;
ScopeVariable[] scope_vars;
LineNumberTable lnt;
string real_name;
public readonly MonoSymbolFile SymbolFile;
public int Index {
get { return index; }
set { index = value; }
}
[Flags]
public enum Flags
{
LocalNamesAmbiguous = 1,
ColumnsInfoIncluded = 1 << 1,
EndInfoIncluded = 1 << 2
}
public const int Size = 12;
internal MethodEntry (MonoSymbolFile file, MyBinaryReader reader, int index)
{
this.SymbolFile = file;
this.index = index;
Token = reader.ReadInt32 ();
DataOffset = reader.ReadInt32 ();
LineNumberTableOffset = reader.ReadInt32 ();
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = DataOffset;
CompileUnitIndex = reader.ReadLeb128 ();
LocalVariableTableOffset = reader.ReadLeb128 ();
NamespaceID = reader.ReadLeb128 ();
CodeBlockTableOffset = reader.ReadLeb128 ();
ScopeVariableTableOffset = reader.ReadLeb128 ();
RealNameOffset = reader.ReadLeb128 ();
flags = (Flags) reader.ReadLeb128 ();
reader.BaseStream.Position = old_pos;
CompileUnit = file.GetCompileUnit (CompileUnitIndex);
}
internal MethodEntry (MonoSymbolFile file, CompileUnitEntry comp_unit,
int token, ScopeVariable[] scope_vars,
LocalVariableEntry[] locals, LineNumberEntry[] lines,
CodeBlockEntry[] code_blocks, string real_name,
Flags flags, int namespace_id)
{
this.SymbolFile = file;
this.real_name = real_name;
this.locals = locals;
this.code_blocks = code_blocks;
this.scope_vars = scope_vars;
this.flags = flags;
index = -1;
Token = token;
CompileUnitIndex = comp_unit.Index;
CompileUnit = comp_unit;
NamespaceID = namespace_id;
CheckLineNumberTable (lines);
lnt = new LineNumberTable (file, lines);
file.NumLineNumbers += lines.Length;
int num_locals = locals != null ? locals.Length : 0;
if (num_locals <= 32) {
// Most of the time, the O(n^2) factor is actually
// less than the cost of allocating the hash table,
// 32 is a rough number obtained through some testing.
for (int i = 0; i < num_locals; i ++) {
string nm = locals [i].Name;
for (int j = i + 1; j < num_locals; j ++) {
if (locals [j].Name == nm) {
flags |= Flags.LocalNamesAmbiguous;
goto locals_check_done;
}
}
}
locals_check_done :
;
} else {
var local_names = new Dictionary<string, LocalVariableEntry> ();
foreach (LocalVariableEntry local in locals) {
if (local_names.ContainsKey (local.Name)) {
flags |= Flags.LocalNamesAmbiguous;
break;
}
local_names.Add (local.Name, local);
}
}
}
static void CheckLineNumberTable (LineNumberEntry[] line_numbers)
{
int last_offset = -1;
int last_row = -1;
if (line_numbers == null)
return;
for (int i = 0; i < line_numbers.Length; i++) {
LineNumberEntry line = line_numbers [i];
if (line.Equals (LineNumberEntry.Null))
throw new MonoSymbolFileException ();
if (line.Offset < last_offset)
throw new MonoSymbolFileException ();
if (line.Offset > last_offset) {
last_row = line.Row;
last_offset = line.Offset;
} else if (line.Row > last_row) {
last_row = line.Row;
}
}
}
internal void Write (MyBinaryWriter bw)
{
if ((index <= 0) || (DataOffset == 0))
throw new InvalidOperationException ();
bw.Write (Token);
bw.Write (DataOffset);
bw.Write (LineNumberTableOffset);
}
internal void WriteData (MonoSymbolFile file, MyBinaryWriter bw)
{
if (index <= 0)
throw new InvalidOperationException ();
LocalVariableTableOffset = (int) bw.BaseStream.Position;
int num_locals = locals != null ? locals.Length : 0;
bw.WriteLeb128 (num_locals);
for (int i = 0; i < num_locals; i++)
locals [i].Write (file, bw);
file.LocalCount += num_locals;
CodeBlockTableOffset = (int) bw.BaseStream.Position;
int num_code_blocks = code_blocks != null ? code_blocks.Length : 0;
bw.WriteLeb128 (num_code_blocks);
for (int i = 0; i < num_code_blocks; i++)
code_blocks [i].Write (bw);
ScopeVariableTableOffset = (int) bw.BaseStream.Position;
int num_scope_vars = scope_vars != null ? scope_vars.Length : 0;
bw.WriteLeb128 (num_scope_vars);
for (int i = 0; i < num_scope_vars; i++)
scope_vars [i].Write (bw);
if (real_name != null) {
RealNameOffset = (int) bw.BaseStream.Position;
bw.Write (real_name);
}
foreach (var lne in lnt.LineNumbers) {
if (lne.EndRow != -1 || lne.EndColumn != -1)
flags |= Flags.EndInfoIncluded;
}
LineNumberTableOffset = (int) bw.BaseStream.Position;
lnt.Write (file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
DataOffset = (int) bw.BaseStream.Position;
bw.WriteLeb128 (CompileUnitIndex);
bw.WriteLeb128 (LocalVariableTableOffset);
bw.WriteLeb128 (NamespaceID);
bw.WriteLeb128 (CodeBlockTableOffset);
bw.WriteLeb128 (ScopeVariableTableOffset);
bw.WriteLeb128 (RealNameOffset);
bw.WriteLeb128 ((int) flags);
}
public void ReadAll ()
{
GetLineNumberTable ();
GetLocals ();
GetCodeBlocks ();
GetScopeVariables ();
GetRealName ();
}
public LineNumberTable GetLineNumberTable ()
{
lock (SymbolFile) {
if (lnt != null)
return lnt;
if (LineNumberTableOffset == 0)
return null;
MyBinaryReader reader = SymbolFile.BinaryReader;
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = LineNumberTableOffset;
lnt = LineNumberTable.Read (SymbolFile, reader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
reader.BaseStream.Position = old_pos;
return lnt;
}
}
public LocalVariableEntry[] GetLocals ()
{
lock (SymbolFile) {
if (locals != null)
return locals;
if (LocalVariableTableOffset == 0)
return null;
MyBinaryReader reader = SymbolFile.BinaryReader;
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = LocalVariableTableOffset;
int num_locals = reader.ReadLeb128 ();
locals = new LocalVariableEntry [num_locals];
for (int i = 0; i < num_locals; i++)
locals [i] = new LocalVariableEntry (SymbolFile, reader);
reader.BaseStream.Position = old_pos;
return locals;
}
}
public CodeBlockEntry[] GetCodeBlocks ()
{
lock (SymbolFile) {
if (code_blocks != null)
return code_blocks;
if (CodeBlockTableOffset == 0)
return null;
MyBinaryReader reader = SymbolFile.BinaryReader;
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = CodeBlockTableOffset;
int num_code_blocks = reader.ReadLeb128 ();
code_blocks = new CodeBlockEntry [num_code_blocks];
for (int i = 0; i < num_code_blocks; i++)
code_blocks [i] = new CodeBlockEntry (i, reader);
reader.BaseStream.Position = old_pos;
return code_blocks;
}
}
public ScopeVariable[] GetScopeVariables ()
{
lock (SymbolFile) {
if (scope_vars != null)
return scope_vars;
if (ScopeVariableTableOffset == 0)
return null;
MyBinaryReader reader = SymbolFile.BinaryReader;
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = ScopeVariableTableOffset;
int num_scope_vars = reader.ReadLeb128 ();
scope_vars = new ScopeVariable [num_scope_vars];
for (int i = 0; i < num_scope_vars; i++)
scope_vars [i] = new ScopeVariable (reader);
reader.BaseStream.Position = old_pos;
return scope_vars;
}
}
public string GetRealName ()
{
lock (SymbolFile) {
if (real_name != null)
return real_name;
if (RealNameOffset == 0)
return null;
real_name = SymbolFile.BinaryReader.ReadString (RealNameOffset);
return real_name;
}
}
public int CompareTo (object obj)
{
MethodEntry method = (MethodEntry) obj;
if (method.Token < Token)
return 1;
else if (method.Token > Token)
return -1;
else
return 0;
}
public override string ToString ()
{
return String.Format ("[Method {0}:{1:x}:{2}:{3}]",
index, Token, CompileUnitIndex, CompileUnit);
}
}
public struct NamespaceEntry
{
#region This is actually written to the symbol file
public readonly string Name;
public readonly int Index;
public readonly int Parent;
public readonly string[] UsingClauses;
#endregion
public NamespaceEntry (string name, int index, string[] using_clauses, int parent)
{
this.Name = name;
this.Index = index;
this.Parent = parent;
this.UsingClauses = using_clauses != null ? using_clauses : new string [0];
}
internal NamespaceEntry (MonoSymbolFile file, MyBinaryReader reader)
{
Name = reader.ReadString ();
Index = reader.ReadLeb128 ();
Parent = reader.ReadLeb128 ();
int count = reader.ReadLeb128 ();
UsingClauses = new string [count];
for (int i = 0; i < count; i++)
UsingClauses [i] = reader.ReadString ();
}
internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
{
bw.Write (Name);
bw.WriteLeb128 (Index);
bw.WriteLeb128 (Parent);
bw.WriteLeb128 (UsingClauses.Length);
foreach (string uc in UsingClauses)
bw.Write (uc);
}
public override string ToString ()
{
return String.Format ("[Namespace {0}:{1}:{2}]", Name, Index, Parent);
}
}
}
| |
//
// ColumnCellStatusIndicator.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Cairo;
using Mono.Unix;
using Hyena.Gui;
using Hyena.Data.Gui;
using Hyena.Data.Gui.Accessibility;
using Banshee.Gui;
using Banshee.Streaming;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
namespace Banshee.Collection.Gui
{
class ColumnCellStatusIndicatorAccessible : ColumnCellAccessible, Atk.IImageImplementor
{
private string image_description;
public ColumnCellStatusIndicatorAccessible (object bound_object, ColumnCellStatusIndicator cell, ICellAccessibleParent parent) : base (bound_object, cell as ColumnCell, parent)
{
image_description = cell.GetTextAlternative (bound_object);
}
public override void Redrawn ()
{
string new_image_description = cell.GetTextAlternative (bound_object);
if (image_description != new_image_description)
GLib.Signal.Emit (this, "visible-data-changed");
image_description = new_image_description;
}
public string ImageLocale { get { return null; } }
public bool SetImageDescription (string description)
{
return false;
}
public void GetImageSize (out int width, out int height)
{
if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object)))
width = height = 16;
else
width = height = Int32.MinValue;
}
public string ImageDescription {
get {
return image_description;
}
}
public void GetImagePosition (out int x, out int y, Atk.CoordType coordType)
{
if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) {
GetPosition (out x, out y, coordType);
x += 4;
y += 4;
} else {
x = y = Int32.MinValue;
}
}
}
public class ColumnCellStatusIndicator : ColumnCell, ISizeRequestCell, ITooltipCell
{
const int padding = 2;
protected enum Icon : int {
Playing,
Paused,
Error,
Protected,
External
}
private string [] status_names;
protected string [] StatusNames {
get { return status_names; }
}
private int pixbuf_size;
protected int PixbufSize {
get { return pixbuf_size; }
set {
pixbuf_size = value;
Width = Height = value;
}
}
private Gdk.Pixbuf [] pixbufs;
protected Gdk.Pixbuf [] Pixbufs {
get { return pixbufs; }
}
public ColumnCellStatusIndicator (string property) : this (property, true)
{
}
public ColumnCellStatusIndicator (string property, bool expand) : base (property, expand)
{
RestrictSize = true;
PixbufSize = 16;
LoadPixbufs ();
}
public bool RestrictSize { get; set; }
public void GetWidthRange (Pango.Layout layout, out int min_width, out int max_width)
{
min_width = max_width = pixbuf_size + 2 * padding;
}
public override Atk.Object GetAccessible (ICellAccessibleParent parent)
{
return new ColumnCellStatusIndicatorAccessible (BoundObject, this, parent);
}
public override string GetTextAlternative (object obj)
{
var track = obj as TrackInfo;
if (track == null)
return "";
int icon_index = GetIconIndex (track);
if ((icon_index < 0) || (icon_index >= status_names.Length)) {
return "";
} else if (icon_index == (int)Icon.Error) {
return track.GetPlaybackErrorMessage () ?? "";
} else {
return status_names[icon_index];
}
}
protected virtual int PixbufCount {
get { return 5; }
}
protected virtual int GetIconIndex (TrackInfo track)
{
int icon_index = -1;
if (track.PlaybackError != StreamPlaybackError.None) {
icon_index = (int)(track.PlaybackError == StreamPlaybackError.Drm
? Icon.Protected
: Icon.Error);
} else if (track.IsPlaying) {
icon_index = (int)(ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused
? Icon.Paused
: Icon.Playing);
} else if ((track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) {
icon_index = (int)Icon.External;
} else {
icon_index = -1;
}
return icon_index;
}
protected virtual void LoadPixbufs ()
{
if (pixbufs != null && pixbufs.Length > 0) {
for (int i = 0; i < pixbufs.Length; i++) {
if (pixbufs[i] != null) {
pixbufs[i].Dispose ();
pixbufs[i] = null;
}
}
}
if (pixbufs == null) {
pixbufs = new Gdk.Pixbuf[PixbufCount];
}
pixbufs[(int)Icon.Playing] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-start");
pixbufs[(int)Icon.Paused] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-pause");
pixbufs[(int)Icon.Error] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-unreadable", "dialog-error");
pixbufs[(int)Icon.Protected] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-readonly", "dialog-error");
pixbufs[(int)Icon.External] = IconThemeUtils.LoadIcon (PixbufSize, "x-office-document");
if (status_names == null) {
status_names = new string[PixbufCount];
for (int i=0; i<PixbufCount; i++)
status_names[i] = "";
}
status_names[(int)Icon.Playing] = Catalog.GetString ("Playing");
status_names[(int)Icon.Paused] = Catalog.GetString ("Paused");
status_names[(int)Icon.Error] = Catalog.GetString ("Error");
status_names[(int)Icon.Protected] = Catalog.GetString ("Protected");
status_names[(int)Icon.External] = Catalog.GetString ("External Document");
}
public override void NotifyThemeChange ()
{
LoadPixbufs ();
}
public override void Render (CellContext context, StateFlags state, double cellWidth, double cellHeight)
{
TrackInfo track = BoundTrack;
if (track == null) {
return;
}
int icon_index = GetIconIndex (track);
TooltipMarkup = icon_index == -1 ? null : StatusNames[icon_index];
if (icon_index < 0 || pixbufs == null || pixbufs[icon_index] == null) {
return;
}
context.Context.Translate (0, 0.5);
Gdk.Pixbuf render_pixbuf = pixbufs[icon_index];
Cairo.Rectangle pixbuf_area = new Cairo.Rectangle ((cellWidth - render_pixbuf.Width) / 2,
(cellHeight - render_pixbuf.Height) / 2, render_pixbuf.Width, render_pixbuf.Height);
if (!context.Opaque) {
context.Context.Save ();
}
Gdk.CairoHelper.SetSourcePixbuf (context.Context, render_pixbuf, pixbuf_area.X, pixbuf_area.Y);
context.Context.Rectangle (pixbuf_area);
if (!context.Opaque) {
context.Context.Clip ();
context.Context.PaintWithAlpha (0.5);
context.Context.Restore ();
} else {
context.Context.Fill ();
}
}
public string GetTooltipMarkup (CellContext cellContext, double columnWidth)
{
return GetTextAlternative (BoundObject);
}
protected TrackInfo BoundTrack {
get { return BoundObject as TrackInfo; }
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
namespace Microsoft.Samples.VisualStudio.CodeDomCodeModel {
[ComVisible(true)]
[SuppressMessage("Microsoft.Interoperability", "CA1409:ComVisibleTypesShouldBeCreatable")]
[SuppressMessage("Microsoft.Interoperability", "CA1405:ComVisibleTypeBaseTypesShouldBeComVisible")]
public class CodeDomCodeVariable : CodeDomCodeElement<CodeMemberField>, CodeVariable {
private CodeElement parent;
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#dte")]
public CodeDomCodeVariable(DTE dte, CodeElement parent, string name, CodeTypeRef type, vsCMAccess access)
: base(dte, name) {
CodeObject = new CodeMemberField(CodeDomCodeTypeRef.ToCodeTypeReference(type), name);
CodeObject.Attributes = VSAccessToMemberAccess(access);
CodeObject.UserData[CodeKey] = this;
this.parent = parent;
}
public CodeDomCodeVariable(CodeElement parent, CodeMemberField field)
: base((null==parent) ? null : parent.DTE, (null==field) ? null : field.Name) {
this.parent = parent;
CodeObject = field;
}
#region CodeVariable Members
public override CodeElements Children {
get { throw new NotImplementedException(); }
}
public override CodeElements Collection {
get { return parent.Children; }
}
public override ProjectItem ProjectItem {
get { return parent.ProjectItem; }
}
public vsCMAccess Access {
get { return MemberAccessToVSAccess(CodeObject.Attributes); }
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
CodeObject.Attributes = VSAccessToMemberAccess(value);
CommitChanges();
}
}
public CodeAttribute AddAttribute(string Name, string Value, object Position) {
CodeAttribute res = AddCustomAttribute(CodeObject.CustomAttributes, Name, Value, Position);
CommitChanges();
return res;
}
public CodeElements Attributes {
get { return GetCustomAttributes(CodeObject.CustomAttributes); }
}
public string Comment {
get {
return GetComment(CodeObject.Comments, false);
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
ReplaceComment(CodeObject.Comments, value, false);
CommitChanges();
}
}
public string DocComment {
get {
return GetComment(CodeObject.Comments, true);
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
ReplaceComment(CodeObject.Comments, value, true);
CommitChanges();
}
}
public object InitExpression {
get {
if (CodeObject.InitExpression != null) {
return ((CodeSnippetExpression)CodeObject.InitExpression).Value;
}
return null;
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
string strVal = value as string;
if (strVal != null) {
CodeObject.InitExpression = new CodeSnippetExpression(strVal);
CommitChanges();
return;
}
throw new ArgumentException(Microsoft.Samples.VisualStudio.IronPythonLanguageService.Resources.CodeModelVariableExpressionNotString);
}
}
public bool IsConstant {
get {
return (CodeObject.Attributes & MemberAttributes.Const) != 0;
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
if (value) CodeObject.Attributes |= MemberAttributes.Const;
else CodeObject.Attributes &= ~MemberAttributes.Const;
CommitChanges();
}
}
public bool IsShared {
get {
return (CodeObject.Attributes & MemberAttributes.Static) != 0;
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
if (value) CodeObject.Attributes |= MemberAttributes.Static;
else CodeObject.Attributes &= ~MemberAttributes.Static;
CommitChanges();
}
}
public object Parent {
get { return parent; }
}
public CodeTypeRef Type {
get {
return CodeDomCodeTypeRef.FromCodeTypeReference(CodeObject.Type);
}
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#")]
set {
CodeObject.Type = CodeDomCodeTypeRef.ToCodeTypeReference(value);
CommitChanges();
}
}
public string get_Prototype(int Flags) {
throw new NotImplementedException();
}
#endregion
public override object ParentElement {
get { return parent; }
}
public override string FullName {
get { return CodeObject.Name; }
}
public override vsCMElement Kind {
get {
return vsCMElement.vsCMElementVariable;
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class TemplateSummary : IEquatable<TemplateSummary>
{
/// <summary>
/// The unique identifier of the template. If this is not provided, DocuSign will generate a value.
/// </summary>
/// <value>The unique identifier of the template. If this is not provided, DocuSign will generate a value.</value>
[DataMember(Name="templateId", EmitDefaultValue=false)]
public string TemplateId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="documentName", EmitDefaultValue=false)]
public string DocumentName { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="applied", EmitDefaultValue=false)]
public string Applied { get; set; }
/// <summary>
/// Gets or Sets TemplateMatch
/// </summary>
[DataMember(Name="templateMatch", EmitDefaultValue=false)]
public TemplateMatch TemplateMatch { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="uri", EmitDefaultValue=false)]
public string Uri { 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 TemplateSummary {\n");
sb.Append(" TemplateId: ").Append(TemplateId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" DocumentName: ").Append(DocumentName).Append("\n");
sb.Append(" Applied: ").Append(Applied).Append("\n");
sb.Append(" TemplateMatch: ").Append(TemplateMatch).Append("\n");
sb.Append(" Uri: ").Append(Uri).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 TemplateSummary);
}
/// <summary>
/// Returns true if TemplateSummary instances are equal
/// </summary>
/// <param name="other">Instance of TemplateSummary to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TemplateSummary other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TemplateId == other.TemplateId ||
this.TemplateId != null &&
this.TemplateId.Equals(other.TemplateId)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.DocumentName == other.DocumentName ||
this.DocumentName != null &&
this.DocumentName.Equals(other.DocumentName)
) &&
(
this.Applied == other.Applied ||
this.Applied != null &&
this.Applied.Equals(other.Applied)
) &&
(
this.TemplateMatch == other.TemplateMatch ||
this.TemplateMatch != null &&
this.TemplateMatch.Equals(other.TemplateMatch)
) &&
(
this.Uri == other.Uri ||
this.Uri != null &&
this.Uri.Equals(other.Uri)
);
}
/// <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.TemplateId != null)
hash = hash * 57 + this.TemplateId.GetHashCode();
if (this.Name != null)
hash = hash * 57 + this.Name.GetHashCode();
if (this.DocumentId != null)
hash = hash * 57 + this.DocumentId.GetHashCode();
if (this.DocumentName != null)
hash = hash * 57 + this.DocumentName.GetHashCode();
if (this.Applied != null)
hash = hash * 57 + this.Applied.GetHashCode();
if (this.TemplateMatch != null)
hash = hash * 57 + this.TemplateMatch.GetHashCode();
if (this.Uri != null)
hash = hash * 57 + this.Uri.GetHashCode();
return hash;
}
}
}
}
| |
/* 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:
*
* * 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Core;
namespace XenAdmin.Dialogs
{
public partial class ConfirmVMDeleteDialog : XenDialogBase
{
private const int MINIMUM_COL_WIDTH = 50;
public ConfirmVMDeleteDialog(IEnumerable<VM> vms)
{
Util.ThrowIfParameterNull(vms, "vms");
InitializeComponent();
pictureBox1.Image = SystemIcons.Warning.ToBitmap();
HelpButton = true;
// We have to set the header text again here because they're in base64
// encoding in the resx, so can't be easily localised: see CA-43371.
listView.Groups["listViewGroupAttachedDisks"].Header = Messages.ATTACHED_VIRTUAL_DISKS;
listView.Groups["listViewGroupSnapshots"].Header = Messages.SNAPSHOTS;
List<VM> vmList = new List<VM>(vms);
if (vmList.Count == 1)
{
String type = vmList[0].is_a_template ? Messages.TEMPLATE : Messages.VM;
Text = String.Format(Messages.CONFIRM_DELETE_TITLE, type);
}
else
{
Text = Messages.CONFIRM_DELETE_ITEMS_TITLE;
}
List<VDI> sharedVDIsCouldBeDelete=new List<VDI>();
foreach (VM vm in vmList)
{
foreach (VBD vbd in vm.Connection.ResolveAll(vm.VBDs))
{
if (!vbd.IsCDROM)
{
VDI vdi = vbd.Connection.Resolve(vbd.VDI);
if (vdi != null)
{
IList<VM> VMsUsingVDI = vdi.GetVMs();
bool allTheVMsAreDeleted = true;
if (VMsUsingVDI.Count > 1)
{
foreach (VM vmUsingVdi in VMsUsingVDI)
{
if (!vmList.Contains(vmUsingVdi))
{
allTheVMsAreDeleted = false;
break;
}
}
if (allTheVMsAreDeleted&&!sharedVDIsCouldBeDelete.Contains(vdi))
{
sharedVDIsCouldBeDelete.Add(vdi);
}
}
else
{
ListViewItem item = new ListViewItem();
item.Text = vdi.Name;
item.SubItems.Add(vm.Name);
item.Group = listView.Groups["listViewGroupAttachedDisks"];
item.Tag = vbd;
item.Checked = vbd.IsOwner;
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
subitem.Tag = subitem.Text;
listView.Items.Add(item);
}
}
}
}
foreach (VM snapshot in vm.Connection.ResolveAll(vm.snapshots))
{
ListViewItem item = new ListViewItem();
item.Text = snapshot.Name;
item.SubItems.Add(vm.Name);
item.Tag = snapshot;
item.Group = listView.Groups["listViewGroupSnapshots"];
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
subitem.Tag = subitem.Text;
listView.Items.Add(item);
}
}
foreach (VDI vdi in sharedVDIsCouldBeDelete)
{
ListViewItem item = new ListViewItem();
item.Text = vdi.Name;
item.SubItems.Add(vdi.VMsOfVDI);
item.Group = listView.Groups["listViewGroupAttachedDisks"];
item.Tag = vdi.Connection.ResolveAll(vdi.VBDs);
item.Checked = false;
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
subitem.Tag = subitem.Text;
listView.Items.Add(item);
}
EnableSelectAllClear();
EllipsizeStrings();
}
public ConfirmVMDeleteDialog(VM vm)
: this(new VM[] { vm })
{
}
public List<VBD> DeleteDisks
{
get
{
List<VBD> vbds = new List<VBD>();
foreach (ListViewItem item in listView.CheckedItems)
{
VBD vbd = item.Tag as VBD;
if (vbd != null)
vbds.Add(vbd);
List<VBD> vbdsList = item.Tag as List<VBD>;
if (vbdsList != null)
vbds.AddRange(vbdsList);
}
return vbds;
}
}
public List<VM> DeleteSnapshots
{
get
{
List<VM> snapshots = new List<VM>();
foreach (ListViewItem item in listView.CheckedItems)
{
VM snapshot = item.Tag as VM;
if (snapshot != null)
snapshots.Add(snapshot);
}
return snapshots;
}
}
private void EllipsizeStrings()
{
foreach (ColumnHeader col in listView.Columns)
EllipsizeStrings(col.Index);
}
private void EllipsizeStrings(int columnIndex)
{
foreach (ListViewItem item in listView.Items)
{
if (columnIndex < 0 || columnIndex >= item.SubItems.Count)
continue;
var subItem = item.SubItems[columnIndex];
string wholeText = subItem.Tag as string;
if (wholeText == null)
continue;
var rec = new Rectangle(subItem.Bounds.Left, subItem.Bounds.Top,
listView.Columns[columnIndex].Width, subItem.Bounds.Height);
subItem.Text = wholeText.Ellipsise(rec, subItem.Font);
listView.Invalidate(rec);
}
}
private void buttonSelectAll_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView.Items)
{
item.Checked = true;
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView.Items)
{
item.Checked = false;
}
}
private void EnableSelectAllClear()
{
bool allChecked = true;
bool allUnChecked = true;
foreach (ListViewItem item in listView.Items)
{
if (item.Checked)
allUnChecked = false;
else
allChecked = false;
}
buttonSelectAll.Enabled = !allChecked;
buttonClear.Enabled = !allUnChecked;
}
private void listView_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
if (e.ColumnIndex < 0 || e.ColumnIndex >= listView.Columns.Count)
return;
if (e.NewWidth < MINIMUM_COL_WIDTH)
{
e.NewWidth = MINIMUM_COL_WIDTH;
e.Cancel = true;
}
}
private void listView_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
{
EllipsizeStrings(e.ColumnIndex);
}
private void listView_ItemChecked(object sender, ItemCheckedEventArgs e)
{
EnableSelectAllClear();
}
private class ListViewDeleteDialog:ListView
{
private bool _b = false;
private string _msg = Messages.EMPTY_LIST_DISK_SNAPSHOTS;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (m.Msg == 20)
{
if (Items.Count == 0)
{
_b = true;
using (Graphics g = CreateGraphics())
{
int w = (Width - g.MeasureString(_msg, Font).ToSize().Width) / 2;
g.DrawString(_msg, Font, SystemBrushes.ControlText, w, 30);
}
}
else
{
if (_b)
{
Invalidate();
_b = false;
}
}
}
if (m.Msg == 4127)
Invalidate();
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact [email protected].
///
/// StyleSheetResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Preview.Understand.Assistant
{
public class StyleSheetResource : Resource
{
private static Request BuildFetchRequest(FetchStyleSheetOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Preview,
"/understand/Assistants/" + options.PathAssistantSid + "/StyleSheet",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Returns Style sheet JSON object for this Assistant
/// </summary>
/// <param name="options"> Fetch StyleSheet parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of StyleSheet </returns>
public static StyleSheetResource Fetch(FetchStyleSheetOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Returns Style sheet JSON object for this Assistant
/// </summary>
/// <param name="options"> Fetch StyleSheet parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of StyleSheet </returns>
public static async System.Threading.Tasks.Task<StyleSheetResource> FetchAsync(FetchStyleSheetOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Returns Style sheet JSON object for this Assistant
/// </summary>
/// <param name="pathAssistantSid"> The unique ID of the Assistant </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of StyleSheet </returns>
public static StyleSheetResource Fetch(string pathAssistantSid, ITwilioRestClient client = null)
{
var options = new FetchStyleSheetOptions(pathAssistantSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Returns Style sheet JSON object for this Assistant
/// </summary>
/// <param name="pathAssistantSid"> The unique ID of the Assistant </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of StyleSheet </returns>
public static async System.Threading.Tasks.Task<StyleSheetResource> FetchAsync(string pathAssistantSid,
ITwilioRestClient client = null)
{
var options = new FetchStyleSheetOptions(pathAssistantSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateStyleSheetOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Preview,
"/understand/Assistants/" + options.PathAssistantSid + "/StyleSheet",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Updates the style sheet for an assistant identified by {AssistantSid} or {AssistantUniqueName}.
/// </summary>
/// <param name="options"> Update StyleSheet parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of StyleSheet </returns>
public static StyleSheetResource Update(UpdateStyleSheetOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Updates the style sheet for an assistant identified by {AssistantSid} or {AssistantUniqueName}.
/// </summary>
/// <param name="options"> Update StyleSheet parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of StyleSheet </returns>
public static async System.Threading.Tasks.Task<StyleSheetResource> UpdateAsync(UpdateStyleSheetOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Updates the style sheet for an assistant identified by {AssistantSid} or {AssistantUniqueName}.
/// </summary>
/// <param name="pathAssistantSid"> The unique ID of the Assistant </param>
/// <param name="styleSheet"> The JSON Style sheet string </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of StyleSheet </returns>
public static StyleSheetResource Update(string pathAssistantSid,
object styleSheet = null,
ITwilioRestClient client = null)
{
var options = new UpdateStyleSheetOptions(pathAssistantSid){StyleSheet = styleSheet};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Updates the style sheet for an assistant identified by {AssistantSid} or {AssistantUniqueName}.
/// </summary>
/// <param name="pathAssistantSid"> The unique ID of the Assistant </param>
/// <param name="styleSheet"> The JSON Style sheet string </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of StyleSheet </returns>
public static async System.Threading.Tasks.Task<StyleSheetResource> UpdateAsync(string pathAssistantSid,
object styleSheet = null,
ITwilioRestClient client = null)
{
var options = new UpdateStyleSheetOptions(pathAssistantSid){StyleSheet = styleSheet};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a StyleSheetResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> StyleSheetResource object represented by the provided JSON </returns>
public static StyleSheetResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<StyleSheetResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique ID of the Account that created this Assistant
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The unique ID of the Assistant
/// </summary>
[JsonProperty("assistant_sid")]
public string AssistantSid { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The JSON style sheet object
/// </summary>
[JsonProperty("data")]
public object Data { get; private set; }
private StyleSheetResource()
{
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// ReSharper disable once CheckNamespace
namespace log4net.Util
{
using System;
using System.Text;
/// <summary>
/// Utility class that represents a format string.
/// </summary>
/// <remarks>
/// <para>
/// Utility class that represents a format string.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
public sealed class SystemStringFormat
{
/// <summary>
/// The fully qualified type of the SystemStringFormat class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private static readonly Type declaringType = typeof(SystemStringFormat);
private readonly object[] m_args;
private readonly string m_format;
private readonly IFormatProvider m_provider;
/// <summary>
/// Initialise the <see cref="SystemStringFormat"/>
/// </summary>
/// <param name="provider">An <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="System.String"/> containing zero or more format items.</param>
/// <param name="args">An <see cref="System.Object"/> array containing zero or more objects to format.</param>
public SystemStringFormat(IFormatProvider provider, string format, params object[] args)
{
this.m_provider = provider;
this.m_format = format;
this.m_args = args;
}
/// <summary>
/// Format the string and arguments
/// </summary>
/// <returns>the formatted string</returns>
public override string ToString()
{
return StringFormat(this.m_provider, this.m_format, this.m_args);
}
/// <summary>
/// Dump the contents of an array into a string builder
/// </summary>
private static void RenderArray(Array array, StringBuilder buffer)
{
if (array == null)
{
buffer.Append(SystemInfo.NullText);
}
else
{
if (array.Rank != 1)
{
buffer.Append(array.ToString());
}
else
{
buffer.Append("{");
var len = array.Length;
if (len > 0)
{
RenderObject(array.GetValue(0), buffer);
for (var i = 1; i < len; i++)
{
buffer.Append(", ");
RenderObject(array.GetValue(i), buffer);
}
}
buffer.Append("}");
}
}
}
/// <summary>
/// Dump an object to a string
/// </summary>
private static void RenderObject(Object obj, StringBuilder buffer)
{
if (obj == null)
{
buffer.Append(SystemInfo.NullText);
}
else
{
try
{
buffer.Append(obj);
}
catch (Exception ex)
{
buffer.Append("<Exception: ").Append(ex.Message).Append(">");
}
#if !NET_2_0 && !MONO_2_0
catch
{
buffer.Append("<Exception>");
}
#endif
}
}
/// <summary>
/// Replaces the format item in a specified <see cref="System.String"/> with the text equivalent
/// of the value of a corresponding <see cref="System.Object"/> instance in a specified array.
/// A specified parameter supplies culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="System.IFormatProvider"/> that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="System.String"/> containing zero or more format items.</param>
/// <param name="args">An <see cref="System.Object"/> array containing zero or more objects to format.</param>
/// <returns>
/// A copy of format in which the format items have been replaced by the <see cref="System.String"/>
/// equivalent of the corresponding instances of <see cref="System.Object"/> in args.
/// </returns>
/// <remarks>
/// <para>
/// This method does not throw exceptions. If an exception thrown while formatting the result the
/// exception and arguments are returned in the result string.
/// </para>
/// </remarks>
private static string StringFormat(IFormatProvider provider, string format, params object[] args)
{
try
{
// The format is missing, log null value
if (format == null)
{
return null;
}
// The args are missing - should not happen unless we are called explicitly with a null array
if (args == null)
{
return format;
}
// Try to format the string
return String.Format(provider, format, args);
}
catch (Exception ex)
{
LogLog.Warn(declaringType, "Exception while rendering format [" + format + "]", ex);
return StringFormatError(ex, format, args);
}
#if !NET_2_0 && !MONO_2_0
catch
{
LogLog.Warn(declaringType, "Exception while rendering format [" + format + "]");
return StringFormatError(null, format, args);
}
#endif
}
/// <summary>
/// Process an error during StringFormat
/// </summary>
private static string StringFormatError(Exception formatException, string format, object[] args)
{
try
{
var buf = new StringBuilder("<log4net.Error>");
if (formatException != null)
{
buf.Append("Exception during StringFormat: ").Append(formatException.Message);
}
else
{
buf.Append("Exception during StringFormat");
}
buf.Append(" <format>").Append(format).Append("</format>");
buf.Append("<args>");
RenderArray(args, buf);
buf.Append("</args>");
buf.Append("</log4net.Error>");
return buf.ToString();
}
catch (Exception ex)
{
LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling", ex);
return "<log4net.Error>Exception during StringFormat. See Internal Log.</log4net.Error>";
}
#if !NET_2_0 && !MONO_2_0
catch
{
LogLog.Error(declaringType, "INTERNAL ERROR during StringFormat error handling");
return "<log4net.Error>Exception during StringFormat. See Internal Log.</log4net.Error>";
}
#endif
}
}
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Clauses.StreamedData;
using Remotion.Linq.Utilities;
namespace Remotion.Linq.Clauses.ResultOperators
{
/// <summary>
/// Represents aggregating the items returned by a query into a single value with an initial seeding value.
/// This is a result operator, operating on the whole result set of a query.
/// </summary>
/// <example>
/// In C#, the "Aggregate" call in the following example corresponds to an <see cref="AggregateFromSeedResultOperator"/>.
/// <code>
/// var result = (from s in Students
/// select s).Aggregate(0, (totalAge, s) => totalAge + s.Age);
/// </code>
/// </example>
public class AggregateFromSeedResultOperator : ValueFromSequenceResultOperatorBase
{
private static readonly MethodInfo s_executeMethod =
typeof(AggregateFromSeedResultOperator).GetRuntimeMethodChecked("ExecuteAggregateInMemory", new[] { typeof(StreamedSequence) });
private Expression _seed;
private LambdaExpression _func;
private LambdaExpression _resultSelector;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateFromSeedResultOperator"/> class.
/// </summary>
/// <param name="seed">The seed expression.</param>
/// <param name="func">The aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so
/// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators
/// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.</param>
/// <param name="optionalResultSelector">The result selector, can be <see langword="null" />.</param>
public AggregateFromSeedResultOperator(Expression seed, LambdaExpression func, LambdaExpression optionalResultSelector)
{
if (func.Type.IsGenericTypeDefinition)
throw new ArgumentException("Open generic delegates are not supported with AggregateFromSeedResultOperator", "func");
Seed = seed;
Func = func;
OptionalResultSelector = optionalResultSelector;
}
/// <summary>
/// Gets or sets the aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so
/// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators
/// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.
/// </summary>
/// <value>The aggregating function.</value>
public LambdaExpression Func
{
get { return _func; }
set
{
if (value.Type.IsGenericTypeDefinition)
throw new ArgumentException("Open generic delegates are not supported with AggregateFromSeedResultOperator", "value");
if (!DescribesValidFuncType(value))
{
var message = string.Format(
"The aggregating function must be a LambdaExpression that describes an instantiation of 'Func<TAccumulate,TAccumulate>', but it is '{0}'.",
value.Type);
throw new ArgumentException(message, "value");
}
_func = value;
}
}
/// <summary>
/// Gets or sets the seed of the accumulation. This is an <see cref="Expression"/> denoting the starting value of the aggregation.
/// </summary>
/// <value>The seed of the accumulation.</value>
public Expression Seed
{
get { return _seed; }
set { _seed = value; }
}
/// <summary>
/// Gets or sets the result selector. This is a <see cref="LambdaExpression"/> applied after the aggregation to select the final value.
/// Can be <see langword="null" />.
/// </summary>
/// <value>The result selector.</value>
public LambdaExpression OptionalResultSelector
{
get { return _resultSelector; }
set
{
if (value != null && value.Type.IsGenericTypeDefinition)
throw new ArgumentException("Open generic delegates are not supported with AggregateFromSeedResultOperator", "value");
if (!DescribesValidResultSelectorType(value))
{
var message = string.Format(
"The result selector must be a LambdaExpression that describes an instantiation of 'Func<TAccumulate,TResult>', but it is '{0}'.",
value.Type);
throw new ArgumentException(message, "value");
}
_resultSelector = value;
}
}
/// <summary>
/// Gets the constant value of the <see cref="Seed"/> property, assuming it is a <see cref="ConstantExpression"/>. If it is
/// not, an <see cref="InvalidOperationException"/> is thrown.
/// </summary>
/// <typeparam name="T">The expected seed type. If the item is not of this type, an <see cref="InvalidOperationException"/> is thrown.</typeparam>
/// <returns>The constant value of the <see cref="Seed"/> property.</returns>
public T GetConstantSeed<T>()
{
return GetConstantValueFromExpression<T>("seed", Seed);
}
/// <inheritdoc cref="ResultOperatorBase.ExecuteInMemory" />
public override StreamedValue ExecuteInMemory<TInput>(StreamedSequence input)
{
var closedExecuteMethod = s_executeMethod.MakeGenericMethod(typeof(TInput), Seed.Type, GetResultType());
return (StreamedValue)InvokeExecuteMethod(closedExecuteMethod, input);
}
/// <summary>
/// Executes the aggregating operation in memory.
/// </summary>
/// <typeparam name="TInput">The type of the source items.</typeparam>
/// <typeparam name="TAggregate">The type of the aggregated items.</typeparam>
/// <typeparam name="TResult">The type of the result items.</typeparam>
/// <param name="input">The input sequence.</param>
/// <returns>A <see cref="StreamedValue"/> object holding the aggregated value.</returns>
public StreamedValue ExecuteAggregateInMemory<TInput, TAggregate, TResult>(StreamedSequence input)
{
var sequence = input.GetTypedSequence<TInput>();
var seed = GetConstantSeed<TAggregate>();
var funcLambda = ReverseResolvingExpressionTreeVisitor.ReverseResolveLambda(input.DataInfo.ItemExpression, Func, 1);
var func = (Func<TAggregate, TInput, TAggregate>)funcLambda.Compile();
var aggregated = sequence.Aggregate(seed, func);
var outputDataInfo = (StreamedValueInfo)GetOutputDataInfo(input.DataInfo);
if (OptionalResultSelector == null)
{
return new StreamedValue(aggregated, outputDataInfo);
}
else
{
var resultSelector = (Func<TAggregate, TResult>)OptionalResultSelector.Compile();
var result = resultSelector(aggregated);
return new StreamedValue(result, outputDataInfo);
}
}
/// <inheritdoc />
public override ResultOperatorBase Clone(CloneContext cloneContext)
{
return new AggregateFromSeedResultOperator(Seed, Func, OptionalResultSelector);
}
/// <inheritdoc />
public override IStreamedDataInfo GetOutputDataInfo(IStreamedDataInfo inputInfo)
{
var aggregatedType = Func.Type.GetGenericArguments()[0];
if (!aggregatedType.IsAssignableFrom(Seed.Type))
{
var message = string.Format(
"The seed expression and the aggregating function don't have matching types. The seed is of type '{0}', but the function aggregates '{1}'.",
Seed.Type,
aggregatedType);
throw new InvalidOperationException(message);
}
var resultTransformedType = OptionalResultSelector != null ? OptionalResultSelector.Type.GetGenericArguments()[0] : null;
if (resultTransformedType != null && aggregatedType != resultTransformedType)
{
var message = string.Format(
"The aggregating function and the result selector don't have matching types. The function aggregates type '{0}', "
+ "but the result selector takes '{1}'.",
aggregatedType,
resultTransformedType);
throw new InvalidOperationException(message);
}
var resultType = GetResultType();
return new StreamedScalarValueInfo(resultType);
}
public override void TransformExpressions(Func<Expression, Expression> transformation)
{
Seed = transformation(Seed);
Func = (LambdaExpression)transformation(Func);
if (OptionalResultSelector != null)
OptionalResultSelector = (LambdaExpression)transformation(OptionalResultSelector);
}
/// <inheritdoc />
public override string ToString()
{
if (OptionalResultSelector != null)
{
return string.Format(
"Aggregate({0}, {1}, {2})",
FormattingExpressionTreeVisitor.Format(Seed),
FormattingExpressionTreeVisitor.Format(Func),
FormattingExpressionTreeVisitor.Format(OptionalResultSelector));
}
else
{
return string.Format(
"Aggregate({0}, {1})",
FormattingExpressionTreeVisitor.Format(Seed),
FormattingExpressionTreeVisitor.Format(Func));
}
}
private Type GetResultType()
{
return OptionalResultSelector != null ? OptionalResultSelector.Body.Type : Func.Body.Type;
}
private bool DescribesValidFuncType(LambdaExpression value)
{
var funcType = value.Type;
if (!funcType.IsGenericType || funcType.GetGenericTypeDefinition() != typeof(Func<,>))
return false;
var genericArguments = funcType.GetGenericArguments();
return genericArguments[0] == genericArguments[1];
}
private bool DescribesValidResultSelectorType(LambdaExpression value)
{
return value == null || (value.Type.IsGenericType && value.Type.GetGenericTypeDefinition() == typeof(Func<,>));
}
}
}
| |
#define ASTAR_MORE_AREAS // Increases the number of areas to 65535 but reduces the maximum number of graphs to 4. Disabling gives a max number of areas of 1023 and 32 graphs.
//#define ASTAR_NO_PENALTY // Enabling this disables the use of penalties. Reduces memory usage.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using Pathfinding.Nodes;
using Pathfinding.Serialization;
namespace Pathfinding.Nodes {
//class A{}
}
namespace Pathfinding {
public delegate void GraphNodeDelegate (GraphNode node);
public delegate bool GraphNodeDelegateCancelable (GraphNode node);
[System.Obsolete("This class has been replaced with GraphNode, it may be removed in future versions",true)]
public class Node {
}
public abstract class GraphNode {
private int nodeIndex;
protected uint flags;
/** Penlty cost for walking on this node. This can be used to make it harder/slower to walk over certain areas. */
private uint penalty;
// Some fallback properties
[System.Obsolete ("This attribute is deprecated. Please use .position (not a capital P)")]
public Int3 Position { get { return position; } }
[System.Obsolete ("This attribute is deprecated. Please use .Walkable (with a capital W)")]
public bool walkable { get { return Walkable; } set { Walkable = value; } }
[System.Obsolete ("This attribute is deprecated. Please use .Tag (with a capital T)")]
public uint tags { get { return Tag; } set { Tag = value; } }
[System.Obsolete ("This attribute is deprecated. Please use .GraphIndex (with a capital G)")]
public uint graphIndex { get { return GraphIndex; } set { GraphIndex = value; } }
// End of fallback
/** Constructor for a graph node. */
public GraphNode (AstarPath astar) {
//this.nodeIndex = NextNodeIndex++;
if (astar != null) {
this.nodeIndex = astar.GetNewNodeIndex();
astar.InitializeNode (this);
} else {
throw new System.Exception ("No active AstarPath object to bind to");
}
}
/** Destroys the node.
* Cleans up any temporary pathfinding data used for this node.
* The graph is responsible for calling this method on nodes when they are destroyed, including when the whole graph is destoyed.
* Otherwise memory leaks might present themselves.
*
* Once called, subsequent calls to this method will not do anything.
*
* \note Assumes the current active AstarPath instance is the same one that created this node.
*/
public void Destroy () {
//Already destroyed
if (nodeIndex == -1) return;
ClearConnections(true);
if (AstarPath.active != null) {
AstarPath.active.DestroyNode(this);
}
nodeIndex = -1;
//System.Console.WriteLine ("~");
}
public bool Destroyed {
get {
return nodeIndex == -1;
}
}
//~GraphNode () {
//Debug.Log ("Destroyed GraphNode " + nodeIndex);
//}
public int NodeIndex { get {return nodeIndex;}}
public Int3 position;
#region Constants
/** Position of the walkable bit. \see Walkable */
const int FlagsWalkableOffset = 0;
/** Mask of the walkable bit. \see Walkable */
const uint FlagsWalkableMask = 1 << FlagsWalkableOffset;
/** Start of region bits. \see Area */
const int FlagsAreaOffset = 1;
/** Mask of region bits. \see Area */
const uint FlagsAreaMask = (1024-1) << FlagsAreaOffset;
/** Start of graph index bits. \see GraphIndex */
const int FlagsGraphOffset = 11;
/** Mask of graph index bits. \see GraphIndex */
const uint FlagsGraphMask = (32-1) << FlagsGraphOffset;
public const uint MaxRegionCount = FlagsAreaMask >> FlagsAreaOffset;
/** Max number of graphs */
public const uint MaxGraphCount = FlagsGraphMask >> FlagsGraphOffset;
/** Start of tag bits. \see Tag */
const int FlagsTagOffset = 19;
/** Mask of tag bits. \see Tag */
const uint FlagsTagMask = (32-1) << FlagsTagOffset;
#endregion
#region Properties
/** Holds various bitpacked variables.
*/
public uint Flags {
get {
return flags;
}
set {
flags = value;
}
}
/** Penalty cost for walking on this node. This can be used to make it harder/slower to walk over certain areas. */
public uint Penalty {
get {
return penalty;
}
set {
if (value > 0xFFFFF)
Debug.LogWarning ("Very high penalty applied. Are you sure negative values haven't underflowed?\n" +
"Penalty values this high could with long paths cause overflows and in some cases infinity loops because of that.\n" +
"Penalty value applied: "+value);
penalty = value;
}
}
/** True if the node is traversable */
public bool Walkable {
get {
return (flags & FlagsWalkableMask) != 0;
}
set {
flags = flags & ~FlagsWalkableMask | (value ? 1U : 0U) << FlagsWalkableOffset;
}
}
public uint Area {
get {
return (flags & FlagsAreaMask) >> FlagsAreaOffset;
}
set {
//Awesome! No parentheses
flags = flags & ~FlagsAreaMask | value << FlagsAreaOffset;
}
}
public uint GraphIndex {
get {
return (flags & FlagsGraphMask) >> FlagsGraphOffset;
}
set {
flags = flags & ~FlagsGraphMask | value << FlagsGraphOffset;
}
}
public uint Tag {
get {
return (flags & FlagsTagMask) >> FlagsTagOffset;
}
set {
flags = flags & ~FlagsTagMask | value << FlagsTagOffset;
}
}
#endregion
public void UpdateG (Path path, PathNode pathNode) {
pathNode.G = pathNode.parent.G + pathNode.cost + path.GetTraversalCost(this);
}
public virtual void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
//Simple but slow default implementation
UpdateG (path,pathNode);
handler.PushNode (pathNode);
GetConnections (delegate (GraphNode other) {
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG (path, otherPN,handler);
});
}
public virtual void FloodFill (Stack<GraphNode> stack, uint region) {
//Simple but slow default implementation
GetConnections (delegate (GraphNode other) {
if (other.Area != region) {
other.Area = region;
stack.Push (other);
}
});
}
/** Calls the delegate with all connections from this node */
public abstract void GetConnections (GraphNodeDelegate del);
public abstract void AddConnection (GraphNode node, uint cost);
public abstract void RemoveConnection (GraphNode node);
/** Remove all connections from this node.
* \param alsoReverse if true, neighbours will be requested to remove connections to this node.
*/
public abstract void ClearConnections (bool alsoReverse);
/** Checks if this node has a connection to the specified node */
public virtual bool ContainsConnection (GraphNode node) {
//Simple but slow default implementation
bool contains = false;
GetConnections (delegate (GraphNode n) {
if (n == node) contains = true;
});
return contains;
}
/** Recalculates all connection costs from this node.
* Depending on the node type, this may or may not be supported.
* Nothing will be done if the operation is not supported
* \todo Use interface?
*/
public virtual void RecalculateConnectionCosts () {
}
/** Add a portal from this node to the specified node.
* This function should add a portal to the left and right lists which is connecting the two nodes (\a this and \a other).
*
* \param other The node which is on the other side of the portal (strictly speaking it does not actually have to be on the other side of the portal though).
* \param left List of portal points on the left side of the funnel
* \param right List of portal points on the right side of the funnel
* \param backwards If this is true, the call was made on a node with the \a other node as the node before this one in the path.
* In this case you may choose to do nothing since a similar call will be made to the \a other node with this node referenced as \a other (but then with backwards = true).
* You do not have to care about switching the left and right lists, that is done for you already.
*
* \returns True if the call was deemed successful. False if some unknown case was encountered and no portal could be added.
* If both calls to node1.GetPortal (node2,...) and node2.GetPortal (node1,...) return false, the funnel modifier will fall back to adding to the path
* the positions of the node.
*
* The default implementation simply returns false.
*
* This function may add more than one portal if necessary.
*
* \see http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html
*/
public virtual bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) {
return false;
}
/** Open the node */
public abstract void Open (Path path, PathNode pathNode, PathHandler handler);
public virtual void SerializeNode (GraphSerializationContext ctx) {
//Write basic node data.
ctx.writer.Write (Penalty);
ctx.writer.Write (Flags);
}
public virtual void DeserializeNode (GraphSerializationContext ctx) {
Penalty = ctx.reader.ReadUInt32();
Flags = ctx.reader.ReadUInt32();
}
/** Used to serialize references to other nodes e.g connections.
* Use the GraphSerializationContext.GetNodeIdentifier and
* GraphSerializationContext.GetNodeFromIdentifier methods
* for serialization and deserialization respectively.
*
* Nodes must override this method and serialize their connections.
* Graph generators do not need to call this method, it will be called automatically on all
* nodes at the correct time by the serializer.
*/
public virtual void SerializeReferences (GraphSerializationContext ctx) {
}
/** Used to deserialize references to other nodes e.g connections.
* Use the GraphSerializationContext.GetNodeIdentifier and
* GraphSerializationContext.GetNodeFromIdentifier methods
* for serialization and deserialization respectively.
*
* Nodes must override this method and serialize their connections.
* Graph generators do not need to call this method, it will be called automatically on all
* nodes at the correct time by the serializer.
*/
public virtual void DeserializeReferences (GraphSerializationContext ctx) {
}
}
public abstract class MeshNode : GraphNode {
public MeshNode (AstarPath astar) : base (astar) {
}
public GraphNode[] connections;
public uint[] connectionCosts;
public abstract Int3 GetVertex (int i);
public abstract int GetVertexCount ();
public abstract Vector3 ClosestPointOnNode (Vector3 p);
public abstract Vector3 ClosestPointOnNodeXZ (Vector3 p);
public override void ClearConnections (bool alsoReverse) {
if (alsoReverse && connections != null) {
for (int i=0;i<connections.Length;i++) {
connections[i].RemoveConnection (this);
}
}
connections = null;
connectionCosts = null;
}
public override void GetConnections (GraphNodeDelegate del) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) del (connections[i]);
}
public override void FloodFill (Stack<GraphNode> stack, uint region) {
//Faster, more specialized implementation to override the slow default implementation
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (other.Area != region) {
other.Area = region;
stack.Push (other);
}
}
}
public override bool ContainsConnection (GraphNode node) {
for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true;
return false;
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler)
{
UpdateG (path,pathNode);
handler.PushNode (pathNode);
for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
other.UpdateRecursiveG (path, otherPN,handler);
}
}
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (connections != null) {
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
connectionCosts[i] = cost;
return;
}
}
}
int connLength = connections != null ? connections.Length : 0;
GraphNode[] newconns = new GraphNode[connLength+1];
uint[] newconncosts = new uint[connLength+1];
for (int i=0;i<connLength;i++) {
newconns[i] = connections[i];
newconncosts[i] = connectionCosts[i];
}
newconns[connLength] = node;
newconncosts[connLength] = cost;
connections = newconns;
connectionCosts = newconncosts;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
int connLength = connections.Length;
GraphNode[] newconns = new GraphNode[connLength-1];
uint[] newconncosts = new uint[connLength-1];
for (int j=0;j<i;j++) {
newconns[j] = connections[j];
newconncosts[j] = connectionCosts[j];
}
for (int j=i+1;j<connLength;j++) {
newconns[j-1] = connections[j];
newconncosts[j-1] = connectionCosts[j];
}
connections = newconns;
connectionCosts = newconncosts;
return;
}
}
}
/** Checks if \a p is inside the node
*
* The default implementation uses XZ space and is in large part got from the website linked below
* \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5)
*/
public virtual bool ContainsPoint (Int3 p) {
bool inside = false;
int count = GetVertexCount();
for (int i = 0, j=count-1; i < count; j = i++) {
if ( ((GetVertex(i).z <= p.z && p.z < GetVertex(j).z) || (GetVertex(j).z <= p.z && p.z < GetVertex(i).z)) &&
(p.x < (GetVertex(j).x - GetVertex(i).x) * (p.z - GetVertex(i).z) / (GetVertex(j).z - GetVertex(i).z) + GetVertex(i).x))
inside = !inside;
}
return inside;
}
public override void SerializeReferences (GraphSerializationContext ctx)
{
if (connections == null) {
ctx.writer.Write(-1);
} else {
ctx.writer.Write (connections.Length);
for (int i=0;i<connections.Length;i++) {
ctx.writer.Write (ctx.GetNodeIdentifier (connections[i]));
ctx.writer.Write (connectionCosts[i]);
}
}
}
public override void DeserializeReferences (GraphSerializationContext ctx)
{
int count = ctx.reader.ReadInt32();
if (count == -1) {
connections = null;
connectionCosts = null;
} else {
connections = new GraphNode[count];
connectionCosts = new uint[count];
for (int i=0;i<count;i++) {
connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32());
connectionCosts[i] = ctx.reader.ReadUInt32();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the ContentType Service, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public class ContentTypeService : ContentTypeServiceBase, IContentTypeService
{
private readonly IContentService _contentService;
private readonly IMediaService _mediaService;
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public ContentTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IContentService contentService, IMediaService mediaService)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
if (contentService == null) throw new ArgumentNullException("contentService");
if (mediaService == null) throw new ArgumentNullException("mediaService");
_contentService = contentService;
_mediaService = mediaService;
}
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllPropertyTypeAliases();
}
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, int parentId = -1)
{
IContentType parent = null;
if (parentId > 0)
{
parent = GetContentType(parentId);
if (parent == null)
{
throw new InvalidOperationException("Could not find content type with id " + parentId);
}
}
return Copy(original, alias, name, parent);
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to, default is null (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, IContentType parent)
{
Mandate.ParameterNotNull(original, "original");
Mandate.ParameterNotNullOrEmpty(alias, "alias");
if (parent != null)
{
Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity"));
}
var clone = original.DeepCloneWithResetIdentities(alias);
clone.Name = name;
var compositionAliases = clone.CompositionAliases().Except(new[] { alias }).ToList();
//remove all composition that is not it's current alias
foreach (var a in compositionAliases)
{
clone.RemoveContentType(a);
}
//if a parent is specified set it's composition and parent
if (parent != null)
{
//add a new parent composition
clone.AddContentType(parent);
clone.ParentId = parent.Id;
}
else
{
//set to root
clone.ParentId = -1;
}
Save(clone);
return clone;
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(string alias)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.Alias == alias);
var contentTypes = repository.GetByQuery(query);
return contentTypes.FirstOrDefault();
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Key
/// </summary>
/// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return Enumerable.Empty<IContentType>();
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return false;
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// This is called after an IContentType is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
/// </summary>
/// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param>
private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes)
{
var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray();
if (toUpdate.Any())
{
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
{
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else
{
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
}
else if (firstType is IMediaType)
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
}
}
}
public void Validate(IContentTypeComposition compo)
{
using (new WriteLock(Locker))
{
ValidateLocked(compo);
}
}
private void ValidateLocked(IContentTypeComposition compositionContentType)
{
// performs business-level validation of the composition
// should ensure that it is absolutely safe to save the composition
// eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
// but that cannot be used (conflict with descendants)
var contentType = compositionContentType as IContentType;
var mediaType = compositionContentType as IMediaType;
IContentTypeComposition[] allContentTypes;
if (contentType != null)
allContentTypes = GetAllContentTypes().Cast<IContentTypeComposition>().ToArray();
else if (mediaType != null)
allContentTypes = GetAllMediaTypes().Cast<IContentTypeComposition>().ToArray();
else
throw new Exception("Composition is neither IContentType nor IMediaType?");
var compositionAliases = compositionContentType.CompositionAliases();
var compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
var indirectReferences = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
var comparer = new DelegateEqualityComparer<IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
var dependencies = new HashSet<IContentTypeComposition>(compositions, comparer);
var stack = new Stack<IContentTypeComposition>();
indirectReferences.ForEach(stack.Push);//Push indirect references to a stack, so we can add recursively
while (stack.Count > 0)
{
var indirectReference = stack.Pop();
dependencies.Add(indirectReference);
//Get all compositions for the current indirect reference
var directReferences = indirectReference.ContentTypeComposition;
foreach (var directReference in directReferences)
{
if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias)) continue;
dependencies.Add(directReference);
//A direct reference has compositions of its own - these also need to be taken into account
var directReferenceGraph = directReference.CompositionAliases();
allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))).ForEach(c => dependencies.Add(c));
}
//Recursive lookup of indirect references
allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)).ForEach(stack.Push);
}
foreach (var dependency in dependencies)
{
if (dependency.Id == compositionContentType.Id) continue;
var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
if (contentTypeDependency == null) continue;
var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
if (intersect.Length == 0) continue;
var message = string.Format("The following PropertyType aliases from the current ContentType conflict with existing PropertyType aliases: {0}.",
string.Join(", ", intersect));
throw new Exception(message);
}
}
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IContentType contentType, int userId = 0)
{
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
ValidateLocked(contentType); // throws if invalid
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
uow.Commit();
}
UpdateContentXmlStructure(contentType);
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(contentType, false), this);
Audit(AuditType.Save, string.Format("Save ContentType performed by user"), userId, contentType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var contentType in asArray)
{
ValidateLocked(contentType); // throws if invalid
}
foreach (var contentType in asArray)
{
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save ContentTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
public void Delete(IContentType contentType, int userId = 0)
{
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
_contentService.DeleteContentOfType(contentType.Id);
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
repository.Delete(contentType);
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(contentType, false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects.
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>
/// Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/>
/// </remarks>
public void Delete(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var contentType in asArray)
{
_contentService.DeleteContentOfType(contentType.Id);
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
foreach (var contentType in asArray)
{
repository.Delete(contentType);
}
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(asArray, false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(string alias)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.Alias == alias);
var contentTypes = repository.GetByQuery(query);
return contentTypes.FirstOrDefault();
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return Enumerable.Empty<IMediaType>();
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return false;
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Saves a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user saving the MediaType</param>
public void Save(IMediaType mediaType, int userId = 0)
{
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
ValidateLocked(mediaType); // throws if invalid
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
uow.Commit();
}
UpdateContentXmlStructure(mediaType);
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(mediaType, false), this);
Audit(AuditType.Save, string.Format("Save MediaType performed by user"), userId, mediaType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user savging the MediaTypes</param>
public void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var mediaType in asArray)
{
ValidateLocked(mediaType); // throws if invalid
}
foreach (var mediaType in asArray)
{
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save MediaTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to delete</param>
/// <param name="userId">Optional Id of the user deleting the MediaType</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IMediaType mediaType, int userId = 0)
{
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
_mediaService.DeleteMediaOfType(mediaType.Id, userId);
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
repository.Delete(mediaType);
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(mediaType, false), this);
}
Audit(AuditType.Delete, string.Format("Delete MediaType performed by user"), userId, mediaType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param>
/// <param name="userId"></param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var mediaType in asArray)
{
_mediaService.DeleteMediaOfType(mediaType.Id);
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
foreach (var mediaType in asArray)
{
repository.Delete(mediaType);
}
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(asArray, false), this);
}
Audit(AuditType.Delete, string.Format("Delete MediaTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Generates the complete (simplified) XML DTD.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetDtd()
{
var dtd = new StringBuilder();
dtd.AppendLine("<!DOCTYPE root [ ");
dtd.AppendLine(GetContentTypesDtd());
dtd.AppendLine("]>");
return dtd.ToString();
}
/// <summary>
/// Generates the complete XML DTD without the root.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetContentTypesDtd()
{
var dtd = new StringBuilder();
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
dtd.AppendLine("<!ELEMENT node ANY> <!ATTLIST node id ID #REQUIRED> <!ELEMENT data ANY>");
}
else
{
try
{
var strictSchemaBuilder = new StringBuilder();
var contentTypes = GetAllContentTypes();
foreach (ContentType contentType in contentTypes)
{
string safeAlias = contentType.Alias.ToUmbracoAlias();
if (safeAlias != null)
{
strictSchemaBuilder.AppendLine(String.Format("<!ELEMENT {0} ANY>", safeAlias));
strictSchemaBuilder.AppendLine(String.Format("<!ATTLIST {0} id ID #REQUIRED>", safeAlias));
}
}
// Only commit the strong schema to the container if we didn't generate an error building it
dtd.Append(strictSchemaBuilder);
}
catch (Exception exception)
{
LogHelper.Error<ContentTypeService>("Error while trying to build DTD for Xml schema; is Umbraco installed correctly and the connection string configured?", exception);
}
}
return dtd.ToString();
}
private void Audit(AuditType type, string message, int userId, int objectId)
{
var uow = UowProvider.GetUnitOfWork();
using (var auditRepo = RepositoryFactory.CreateAuditRepository(uow))
{
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
}
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletingContentType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletedContentType;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletingMediaType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletedMediaType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavingContentType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavedContentType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavingMediaType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavedMediaType;
#endregion
}
}
| |
using UnityEngine;
public class SfxrParams {
/**
* SfxrSynth
*
* Copyright 2010 Thomas Vian
* Copyright 2013 Zeh Fernando
*
* 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.
*
*/
/**
* SfxrParams
* Holds parameters used by SfxrSynth
*
* @author Zeh Fernando
*/
// Properties
public bool paramsDirty; // Whether the parameters have been changed since last time (shouldn't used cached sound)
private uint _waveType = 0; // Shape of wave to generate (see enum WaveType)
private float _masterVolume = 0.5f; // Overall volume of the sound (0 to 1)
private float _attackTime = 0.0f; // Length of the volume envelope attack (0 to 1)
private float _sustainTime = 0.0f; // Length of the volume envelope sustain (0 to 1)
private float _sustainPunch = 0.0f; // Tilts the sustain envelope for more 'pop' (0 to 1)
private float _decayTime = 0.0f; // Length of the volume envelope decay (yes, I know it's called release) (0 to 1)
private float _startFrequency = 0.0f; // Base note of the sound (0 to 1)
private float _minFrequency = 0.0f; // If sliding, the sound will stop at this frequency, to prevent really low notes (0 to 1)
private float _slide = 0.0f; // Slides the note up or down (-1 to 1)
private float _deltaSlide = 0.0f; // Accelerates the slide (-1 to 1)
private float _vibratoDepth = 0.0f; // Strength of the vibrato effect (0 to 1)
private float _vibratoSpeed = 0.0f; // Speed of the vibrato effect (i.e. frequency) (0 to 1)
private float _changeAmount = 0.0f; // Shift in note, either up or down (-1 to 1)
private float _changeSpeed = 0.0f; // How fast the note shift happens (only happens once) (0 to 1)
private float _squareDuty = 0.0f; // Controls the ratio between the up and down states of the square wave, changing the tibre (0 to 1)
private float _dutySweep = 0.0f; // Sweeps the duty up or down (-1 to 1)
private float _repeatSpeed = 0.0f; // Speed of the note repeating - certain variables are reset each time (0 to 1)
private float _phaserOffset = 0.0f; // Offsets a second copy of the wave by a small phase, changing the tibre (-1 to 1)
private float _phaserSweep = 0.0f; // Sweeps the phase up or down (-1 to 1)
private float _lpFilterCutoff = 0.0f; // Frequency at which the low-pass filter starts attenuating higher frequencies (0 to 1)
private float _lpFilterCutoffSweep = 0.0f; // Sweeps the low-pass cutoff up or down (-1 to 1)
private float _lpFilterResonance = 0.0f; // Changes the attenuation rate for the low-pass filter, changing the timbre (0 to 1)
private float _hpFilterCutoff = 0.0f; // Frequency at which the high-pass filter starts attenuating lower frequencies (0 to 1)
private float _hpFilterCutoffSweep = 0.0f; // Sweeps the high-pass cutoff up or down (-1 to 1)
// From BFXR
private float _changeRepeat = 0.0f; // Pitch Jump Repeat Speed: larger Values means more pitch jumps, which can be useful for arpeggiation (0 to 1)
private float _changeAmount2 = 0.0f; // Shift in note, either up or down (-1 to 1)
private float _changeSpeed2 = 0.0f; // How fast the note shift happens (only happens once) (0 to 1)
private float _compressionAmount = 0.0f; // Compression: pushes amplitudes together into a narrower range to make them stand out more. Very good for sound effects, where you want them to stick out against background music (0 to 1)
private float _overtones = 0.0f; // Harmonics: overlays copies of the waveform with copies and multiples of its frequency. Good for bulking out or otherwise enriching the texture of the sounds (warning: this is the number 1 cause of usfxr slowdown!) (0 to 1)
private float _overtoneFalloff = 0.0f; // Harmonics falloff: the rate at which higher overtones should decay (0 to 1)
private float _bitCrush = 0.0f; // Bit crush: resamples the audio at a lower frequency (0 to 1)
private float _bitCrushSweep = 0.0f; // Bit crush sweep: sweeps the Bit Crush filter up or down (-1 to 1)
// ================================================================================================================
// ACCESSOR INTERFACE ---------------------------------------------------------------------------------------------
/** Shape of the wave (0:square, 1:sawtooth, 2:sin, 3:noise) */
public uint waveType {
get { return _waveType; }
set { _waveType = value > 8 ? 0 : value; paramsDirty = true; }
}
/** Overall volume of the sound (0 to 1) */
public float masterVolume {
get { return _masterVolume; }
set { _masterVolume = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Length of the volume envelope attack (0 to 1) */
public float attackTime {
get { return _attackTime; }
set { _attackTime = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Length of the volume envelope sustain (0 to 1) */
public float sustainTime {
get { return _sustainTime; }
set { _sustainTime = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Tilts the sustain envelope for more 'pop' (0 to 1) */
public float sustainPunch {
get { return _sustainPunch; }
set { _sustainPunch = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Length of the volume envelope decay (yes, I know it's called release) (0 to 1) */
public float decayTime {
get { return _decayTime; }
set { _decayTime = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Base note of the sound (0 to 1) */
public float startFrequency {
get { return _startFrequency; }
set { _startFrequency = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** If sliding, the sound will stop at this frequency, to prevent really low notes (0 to 1) */
public float minFrequency {
get { return _minFrequency; }
set { _minFrequency = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Slides the note up or down (-1 to 1) */
public float slide {
get { return _slide; }
set { _slide = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** Accelerates the slide (-1 to 1) */
public float deltaSlide {
get { return _deltaSlide; }
set { _deltaSlide = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** Strength of the vibrato effect (0 to 1) */
public float vibratoDepth {
get { return _vibratoDepth; }
set { _vibratoDepth = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Speed of the vibrato effect (i.e. frequency) (0 to 1) */
public float vibratoSpeed {
get { return _vibratoSpeed; }
set { _vibratoSpeed = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Shift in note, either up or down (-1 to 1) */
public float changeAmount {
get { return _changeAmount; }
set { _changeAmount = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** How fast the note shift happens (only happens once) (0 to 1) */
public float changeSpeed {
get { return _changeSpeed; }
set { _changeSpeed = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Controls the ratio between the up and down states of the square wave, changing the tibre (0 to 1) */
public float squareDuty {
get { return _squareDuty; }
set { _squareDuty = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Sweeps the duty up or down (-1 to 1) */
public float dutySweep {
get { return _dutySweep; }
set { _dutySweep = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** Speed of the note repeating - certain variables are reset each time (0 to 1) */
public float repeatSpeed {
get { return _repeatSpeed; }
set { _repeatSpeed = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Offsets a second copy of the wave by a small phase, changing the tibre (-1 to 1) */
public float phaserOffset {
get { return _phaserOffset; }
set { _phaserOffset = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** Sweeps the phase up or down (-1 to 1) */
public float phaserSweep {
get { return _phaserSweep; }
set { _phaserSweep = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** Frequency at which the low-pass filter starts attenuating higher frequencies (0 to 1) */
public float lpFilterCutoff {
get { return _lpFilterCutoff; }
set { _lpFilterCutoff = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Sweeps the low-pass cutoff up or down (-1 to 1) */
public float lpFilterCutoffSweep {
get { return _lpFilterCutoffSweep; }
set { _lpFilterCutoffSweep = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** Changes the attenuation rate for the low-pass filter, changing the timbre (0 to 1) */
public float lpFilterResonance {
get { return _lpFilterResonance; }
set { _lpFilterResonance = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Frequency at which the high-pass filter starts attenuating lower frequencies (0 to 1) */
public float hpFilterCutoff {
get { return _hpFilterCutoff; }
set { _hpFilterCutoff = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Sweeps the high-pass cutoff up or down (-1 to 1) */
public float hpFilterCutoffSweep {
get { return _hpFilterCutoffSweep; }
set { _hpFilterCutoffSweep = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
// From BFXR
/** Pitch Jump Repeat Speed: larger Values means more pitch jumps, which can be useful for arpeggiation (0 to 1) */
public float changeRepeat {
get { return _changeRepeat; }
set { _changeRepeat = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Shift in note, either up or down (-1 to 1) */
public float changeAmount2 {
get { return _changeAmount2; }
set { _changeAmount2 = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
/** How fast the note shift happens (only happens once) (0 to 1) */
public float changeSpeed2 {
get { return _changeSpeed2; }
set { _changeSpeed2 = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Pushes amplitudes together into a narrower range to make them stand out more. Very good for sound effects, where you want them to stick out against background music (0 to 1) */
public float compressionAmount {
get { return _compressionAmount; }
set { _compressionAmount = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Harmonics: overlays copies of the waveform with copies and multiples of its frequency. Good for bulking out or otherwise enriching the texture of the sounds (warning: this is the number 1 cause of bfxr slowdown!) (0 to 1) */
public float overtones {
get { return _overtones; }
set { _overtones = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Harmonics falloff: The rate at which higher overtones should decay (0 to 1) */
public float overtoneFalloff {
get { return _overtoneFalloff; }
set { _overtoneFalloff = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Bit crush: resamples the audio at a lower frequency (0 to 1) */
public float bitCrush {
get { return _bitCrush; }
set { _bitCrush = Mathf.Clamp(value, 0, 1); paramsDirty = true; }
}
/** Bit crush sweep: sweeps the Bit Crush filter up or down (-1 to 1) */
public float bitCrushSweep {
get { return _bitCrushSweep; }
set { _bitCrushSweep = Mathf.Clamp(value, -1, 1); paramsDirty = true; }
}
// ================================================================================================================
// PUBLIC INTERFACE -----------------------------------------------------------------------------------------------
// Generator methods
/**
* Sets the parameters to generate a pickup/coin sound
*/
public void GeneratePickupCoin() {
resetParams();
_startFrequency = 0.4f + GetRandom() * 0.5f;
_sustainTime = GetRandom() * 0.1f;
_decayTime = 0.1f + GetRandom() * 0.4f;
_sustainPunch = 0.3f + GetRandom() * 0.3f;
if (GetRandomBool()) {
_changeSpeed = 0.5f + GetRandom() * 0.2f;
int cnum = (int)(GetRandom()*7f) + 1;
int cden = cnum + (int)(GetRandom()*7f) + 2;
_changeAmount = (float)cnum / (float)cden;
}
}
/**
* Sets the parameters to generate a laser/shoot sound
*/
public void GenerateLaserShoot() {
resetParams();
_waveType = (uint)(GetRandom() * 3);
if (_waveType == 2 && GetRandomBool()) _waveType = (uint)(GetRandom() * 2f);
_startFrequency = 0.5f + GetRandom() * 0.5f;
_minFrequency = _startFrequency - 0.2f - GetRandom() * 0.6f;
if (_minFrequency < 0.2f) _minFrequency = 0.2f;
_slide = -0.15f - GetRandom() * 0.2f;
if (GetRandom() < 0.33f) {
_startFrequency = 0.3f + GetRandom() * 0.6f;
_minFrequency = GetRandom() * 0.1f;
_slide = -0.35f - GetRandom() * 0.3f;
}
if (GetRandomBool()) {
_squareDuty = GetRandom() * 0.5f;
_dutySweep = GetRandom() * 0.2f;
} else {
_squareDuty = 0.4f + GetRandom() * 0.5f;
_dutySweep = -GetRandom() * 0.7f;
}
_sustainTime = 0.1f + GetRandom() * 0.2f;
_decayTime = GetRandom() * 0.4f;
if (GetRandomBool()) _sustainPunch = GetRandom() * 0.3f;
if (GetRandom() < 0.33f) {
_phaserOffset = GetRandom() * 0.2f;
_phaserSweep = -GetRandom() * 0.2f;
}
if (GetRandomBool()) _hpFilterCutoff = GetRandom() * 0.3f;
}
/**
* Sets the parameters to generate an explosion sound
*/
public void GenerateExplosion() {
resetParams();
_waveType = 3;
if (GetRandomBool()) {
_startFrequency = 0.1f + GetRandom() * 0.4f;
_slide = -0.1f + GetRandom() * 0.4f;
} else {
_startFrequency = 0.2f + GetRandom() * 0.7f;
_slide = -0.2f - GetRandom() * 0.2f;
}
_startFrequency *= _startFrequency;
if (GetRandom() < 0.2f) _slide = 0.0f;
if (GetRandom() < 0.33f) _repeatSpeed = 0.3f + GetRandom() * 0.5f;
_sustainTime = 0.1f + GetRandom() * 0.3f;
_decayTime = GetRandom() * 0.5f;
_sustainPunch = 0.2f + GetRandom() * 0.6f;
if (GetRandomBool()) {
_phaserOffset = -0.3f + GetRandom() * 0.9f;
_phaserSweep = -GetRandom() * 0.3f;
}
if (GetRandom() < 0.33f) {
_changeSpeed = 0.6f + GetRandom() * 0.3f;
_changeAmount = 0.8f - GetRandom() * 1.6f;
}
}
/**
* Sets the parameters to generate a powerup sound
*/
public void GeneratePowerup() {
resetParams();
if (GetRandomBool()) {
_waveType = 1;
} else {
_squareDuty = GetRandom() * 0.6f;
}
if (GetRandomBool()) {
_startFrequency = 0.2f + GetRandom() * 0.3f;
_slide = 0.1f + GetRandom() * 0.4f;
_repeatSpeed = 0.4f + GetRandom() * 0.4f;
} else {
_startFrequency = 0.2f + GetRandom() * 0.3f;
_slide = 0.05f + GetRandom() * 0.2f;
if (GetRandomBool()) {
_vibratoDepth = GetRandom() * 0.7f;
_vibratoSpeed = GetRandom() * 0.6f;
}
}
_sustainTime = GetRandom() * 0.4f;
_decayTime = 0.1f + GetRandom() * 0.4f;
}
/**
* Sets the parameters to generate a hit/hurt sound
*/
public void GenerateHitHurt() {
resetParams();
_waveType = (uint)(GetRandom() * 3f);
if (_waveType == 2) {
_waveType = 3;
} else if (_waveType == 0) {
_squareDuty = GetRandom() * 0.6f;
}
_startFrequency = 0.2f + GetRandom() * 0.6f;
_slide = -0.3f - GetRandom() * 0.4f;
_sustainTime = GetRandom() * 0.1f;
_decayTime = 0.1f + GetRandom() * 0.2f;
if (GetRandomBool()) _hpFilterCutoff = GetRandom() * 0.3f;
}
/**
* Sets the parameters to generate a jump sound
*/
public void GenerateJump() {
resetParams();
_waveType = 0;
_squareDuty = GetRandom() * 0.6f;
_startFrequency = 0.3f + GetRandom() * 0.3f;
_slide = 0.1f + GetRandom() * 0.2f;
_sustainTime = 0.1f + GetRandom() * 0.3f;
_decayTime = 0.1f + GetRandom() * 0.2f;
if (GetRandomBool()) _hpFilterCutoff = GetRandom() * 0.3f;
if (GetRandomBool()) _lpFilterCutoff = 1.0f - GetRandom() * 0.6f;
}
/**
* Sets the parameters to generate a blip/select sound
*/
public void GenerateBlipSelect() {
resetParams();
_waveType = (uint)(GetRandom() * 2f);
if (_waveType == 0) _squareDuty = GetRandom() * 0.6f;
_startFrequency = 0.2f + GetRandom() * 0.4f;
_sustainTime = 0.1f + GetRandom() * 0.1f;
_decayTime = GetRandom() * 0.2f;
_hpFilterCutoff = 0.1f;
}
/**
* Resets the parameters, used at the start of each generate function
*/
protected void resetParams() {
paramsDirty = true;
_waveType = 0;
_startFrequency = 0.3f;
_minFrequency = 0.0f;
_slide = 0.0f;
_deltaSlide = 0.0f;
_squareDuty = 0.0f;
_dutySweep = 0.0f;
_vibratoDepth = 0.0f;
_vibratoSpeed = 0.0f;
_attackTime = 0.0f;
_sustainTime = 0.3f;
_decayTime = 0.4f;
_sustainPunch = 0.0f;
_lpFilterResonance = 0.0f;
_lpFilterCutoff = 1.0f;
_lpFilterCutoffSweep = 0.0f;
_hpFilterCutoff = 0.0f;
_hpFilterCutoffSweep = 0.0f;
_phaserOffset = 0.0f;
_phaserSweep = 0.0f;
_repeatSpeed = 0.0f;
_changeSpeed = 0.0f;
_changeAmount = 0.0f;
// From BFXR
_changeRepeat = 0.0f;
_changeAmount2 = 0.0f;
_changeSpeed2 = 0.0f;
_compressionAmount = 0.3f;
_overtones = 0.0f;
_overtoneFalloff = 0.0f;
_bitCrush = 0.0f;
_bitCrushSweep = 0.0f;
}
// Randomization methods
/**
* Randomly adjusts the parameters ever so slightly
*/
public void Mutate(float __mutation = 0.05f) {
if (GetRandomBool()) startFrequency += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) minFrequency += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) slide += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) deltaSlide += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) squareDuty += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) dutySweep += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) vibratoDepth += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) vibratoSpeed += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) attackTime += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) sustainTime += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) decayTime += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) sustainPunch += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) lpFilterCutoff += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) lpFilterCutoffSweep += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) lpFilterResonance += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) hpFilterCutoff += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) hpFilterCutoffSweep += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) phaserOffset += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) phaserSweep += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) repeatSpeed += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) changeSpeed += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) changeAmount += GetRandom() * __mutation * 2f - __mutation;
// From BFXR
if (GetRandomBool()) changeRepeat += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) changeAmount2 += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) changeSpeed2 += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) compressionAmount += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) overtones += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) overtoneFalloff += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) bitCrush += GetRandom() * __mutation * 2f - __mutation;
if (GetRandomBool()) bitCrushSweep += GetRandom() * __mutation * 2f - __mutation;
}
/**
* Sets all parameters to random values
*/
public void Randomize() {
resetParams();
_waveType = (uint)(GetRandom() * 9f);
_attackTime = Pow(GetRandom() * 2f - 1f, 4);
_sustainTime = Pow(GetRandom() * 2f - 1f, 2);
_sustainPunch = Pow(GetRandom() * 0.8f, 2);
_decayTime = GetRandom();
_startFrequency = (GetRandomBool()) ? Pow(GetRandom() * 2f - 1f, 2) : (Pow(GetRandom() * 0.5f, 3) + 0.5f);
_minFrequency = 0.0f;
_slide = Pow(GetRandom() * 2f - 1f, 3);
_deltaSlide = Pow(GetRandom() * 2f - 1f, 3);
_vibratoDepth = Pow(GetRandom() * 2f - 1f, 3);
_vibratoSpeed = GetRandom() * 2f - 1f;
_changeAmount = GetRandom() * 2f - 1f;
_changeSpeed = GetRandom() * 2f - 1f;
_squareDuty = GetRandom() * 2f - 1f;
_dutySweep = Pow(GetRandom() * 2f - 1f, 3);
_repeatSpeed = GetRandom() * 2f - 1f;
_phaserOffset = Pow(GetRandom() * 2f - 1f, 3);
_phaserSweep = Pow(GetRandom() * 2f - 1f, 3);
_lpFilterCutoff = 1f - Pow(GetRandom(), 3);
_lpFilterCutoffSweep = Pow(GetRandom() * 2f - 1f, 3);
_lpFilterResonance = GetRandom() * 2f - 1f;
_hpFilterCutoff = Pow(GetRandom(), 5);
_hpFilterCutoffSweep = Pow(GetRandom() * 2f - 1f, 5);
if (_attackTime + _sustainTime + _decayTime < 0.2f) {
_sustainTime = 0.2f + GetRandom() * 0.3f;
_decayTime = 0.2f + GetRandom() * 0.3f;
}
if ((_startFrequency > 0.7f && _slide > 0.2) || (_startFrequency < 0.2 && _slide < -0.05)) {
_slide = -_slide;
}
if (_lpFilterCutoff < 0.1f && _lpFilterCutoffSweep < -0.05f) {
_lpFilterCutoffSweep = -_lpFilterCutoffSweep;
}
// From BFXR
_changeRepeat = GetRandom();
_changeAmount2 = GetRandom() * 2f - 1f;
_changeSpeed2 = GetRandom();
_compressionAmount = GetRandom();
_overtones = GetRandom();
_overtoneFalloff = GetRandom();
_bitCrush = GetRandom();
_bitCrushSweep = GetRandom() * 2f - 1f;
}
// Setting string methods
/**
* Returns a string representation of the parameters for copy/paste sharing in the old format (24 parameters, SFXR/AS3SFXR compatible)
* @return A comma-delimited list of parameter values
*/
public string GetSettingsStringLegacy() {
string str = "";
// 24 params
str += waveType.ToString() + ",";
str += To4DP(_attackTime) + ",";
str += To4DP(_sustainTime) + ",";
str += To4DP(_sustainPunch) + ",";
str += To4DP(_decayTime) + ",";
str += To4DP(_startFrequency) + ",";
str += To4DP(_minFrequency) + ",";
str += To4DP(_slide) + ",";
str += To4DP(_deltaSlide) + ",";
str += To4DP(_vibratoDepth) + ",";
str += To4DP(_vibratoSpeed) + ",";
str += To4DP(_changeAmount) + ",";
str += To4DP(_changeSpeed) + ",";
str += To4DP(_squareDuty) + ",";
str += To4DP(_dutySweep) + ",";
str += To4DP(_repeatSpeed) + ",";
str += To4DP(_phaserOffset) + ",";
str += To4DP(_phaserSweep) + ",";
str += To4DP(_lpFilterCutoff) + ",";
str += To4DP(_lpFilterCutoffSweep) + ",";
str += To4DP(_lpFilterResonance) + ",";
str += To4DP(_hpFilterCutoff) + ",";
str += To4DP(_hpFilterCutoffSweep) + ",";
str += To4DP(_masterVolume);
return str;
}
/**
* Returns a string representation of the parameters for copy/paste sharing in the new format (32 parameters, BFXR compatible)
* @return A comma-delimited list of parameter values
*/
public string GetSettingsString() {
string str = "";
// 32 params
str += waveType.ToString() + ",";
str += To4DP(_masterVolume) + ",";
str += To4DP(_attackTime) + ",";
str += To4DP(_sustainTime) + ",";
str += To4DP(_sustainPunch) + ",";
str += To4DP(_decayTime) + ",";
str += To4DP(_compressionAmount) + ",";
str += To4DP(_startFrequency) + ",";
str += To4DP(_minFrequency) + ",";
str += To4DP(_slide) + ",";
str += To4DP(_deltaSlide) + ",";
str += To4DP(_vibratoDepth) + ",";
str += To4DP(_vibratoSpeed) + ",";
str += To4DP(_overtones) + ",";
str += To4DP(_overtoneFalloff) + ",";
str += To4DP(_changeRepeat) + ","; // _changeRepeat?
str += To4DP(_changeAmount) + ",";
str += To4DP(_changeSpeed) + ",";
str += To4DP(_changeAmount2) + ","; // changeamount2
str += To4DP(_changeSpeed2) + ","; // changespeed2
str += To4DP(_squareDuty) + ",";
str += To4DP(_dutySweep) + ",";
str += To4DP(_repeatSpeed) + ",";
str += To4DP(_phaserOffset) + ",";
str += To4DP(_phaserSweep) + ",";
str += To4DP(_lpFilterCutoff) + ",";
str += To4DP(_lpFilterCutoffSweep) + ",";
str += To4DP(_lpFilterResonance) + ",";
str += To4DP(_hpFilterCutoff) + ",";
str += To4DP(_hpFilterCutoffSweep) + ",";
str += To4DP(_bitCrush) + ",";
str += To4DP(_bitCrushSweep);
return str;
}
/**
* Parses a settings string into the parameters
* @param string Settings string to parse
* @return If the string successfully parsed
*/
public bool SetSettingsString(string __string) {
string[] values = __string.Split(new char[] { ',' });
if (values.Length == 24) {
// Old format (SFXR): 24 parameters
resetParams();
waveType = ParseUint(values[0]);
attackTime = ParseFloat(values[1]);
sustainTime = ParseFloat(values[2]);
sustainPunch = ParseFloat(values[3]);
decayTime = ParseFloat(values[4]);
startFrequency = ParseFloat(values[5]);
minFrequency = ParseFloat(values[6]);
slide = ParseFloat(values[7]);
deltaSlide = ParseFloat(values[8]);
vibratoDepth = ParseFloat(values[9]);
vibratoSpeed = ParseFloat(values[10]);
changeAmount = ParseFloat(values[11]);
changeSpeed = ParseFloat(values[12]);
squareDuty = ParseFloat(values[13]);
dutySweep = ParseFloat(values[14]);
repeatSpeed = ParseFloat(values[15]);
phaserOffset = ParseFloat(values[16]);
phaserSweep = ParseFloat(values[17]);
lpFilterCutoff = ParseFloat(values[18]);
lpFilterCutoffSweep = ParseFloat(values[19]);
lpFilterResonance = ParseFloat(values[20]);
hpFilterCutoff = ParseFloat(values[21]);
hpFilterCutoffSweep = ParseFloat(values[22]);
masterVolume = ParseFloat(values[23]);
} else if (values.Length >= 32) {
// New format (BFXR): 32 parameters (or more, but locked parameters are ignored)
resetParams();
waveType = ParseUint(values[0]);
masterVolume = ParseFloat(values[1]);
attackTime = ParseFloat(values[2]);
sustainTime = ParseFloat(values[3]);
sustainPunch = ParseFloat(values[4]);
decayTime = ParseFloat(values[5]);
compressionAmount = ParseFloat(values[6]);
startFrequency = ParseFloat(values[7]);
minFrequency = ParseFloat(values[8]);
slide = ParseFloat(values[9]);
deltaSlide = ParseFloat(values[10]);
vibratoDepth = ParseFloat(values[11]);
vibratoSpeed = ParseFloat(values[12]);
overtones = ParseFloat(values[13]);
overtoneFalloff = ParseFloat(values[14]);
changeRepeat = ParseFloat(values[15]);
changeAmount = ParseFloat(values[16]);
changeSpeed = ParseFloat(values[17]);
changeAmount2 = ParseFloat(values[18]);
changeSpeed2 = ParseFloat(values[19]);
squareDuty = ParseFloat(values[20]);
dutySweep = ParseFloat(values[21]);
repeatSpeed = ParseFloat(values[22]);
phaserOffset = ParseFloat(values[23]);
phaserSweep = ParseFloat(values[24]);
lpFilterCutoff = ParseFloat(values[25]);
lpFilterCutoffSweep = ParseFloat(values[26]);
lpFilterResonance = ParseFloat(values[27]);
hpFilterCutoff = ParseFloat(values[28]);
hpFilterCutoffSweep = ParseFloat(values[29]);
bitCrush = ParseFloat(values[30]);
bitCrushSweep = ParseFloat(values[31]);
} else {
Debug.LogError("Could not paste settings string: parameters contain " + values.Length + " values (was expecting 24 or >32)");
return false;
}
return true;
}
// Copying methods
/**
* Returns a copy of this SfxrParams with all settings duplicated
* @return A copy of this SfxrParams
*/
public SfxrParams Clone() {
SfxrParams outp = new SfxrParams();
outp.CopyFrom(this);
return outp;
}
/**
* Copies parameters from another instance
* @param params Instance to copy parameters from
*/
public void CopyFrom(SfxrParams __params, bool __makeDirty = false) {
bool wasDirty = paramsDirty;
SetSettingsString(GetSettingsString());
paramsDirty = wasDirty || __makeDirty;
}
// Utility methods
/**
* Faster power function; this function takes about 36% of the time Mathf.Pow() would take in our use cases
* @param base Base to raise to power
* @param power Power to raise base by
* @return The calculated power
*/
private float Pow(float __pbase, int __power) {
switch(__power) {
case 2: return __pbase * __pbase;
case 3: return __pbase * __pbase * __pbase;
case 4: return __pbase * __pbase * __pbase * __pbase;
case 5: return __pbase * __pbase * __pbase * __pbase * __pbase;
}
return 1f;
}
// ================================================================================================================
// INTERNAL INTERFACE ---------------------------------------------------------------------------------------------
/**
* Returns the number as a string to 4 decimal places
* @param value Number to convert
* @return Number to 4dp as a string
*/
private string To4DP(float __value) {
if (__value < 0.0001f && __value > -0.0001f) return "";
return __value.ToString("#.####");
}
/**
* Parses a string into an uint value; also returns 0 if the string is empty, rather than an error
*/
private uint ParseUint(string __value) {
if (__value.Length == 0) return 0;
return uint.Parse(__value);
}
/**
* Parses a string into a float value; also returns 0 if the string is empty, rather than an error
*/
private float ParseFloat(string __value) {
if (__value.Length == 0) return 0;
return float.Parse(__value);
}
/**
* Returns a random value: 0 <= n < 1
* This function is needed so we can follow the original code more strictly; Unity's Random.value returns 0 <= n <= 1
*/
private float GetRandom() {
return UnityEngine.Random.value % 1;
}
/**
* Returns a boolean value
*/
private bool GetRandomBool() {
return UnityEngine.Random.value > 0.5f;
}
}
| |
// #1626
using Bridge.Test.NUnit;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Bridge.ClientTest.Collections.Generic
{
[Category(Constants.MODULE_ICOLLECTION)]
[TestFixture(TestNameFormat = "IReadOnlyDictionary - {0}")]
public class IReadOnlyDictionaryTests
{
private class MyReadOnlyDictionary : IReadOnlyDictionary<int, string>
{
private Dictionary<int, string> _backingDictionary;
public MyReadOnlyDictionary()
: this(new Dictionary<int, string>())
{
}
public MyReadOnlyDictionary(IDictionary<int, string> initialValues)
{
_backingDictionary = new Dictionary<int, string>(initialValues);
}
public string this[int key]
{
get
{
return _backingDictionary[key];
}
}
public IEnumerable<int> Keys
{
get
{
return _backingDictionary.Keys;
}
}
public IEnumerable<string> Values
{
get
{
return _backingDictionary.Values;
}
}
public bool ContainsKey(int key)
{
return _backingDictionary.ContainsKey(key);
}
public bool TryGetValue(int key, out string value)
{
return _backingDictionary.TryGetValue(key, out value);
}
public int Count
{
get
{
return _backingDictionary.Count;
}
}
public IEnumerator<KeyValuePair<int, string>> GetEnumerator()
{
return _backingDictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _backingDictionary.GetEnumerator();
}
}
[Test]
public void TypePropertiesAreCorrect()
{
Assert.AreEqual("System.Collections.Generic.IReadOnlyDictionary`2[[System.Object, mscorlib],[System.Object, mscorlib]]", typeof(IReadOnlyDictionary<object, object>).FullName, "FullName should be correct");
Assert.True(typeof(IReadOnlyDictionary<object, object>).IsInterface, "IsInterface should be true");
var interfaces = typeof(IReadOnlyDictionary<int, string>).GetInterfaces();
Assert.AreEqual(3, interfaces.Length, "Interfaces length");
Assert.AreEqual(typeof(IReadOnlyCollection<KeyValuePair<int, string>>).FullName, interfaces[0].FullName, "Interfaces IReadOnlyCollection<KeyValuePair<int, string>>");
Assert.AreEqual(typeof(IEnumerable<KeyValuePair<int, string>>).FullName, interfaces[1].FullName, "Interfaces IEnumerable<KeyValuePair<int, string>>");
Assert.AreEqual(typeof(IEnumerable).FullName, interfaces[2].FullName, "Interfaces IEnumerable");
}
[Test]
public void ClassImplementsInterfaces()
{
Assert.True((object)new MyReadOnlyDictionary() is IReadOnlyDictionary<int, string>);
}
[Test]
public void CountWorks()
{
var d = new MyReadOnlyDictionary();
Assert.AreEqual(0, d.Count);
var d2 = new MyReadOnlyDictionary(new Dictionary<int, string> { { 3, "c" } });
Assert.AreEqual(1, d2.Count);
}
[Test]
public void KeysWorks()
{
var d = new MyReadOnlyDictionary(new Dictionary<int, string> { { 3, "b" }, { 6, "z" }, { 9, "x" } });
var actualKeys = new int[] { 3, 6, 9 };
var keys = d.Keys;
Assert.True(keys is IEnumerable<int>);
int i = 0;
foreach (var key in keys)
{
Assert.AreEqual(actualKeys[i], key);
i++;
}
Assert.AreEqual(actualKeys.Length, i);
keys = ((IReadOnlyDictionary<int, string>)d).Keys;
Assert.True(keys is IEnumerable<int>);
i = 0;
foreach (var key in keys)
{
Assert.AreEqual(actualKeys[i], key);
i++;
}
Assert.AreEqual(actualKeys.Length, i);
}
[Test]
public void GetItemWorks()
{
var d = new MyReadOnlyDictionary(new Dictionary<int, string> { { 3, "b" }, { 6, "z" }, { 9, "x" } });
var di = (IReadOnlyDictionary<int, string>)d;
Assert.AreEqual("b", d[3]);
Assert.AreEqual("z", di[6]);
try
{
var x = d[1];
Assert.Fail("Should throw");
}
catch (Exception)
{
}
try
{
var x = di[1];
Assert.Fail("Should throw");
}
catch (Exception)
{
}
}
[Test]
public void ValuesWorks()
{
var d = new MyReadOnlyDictionary(new Dictionary<int, string> { { 3, "b" }, { 6, "z" }, { 9, "x" } });
var actualValues = new string[] { "b", "z", "x" };
var values = d.Values;
int i = 0;
Assert.True(values is IEnumerable<string>);
foreach (var val in values)
{
Assert.AreEqual(actualValues[i], val);
i++;
}
Assert.AreEqual(actualValues.Length, i);
values = ((IReadOnlyDictionary<int, string>)d).Values;
Assert.True(values is IEnumerable<string>);
i = 0;
foreach (var val in values)
{
Assert.AreEqual(actualValues[i], val);
i++;
}
Assert.AreEqual(actualValues.Length, i);
}
[Test]
public void ContainsKeyWorks()
{
var d = new MyReadOnlyDictionary(new Dictionary<int, string> { { 3, "b" }, { 6, "z" }, { 9, "x" } });
var di = (IReadOnlyDictionary<int, string>)d;
Assert.True(d.ContainsKey(6));
Assert.True(di.ContainsKey(3));
Assert.False(d.ContainsKey(6123));
Assert.False(di.ContainsKey(32));
}
[Test]
public void TryGetValueWorks()
{
var d = new MyReadOnlyDictionary(new Dictionary<int, string> { { 3, "b" }, { 6, "z" }, { 9, "x" } });
var di = (IReadOnlyDictionary<int, string>)d;
string outVal;
Assert.True(d.TryGetValue(6, out outVal));
Assert.AreEqual("z", outVal);
Assert.True(di.TryGetValue(3, out outVal));
Assert.AreEqual("b", outVal);
outVal = "!!!";
Assert.False(d.TryGetValue(6123, out outVal));
Assert.AreEqual(null, outVal);
outVal = "!!!";
Assert.False(di.TryGetValue(32, out outVal));
Assert.AreEqual(null, outVal);
}
public class Person
{
public string Name
{
get; set;
}
public int Age
{
get; set;
}
public IReadOnlyDictionary<string, object> ToDict()
{
return new Dictionary<string, object>
{
{nameof(Name), Name},
{nameof(Age), Age}
};
}
}
[Test]
public void UsersTestCase_1626_Works()
{
var p = new Person() { Name = "Donald", Age = 27 };
var d = p.ToDict();
Assert.AreEqual("Donald", d["Name"]);
Assert.AreEqual(27, d["Age"]);
}
}
}
| |
using J2N.Text;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using WritableArrayAttribute = YAF.Lucene.Net.Support.WritableArrayAttribute;
namespace YAF.Lucene.Net.Analysis.TokenAttributes
{
/*
* 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 Attribute = YAF.Lucene.Net.Util.Attribute;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using IAttribute = YAF.Lucene.Net.Util.IAttribute;
using IAttributeReflector = YAF.Lucene.Net.Util.IAttributeReflector;
using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator;
using UnicodeUtil = YAF.Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Default implementation of <see cref="ICharTermAttribute"/>. </summary>
public class CharTermAttribute : Attribute, ICharTermAttribute, ITermToBytesRefAttribute, IAppendable
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private static int MIN_BUFFER_SIZE = 10;
private char[] termBuffer = CreateBuffer(MIN_BUFFER_SIZE);
private int termLength = 0;
/// <summary>
/// Initialize this attribute with empty term text </summary>
public CharTermAttribute()
{
}
// LUCENENET specific - ICharSequence member from J2N
bool ICharSequence.HasValue => termBuffer != null;
public void CopyBuffer(char[] buffer, int offset, int length)
{
GrowTermBuffer(length);
Array.Copy(buffer, offset, termBuffer, 0, length);
termLength = length;
}
char[] ICharTermAttribute.Buffer => termBuffer;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public char[] Buffer => termBuffer;
public char[] ResizeBuffer(int newSize)
{
if (termBuffer.Length < newSize)
{
// Not big enough; create a new array with slight
// over allocation and preserve content
char[] newCharBuffer = new char[ArrayUtil.Oversize(newSize, RamUsageEstimator.NUM_BYTES_CHAR)];
Array.Copy(termBuffer, 0, newCharBuffer, 0, termBuffer.Length);
termBuffer = newCharBuffer;
}
return termBuffer;
}
private void GrowTermBuffer(int newSize)
{
if (termBuffer.Length < newSize)
{
// Not big enough; create a new array with slight
// over allocation:
termBuffer = new char[ArrayUtil.Oversize(newSize, RamUsageEstimator.NUM_BYTES_CHAR)];
}
}
int ICharTermAttribute.Length { get => Length; set => SetLength(value); }
int ICharSequence.Length => Length;
public int Length
{
get => termLength;
set => SetLength(value);
}
public CharTermAttribute SetLength(int length)
{
if (length > termBuffer.Length)
{
throw new ArgumentException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.Length + ")");
}
termLength = length;
return this;
}
public CharTermAttribute SetEmpty()
{
termLength = 0;
return this;
}
// *** TermToBytesRefAttribute interface ***
private BytesRef bytes = new BytesRef(MIN_BUFFER_SIZE);
public virtual void FillBytesRef()
{
UnicodeUtil.UTF16toUTF8(termBuffer, 0, termLength, bytes);
}
public virtual BytesRef BytesRef => bytes;
// *** CharSequence interface ***
// LUCENENET specific: Replaced with this[int] to .NETify
//public char CharAt(int index)
//{
// if (index >= TermLength)
// {
// throw new IndexOutOfRangeException();
// }
// return TermBuffer[index];
//}
char ICharSequence.this[int index] => this[index];
char ICharTermAttribute.this[int index] { get => this[index]; set => this[index] = value; }
// LUCENENET specific indexer to make CharTermAttribute act more like a .NET type
public char this[int index]
{
get
{
if (index < 0 || index >= termLength) // LUCENENET: Added better bounds checking
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return termBuffer[index];
}
set
{
if (index < 0 || index >= termLength)
{
throw new ArgumentOutOfRangeException(nameof(index)); // LUCENENET: Added better bounds checking
}
termBuffer[index] = value;
}
}
public ICharSequence Subsequence(int startIndex, int length)
{
// From Apache Harmony String class
if (termBuffer == null || (startIndex == 0 && length == termBuffer.Length))
{
return new CharArrayCharSequence(termBuffer);
}
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length));
if (startIndex + length > Length)
throw new ArgumentOutOfRangeException("", $"{nameof(startIndex)} + {nameof(length)} > {nameof(Length)}");
char[] result = new char[length];
for (int i = 0, j = startIndex; i < length; i++, j++)
result[i] = termBuffer[j];
return new CharArrayCharSequence(result);
}
// *** Appendable interface ***
public CharTermAttribute Append(string value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
value.CopyTo(startIndex, InternalResizeBuffer(termLength + charCount), termLength, charCount);
Length += charCount;
return this;
}
public CharTermAttribute Append(char value)
{
ResizeBuffer(termLength + 1)[termLength++] = value;
return this;
}
public CharTermAttribute Append(char[] value)
{
if (value == null)
//return AppendNull();
return this; // No-op
int len = value.Length;
value.CopyTo(InternalResizeBuffer(termLength + len), termLength);
Length += len;
return this;
}
public CharTermAttribute Append(char[] value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
Array.Copy(value, startIndex, InternalResizeBuffer(termLength + charCount), termLength, charCount);
Length += charCount;
return this;
}
public CharTermAttribute Append(string value)
{
return Append(value, 0, value == null ? 0 : value.Length);
}
public CharTermAttribute Append(StringBuilder value)
{
if (value == null) // needed for Appendable compliance
{
//return AppendNull();
return this; // No-op
}
return Append(value.ToString());
}
public CharTermAttribute Append(StringBuilder value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
return Append(value.ToString(startIndex, charCount));
}
public CharTermAttribute Append(ICharTermAttribute value)
{
if (value == null) // needed for Appendable compliance
{
//return AppendNull();
return this; // No-op
}
int len = value.Length;
Array.Copy(value.Buffer, 0, ResizeBuffer(termLength + len), termLength, len);
termLength += len;
return this;
}
public CharTermAttribute Append(ICharSequence value)
{
if (value == null)
//return AppendNull();
return this; // No-op
return Append(value, 0, value.Length);
}
public CharTermAttribute Append(ICharSequence value, int startIndex, int charCount)
{
// LUCENENET: Changed semantics to be the same as the StringBuilder in .NET
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex));
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount));
if (value == null)
{
if (startIndex == 0 && charCount == 0)
return this;
throw new ArgumentNullException(nameof(value));
}
if (charCount == 0)
return this;
if (startIndex > value.Length - charCount)
throw new ArgumentOutOfRangeException(nameof(startIndex));
ResizeBuffer(termLength + charCount);
for (int i = 0; i < charCount; i++)
termBuffer[termLength++] = value[startIndex + i];
return this;
}
private char[] InternalResizeBuffer(int length)
{
if (termBuffer.Length < length)
{
char[] newBuffer = CreateBuffer(length);
Array.Copy(termBuffer, 0, newBuffer, 0, termBuffer.Length);
this.termBuffer = newBuffer;
}
return termBuffer;
}
private static char[] CreateBuffer(int length)
{
return new char[ArrayUtil.Oversize(length, RamUsageEstimator.NUM_BYTES_CHAR)];
}
// LUCENENET: Not used - we are doing a no-op when the value is null
//private CharTermAttribute AppendNull()
//{
// ResizeBuffer(termLength + 4);
// termBuffer[termLength++] = 'n';
// termBuffer[termLength++] = 'u';
// termBuffer[termLength++] = 'l';
// termBuffer[termLength++] = 'l';
// return this;
//}
// *** Attribute ***
public override int GetHashCode()
{
int code = termLength;
code = code * 31 + ArrayUtil.GetHashCode(termBuffer, 0, termLength);
return code;
}
public override void Clear()
{
termLength = 0;
}
public override object Clone()
{
CharTermAttribute t = (CharTermAttribute)base.Clone();
// Do a deep clone
t.termBuffer = new char[this.termLength];
Array.Copy(this.termBuffer, 0, t.termBuffer, 0, this.termLength);
t.bytes = BytesRef.DeepCopyOf(bytes);
return t;
}
public override bool Equals(object other)
{
if (other == this)
{
return true;
}
if (other is CharTermAttribute o)
{
if (termLength != o.termLength)
{
return false;
}
for (int i = 0; i < termLength; i++)
{
if (termBuffer[i] != o.termBuffer[i])
{
return false;
}
}
return true;
}
return false;
}
/// <summary>
/// Returns solely the term text as specified by the
/// <see cref="ICharSequence"/> interface.
/// <para/>
/// this method changed the behavior with Lucene 3.1,
/// before it returned a String representation of the whole
/// term with all attributes.
/// this affects especially the
/// <see cref="Lucene.Net.Analysis.Token"/> subclass.
/// </summary>
public override string ToString()
{
return new string(termBuffer, 0, termLength);
}
public override void ReflectWith(IAttributeReflector reflector)
{
reflector.Reflect(typeof(ICharTermAttribute), "term", ToString());
FillBytesRef();
reflector.Reflect(typeof(ITermToBytesRefAttribute), "bytes", BytesRef.DeepCopyOf(bytes));
}
public override void CopyTo(IAttribute target)
{
CharTermAttribute t = (CharTermAttribute)target;
t.CopyBuffer(termBuffer, 0, termLength);
}
#region ICharTermAttribute Members
void ICharTermAttribute.CopyBuffer(char[] buffer, int offset, int length) => CopyBuffer(buffer, offset, length);
char[] ICharTermAttribute.ResizeBuffer(int newSize) => ResizeBuffer(newSize);
ICharTermAttribute ICharTermAttribute.SetLength(int length) => SetLength(length);
ICharTermAttribute ICharTermAttribute.SetEmpty() => SetEmpty();
ICharTermAttribute ICharTermAttribute.Append(ICharSequence value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(ICharSequence value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(char value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(char[] value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(char[] value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(string value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(string value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(StringBuilder value) => Append(value);
ICharTermAttribute ICharTermAttribute.Append(StringBuilder value, int startIndex, int count) => Append(value, startIndex, count);
ICharTermAttribute ICharTermAttribute.Append(ICharTermAttribute value) => Append(value);
#endregion
#region IAppendable Members
IAppendable IAppendable.Append(char value) => Append(value);
IAppendable IAppendable.Append(string value) => Append(value);
IAppendable IAppendable.Append(string value, int startIndex, int count) => Append(value, startIndex, count);
IAppendable IAppendable.Append(StringBuilder value) => Append(value);
IAppendable IAppendable.Append(StringBuilder value, int startIndex, int count) => Append(value, startIndex, count);
IAppendable IAppendable.Append(char[] value) => Append(value);
IAppendable IAppendable.Append(char[] value, int startIndex, int count) => Append(value, startIndex, count);
IAppendable IAppendable.Append(ICharSequence value) => Append(value);
IAppendable IAppendable.Append(ICharSequence value, int startIndex, int count) => Append(value, startIndex, count);
#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.
namespace System.Security {
using System.Security.Cryptography;
using System.Runtime.InteropServices;
#if FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ExceptionServices;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Text;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
public sealed class SecureString: IDisposable {
[System.Security.SecurityCritical] // auto-generated
private SafeBSTRHandle m_buffer;
[ContractPublicPropertyName("Length")]
private int m_length;
private bool m_readOnly;
private bool m_encrypted;
static bool supportedOnCurrentPlatform = EncryptionSupported();
const int BlockSize = (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE /2; // a char is two bytes
const int MaxLength = 65536;
const uint ProtectionScope = Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS;
[System.Security.SecuritySafeCritical] // auto-generated
static SecureString()
{
}
[System.Security.SecurityCritical] // auto-generated
unsafe static bool EncryptionSupported() {
// check if the enrypt/decrypt function is supported on current OS
bool supported = true;
try {
Win32Native.SystemFunction041(
SafeBSTRHandle.Allocate(null , (int)Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE),
Win32Native.CRYPTPROTECTMEMORY_BLOCK_SIZE,
Win32Native.CRYPTPROTECTMEMORY_SAME_PROCESS);
}
catch (EntryPointNotFoundException) {
supported = false;
}
return supported;
}
[System.Security.SecurityCritical] // auto-generated
internal SecureString(SecureString str) {
AllocateBuffer(str.BufferLength);
SafeBSTRHandle.Copy(str.m_buffer, this.m_buffer);
m_length = str.m_length;
m_encrypted = str.m_encrypted;
}
[System.Security.SecuritySafeCritical] // auto-generated
public SecureString() {
CheckSupportedOnCurrentPlatform();
// allocate the minimum block size for calling protectMemory
AllocateBuffer(BlockSize);
m_length = 0;
}
[System.Security.SecurityCritical] // auto-generated
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
private unsafe void InitializeSecureString(char* value, int length)
{
CheckSupportedOnCurrentPlatform();
AllocateBuffer(length);
m_length = length;
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy(bufferPtr, (byte*)value, length * 2);
}
catch (Exception) {
ProtectMemory();
throw;
}
finally
{
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
ProtectMemory();
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe SecureString(char* value, int length) {
if( value == null) {
throw new ArgumentNullException("value");
}
if( length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if( length > MaxLength) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_Length"));
}
Contract.EndContractBlock();
// Refactored since HandleProcessCorruptedStateExceptionsAttribute applies to methods only (yet).
InitializeSecureString(value, length);
}
public int Length {
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
get {
EnsureNotDisposed();
return m_length;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void AppendChar(char c) {
EnsureNotDisposed();
EnsureNotReadOnly();
EnsureCapacity(m_length + 1);
RuntimeHelpers.PrepareConstrainedRegions();
try {
UnProtectMemory();
m_buffer.Write<char>((uint)m_length * sizeof(char), c);
m_length++;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
}
}
// clears the current contents. Only available if writable
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void Clear() {
EnsureNotDisposed();
EnsureNotReadOnly();
m_length = 0;
m_buffer.ClearBuffer();
m_encrypted = false;
}
// Do a deep-copy of the SecureString
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public SecureString Copy() {
EnsureNotDisposed();
return new SecureString(this);
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void Dispose() {
if(m_buffer != null && !m_buffer.IsInvalid) {
m_buffer.Close();
m_buffer = null;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void InsertAt( int index, char c ) {
if( index < 0 || index > m_length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
EnsureNotDisposed();
EnsureNotReadOnly();
EnsureCapacity(m_length + 1);
unsafe {
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = m_length; i > index; i--) {
pBuffer[i] = pBuffer[i - 1];
}
pBuffer[index] = c;
++m_length;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public bool IsReadOnly() {
EnsureNotDisposed();
return m_readOnly;
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void MakeReadOnly() {
EnsureNotDisposed();
m_readOnly = true;
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void RemoveAt( int index ) {
EnsureNotDisposed();
EnsureNotReadOnly();
if( index < 0 || index >= m_length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
unsafe
{
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
char* pBuffer = (char*)bufferPtr;
for (int i = index; i < m_length - 1; i++)
{
pBuffer[i] = pBuffer[i + 1];
}
pBuffer[--m_length] = (char)0;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally
{
ProtectMemory();
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
public void SetAt( int index, char c ) {
if( index < 0 || index >= m_length) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
Contract.Assert(index <= Int32.MaxValue / sizeof(char));
EnsureNotDisposed();
EnsureNotReadOnly();
RuntimeHelpers.PrepareConstrainedRegions();
try {
UnProtectMemory();
m_buffer.Write<char>((uint)index * sizeof(char), c);
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
}
}
private int BufferLength {
[System.Security.SecurityCritical] // auto-generated
get {
Contract.Assert(m_buffer != null, "Buffer is not initialized!");
return m_buffer.Length;
}
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private void AllocateBuffer(int size) {
uint alignedSize = GetAlignedSize(size);
m_buffer = SafeBSTRHandle.Allocate(null, alignedSize);
if (m_buffer.IsInvalid) {
throw new OutOfMemoryException();
}
}
private void CheckSupportedOnCurrentPlatform() {
if( !supportedOnCurrentPlatform) {
throw new NotSupportedException(Environment.GetResourceString("Arg_PlatformSecureString"));
}
Contract.EndContractBlock();
}
[System.Security.SecurityCritical] // auto-generated
private void EnsureCapacity(int capacity) {
if( capacity > MaxLength) {
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
Contract.EndContractBlock();
if( capacity <= m_buffer.Length) {
return;
}
SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(null, GetAlignedSize(capacity));
if (newBuffer.IsInvalid) {
throw new OutOfMemoryException();
}
SafeBSTRHandle.Copy(m_buffer, newBuffer);
m_buffer.Close();
m_buffer = newBuffer;
}
[System.Security.SecurityCritical] // auto-generated
private void EnsureNotDisposed() {
if( m_buffer == null) {
throw new ObjectDisposedException(null);
}
Contract.EndContractBlock();
}
private void EnsureNotReadOnly() {
if( m_readOnly) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static uint GetAlignedSize( int size) {
Contract.Assert(size >= 0, "size must be non-negative");
uint alignedSize = ((uint)size / BlockSize) * BlockSize;
if( (size % BlockSize != 0) || size == 0) { // if size is 0, set allocated size to blocksize
alignedSize += BlockSize;
}
return alignedSize;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe int GetAnsiByteCount() {
const uint CP_ACP = 0;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = WC_NO_BEST_FIT_CHARS;
uint DefaultCharUsed = (uint)'?';
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_buffer.AcquirePointer(ref bufferPtr);
return Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
(char*) bufferPtr,
m_length,
null,
0,
IntPtr.Zero,
new IntPtr((void*)&DefaultCharUsed));
}
finally {
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
[System.Security.SecurityCritical] // auto-generated
private unsafe void GetAnsiBytes( byte * ansiStrPtr, int byteCount) {
const uint CP_ACP = 0;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = WC_NO_BEST_FIT_CHARS;
uint DefaultCharUsed = (uint)'?';
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_buffer.AcquirePointer(ref bufferPtr);
Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
(char*) bufferPtr,
m_length,
ansiStrPtr,
byteCount - 1,
IntPtr.Zero,
new IntPtr((void*)&DefaultCharUsed));
*(ansiStrPtr + byteCount - 1) = (byte)0;
}
finally {
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private void ProtectMemory() {
Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0 || m_encrypted) {
return;
}
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
// RtlEncryptMemory return an NTSTATUS
int status = Win32Native.SystemFunction040(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope);
if (status < 0) { // non-negative numbers indicate success
#if FEATURE_CORECLR
throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status));
#else
throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
#endif
}
m_encrypted = true;
}
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal unsafe IntPtr ToBSTR() {
EnsureNotDisposed();
int length = m_length;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
ptr = Win32Native.SysAllocStringLen(null, length);
}
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
result = ptr;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
Win32Native.SysFreeString(ptr);
}
}
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal unsafe IntPtr ToUniStr(bool allocateFromHeap) {
EnsureNotDisposed();
int length = m_length;
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
if( allocateFromHeap) {
ptr = Marshal.AllocHGlobal((length + 1) * 2);
}
else {
ptr = Marshal.AllocCoTaskMem((length + 1) * 2);
}
}
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
UnProtectMemory();
m_buffer.AcquirePointer(ref bufferPtr);
Buffer.Memcpy((byte*) ptr.ToPointer(), bufferPtr, length *2);
char * endptr = (char *) ptr.ToPointer();
*(endptr + length) = '\0';
result = ptr;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)(length * 2));
if( allocateFromHeap) {
Marshal.FreeHGlobal(ptr);
}
else {
Marshal.FreeCoTaskMem(ptr);
}
}
}
if (bufferPtr != null)
m_buffer.ReleasePointer();
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.Synchronized)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal unsafe IntPtr ToAnsiStr(bool allocateFromHeap) {
EnsureNotDisposed();
IntPtr ptr = IntPtr.Zero;
IntPtr result = IntPtr.Zero;
int byteCount = 0;
RuntimeHelpers.PrepareConstrainedRegions();
try {
// GetAnsiByteCount uses the string data, so the calculation must happen after we are decrypted.
UnProtectMemory();
// allocating an extra char for terminating zero
byteCount = GetAnsiByteCount() + 1;
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
if( allocateFromHeap) {
ptr = Marshal.AllocHGlobal(byteCount);
}
else {
ptr = Marshal.AllocCoTaskMem(byteCount);
}
}
if (ptr == IntPtr.Zero) {
throw new OutOfMemoryException();
}
GetAnsiBytes((byte *)ptr.ToPointer(), byteCount);
result = ptr;
}
catch (Exception) {
ProtectMemory();
throw;
}
finally {
ProtectMemory();
if( result == IntPtr.Zero) {
// If we failed for any reason, free the new buffer
if (ptr != IntPtr.Zero) {
Win32Native.ZeroMemory(ptr, (UIntPtr)byteCount);
if( allocateFromHeap) {
Marshal.FreeHGlobal(ptr);
}
else {
Marshal.FreeCoTaskMem(ptr);
}
}
}
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void UnProtectMemory() {
Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0) {
return;
}
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
if (m_encrypted) {
// RtlEncryptMemory return an NTSTATUS
int status = Win32Native.SystemFunction041(m_buffer, (uint)m_buffer.Length * 2, ProtectionScope);
if (status < 0)
{ // non-negative numbers indicate success
#if FEATURE_CORECLR
throw new CryptographicException(Win32Native.RtlNtStatusToDosError(status));
#else
throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
#endif
}
m_encrypted = false;
}
}
}
}
[System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeBSTRHandle : SafeBuffer {
internal SafeBSTRHandle () : base(true) {}
internal static SafeBSTRHandle Allocate(String src, uint len)
{
SafeBSTRHandle bstr = SysAllocStringLen(src, len);
bstr.Initialize(len * sizeof(char));
return bstr;
}
[DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern SafeBSTRHandle SysAllocStringLen(String src, uint len); // BSTR
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
Win32Native.ZeroMemory(handle, (UIntPtr) (Win32Native.SysStringLen(handle) * 2));
Win32Native.SysFreeString(handle);
return true;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe void ClearBuffer() {
byte* bufferPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
AcquirePointer(ref bufferPtr);
Win32Native.ZeroMemory((IntPtr)bufferPtr, (UIntPtr) (Win32Native.SysStringLen((IntPtr)bufferPtr) * 2));
}
finally
{
if (bufferPtr != null)
ReleasePointer();
}
}
internal unsafe int Length {
get {
return (int) Win32Native.SysStringLen(this);
}
}
internal unsafe static void Copy(SafeBSTRHandle source, SafeBSTRHandle target) {
byte* sourcePtr = null, targetPtr = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
source.AcquirePointer(ref sourcePtr);
target.AcquirePointer(ref targetPtr);
Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2);
}
finally
{
if (sourcePtr != null)
source.ReleasePointer();
if (targetPtr != null)
target.ReleasePointer();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
namespace UnitTests.GrainInterfaces
{
public interface IGenericGrainWithGenericState<TFirstTypeParam, TStateType, TLastTypeParam> : IGrainWithGuidKey
{
Task<Type> GetStateType();
}
public class GenericGrainWithGenericState<TFirstTypeParam, TStateType, TLastTypeParam> : Grain<TStateType>,
IGenericGrainWithGenericState<TFirstTypeParam, TStateType, TLastTypeParam> where TStateType : new()
{
public Task<Type> GetStateType() => Task.FromResult(this.State.GetType());
}
public interface IGenericGrain<T, U> : IGrainWithIntegerKey
{
Task SetT(T a);
Task<U> MapT2U();
}
public interface ISimpleGenericGrain1<T> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, T b);
Task SetA(T a);
Task SetB(T b);
}
/// <summary>
/// Long named grain type, which can cause issues in AzureTableStorage
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISimpleGenericGrainUsingAzureStorageAndLongGrainName<T> : IGrainWithGuidKey
{
Task<T> EchoAsync(T entity);
Task ClearState();
}
/// <summary>
/// Short named grain type, which shouldn't cause issues in AzureTableStorage
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITinyNameGrain<T> : IGrainWithGuidKey
{
Task<T> EchoAsync(T entity);
Task ClearState();
}
public interface ISimpleGenericGrainU<U> : IGrainWithIntegerKey
{
Task<U> GetA();
Task<string> GetAxB();
Task<string> GetAxB(U a, U b);
Task SetA(U a);
Task SetB(U b);
}
public interface ISimpleGenericGrain2<T, in U> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, U b);
Task SetA(T a);
Task SetB(U b);
}
public interface IGenericGrainWithNoProperties<in T> : IGrainWithIntegerKey
{
Task<string> GetAxB(T a, T b);
}
public interface IGrainWithNoProperties : IGrainWithIntegerKey
{
Task<string> GetAxB(int a, int b);
}
public interface IGrainWithListFields : IGrainWithIntegerKey
{
Task AddItem(string item);
Task<IList<string>> GetItems();
}
public interface IGenericGrainWithListFields<T> : IGrainWithIntegerKey
{
Task AddItem(T item);
Task<IList<T>> GetItems();
}
public interface IGenericReader1<T> : IGrainWithIntegerKey
{
Task<T> GetValue();
}
public interface IGenericWriter1<in T> : IGrainWithIntegerKey
{
Task SetValue(T value);
}
public interface IGenericReaderWriterGrain1<T> : IGenericWriter1<T>, IGenericReader1<T>
{
}
public interface IGenericReader2<TOne, TTwo> : IGrainWithIntegerKey
{
Task<TOne> GetValue1();
Task<TTwo> GetValue2();
}
public interface IGenericWriter2<in TOne, in TTwo> : IGrainWithIntegerKey
{
Task SetValue1(TOne value);
Task SetValue2(TTwo value);
}
public interface IGenericReaderWriterGrain2<TOne, TTwo> : IGenericWriter2<TOne, TTwo>, IGenericReader2<TOne, TTwo>
{
}
public interface IGenericReader3<TOne, TTwo, TThree> : IGenericReader2<TOne, TTwo>
{
Task<TThree> GetValue3();
}
public interface IGenericWriter3<in TOne, in TTwo, in TThree> : IGenericWriter2<TOne, TTwo>
{
Task SetValue3(TThree value);
}
public interface IGenericReaderWriterGrain3<TOne, TTwo, TThree> : IGenericWriter3<TOne, TTwo, TThree>, IGenericReader3<TOne, TTwo, TThree>
{
}
public interface IBasicGenericGrain<T, U> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, U b);
Task SetA(T a);
Task SetB(U b);
}
public interface IHubGrain<TKey, T1, T2> : IGrainWithIntegerKey
{
Task Bar(TKey key, T1 message1, T2 message2);
}
public interface IEchoHubGrain<TKey, TMessage> : IHubGrain<TKey, TMessage, TMessage>
{
Task Foo(TKey key, TMessage message, int x);
Task<int> GetX();
}
public interface IEchoGenericChainGrain<T> : IGrainWithIntegerKey
{
Task<T> Echo(T item);
Task<T> Echo2(T item);
Task<T> Echo3(T item);
Task<T> Echo4(T item);
Task<T> Echo5(T item);
Task<T> Echo6(T item);
}
public interface INonGenericBase : IGrainWithGuidKey
{
Task Ping();
}
public interface IGeneric1Argument<T> : IGrainWithGuidKey
{
Task<T> Ping(T t);
}
public interface IGeneric2Arguments<T, U> : IGrainWithIntegerKey
{
Task<Tuple<T, U>> Ping(T t, U u);
}
public interface IDbGrain<T> : IGrainWithIntegerKey
{
Task SetValue(T value);
Task<T> GetValue();
}
public interface IGenericPingSelf<T> : IGrainWithGuidKey
{
Task<T> Ping(T t);
Task<T> PingSelf(T t);
Task<T> PingOther(IGenericPingSelf<T> target, T t);
Task<T> PingSelfThroughOther(IGenericPingSelf<T> target, T t);
Task<T> GetLastValue();
Task ScheduleDelayedPing(IGenericPingSelf<T> target, T t, TimeSpan delay);
Task ScheduleDelayedPingToSelfAndDeactivate(IGenericPingSelf<T> target, T t, TimeSpan delay);
}
public interface ILongRunningTaskGrain<T> : IGrainWithGuidKey
{
Task<string> GetRuntimeInstanceId();
Task<string> GetRuntimeInstanceIdWithDelay(TimeSpan delay);
Task LongWait(GrainCancellationToken tc, TimeSpan delay);
Task<T> LongRunningTask(T t, TimeSpan delay);
Task<T> CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay);
Task<T> FanOutOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay, int degreeOfParallelism);
Task CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, GrainCancellationToken tc, TimeSpan delay);
Task CallOtherLongRunningTaskWithLocalToken(ILongRunningTaskGrain<T> target, TimeSpan delay,
TimeSpan delayBeforeCancel);
Task<bool> CancellationTokenCallbackResolve(GrainCancellationToken tc);
Task<bool> CallOtherCancellationTokenCallbackResolve(ILongRunningTaskGrain<T> target);
Task CancellationTokenCallbackThrow(GrainCancellationToken tc);
Task<T> GetLastValue();
}
public interface IGenericGrainWithConstraints<A, B, C> : IGrainWithStringKey
where A : ICollection<B>, new() where B : struct where C : class
{
Task<int> GetCount();
Task Add(B item);
Task<C> RoundTrip(C value);
}
public interface INonGenericCastableGrain : IGrainWithGuidKey
{
Task DoSomething();
}
public interface IGenericCastableGrain<T> : IGrainWithGuidKey
{ }
public interface IGrainSayingHello : IGrainWithGuidKey
{
Task<string> Hello();
}
public interface ISomeGenericGrain<T> : IGrainSayingHello
{ }
public interface INonGenericCastGrain : IGrainSayingHello
{ }
public interface IIndependentlyConcretizedGrain : ISomeGenericGrain<string>
{ }
public interface IIndependentlyConcretizedGenericGrain<T> : ISomeGenericGrain<T>
{ }
namespace Generic.EdgeCases
{
public interface IBasicGrain : IGrainWithGuidKey
{
Task<string> Hello();
Task<string[]> ConcreteGenArgTypeNames();
}
public interface IGrainWithTwoGenArgs<T1, T2> : IBasicGrain
{ }
public interface IGrainWithThreeGenArgs<T1, T2, T3> : IBasicGrain
{ }
public interface IGrainReceivingRepeatedGenArgs<T1, T2> : IBasicGrain
{ }
public interface IPartiallySpecifyingInterface<T> : IGrainWithTwoGenArgs<T, int>
{ }
public interface IReceivingRepeatedGenArgsAmongstOthers<T1, T2, T3> : IBasicGrain
{ }
public interface IReceivingRepeatedGenArgsFromOtherInterface<T1, T2, T3> : IBasicGrain
{ }
public interface ISpecifyingGenArgsRepeatedlyToParentInterface<T> : IReceivingRepeatedGenArgsFromOtherInterface<T, T, T>
{ }
public interface IReceivingRearrangedGenArgs<T1, T2> : IBasicGrain
{ }
public interface IReceivingRearrangedGenArgsViaCast<T1, T2> : IBasicGrain
{ }
public interface ISpecifyingRearrangedGenArgsToParentInterface<T1, T2> : IReceivingRearrangedGenArgsViaCast<T2, T1>
{ }
public interface IArbitraryInterface<T1, T2> : IBasicGrain
{ }
public interface IInterfaceUnrelatedToConcreteGenArgs<T> : IBasicGrain
{ }
public interface IInterfaceTakingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
public interface IAnotherReceivingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
public interface IYetOneMoreReceivingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
using UMA;
using UMA.Integrations;
namespace UMAEditor
{
public class DNAMasterEditor
{
private readonly Dictionary<Type, DNASingleEditor> _dnaValues = new Dictionary<Type, DNASingleEditor>();
private readonly Type[] _dnaTypes;
private readonly string[] _dnaTypeNames;
public int viewDna = 0;
public UMAData.UMARecipe recipe;
public static UMAGeneratorBase umaGenerator;
public DNAMasterEditor(UMAData.UMARecipe recipe)
{
this.recipe = recipe;
UMADnaBase[] allDna = recipe.GetAllDna();
_dnaTypes = new Type[allDna.Length];
_dnaTypeNames = new string[allDna.Length];
for (int i = 0; i < allDna.Length; i++)
{
var entry = allDna[i];
var entryType = entry.GetType();
_dnaTypes[i] = entryType;
_dnaTypeNames[i] = entryType.Name;
_dnaValues[entryType] = new DNASingleEditor(entry);
}
}
public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
GUILayout.BeginHorizontal();
var newToolBarIndex = EditorGUILayout.Popup("DNA", viewDna, _dnaTypeNames);
if (newToolBarIndex != viewDna)
{
viewDna = newToolBarIndex;
}
GUI.enabled = viewDna >= 0;
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(24)))
{
if (viewDna >= 0)
{
recipe.RemoveDna(_dnaTypes[viewDna]);
if (viewDna >= _dnaTypes.Length - 1) viewDna--;
GUI.enabled = true;
GUILayout.EndHorizontal();
_dnaDirty = true;
return true;
}
}
GUI.enabled = true;
GUILayout.EndHorizontal();
if (viewDna >= 0)
{
Type dnaType = _dnaTypes[viewDna];
if (_dnaValues[dnaType].OnGUI())
{
_dnaDirty = true;
return true;
}
}
return false;
}
internal bool NeedsReenable()
{
return _dnaValues == null;
}
public bool IsValid
{
get
{
return !(_dnaTypes == null || _dnaTypes.Length == 0);
}
}
}
public class DNASingleEditor
{
private readonly SortedDictionary<string, DNAGroupEditor> _groups = new SortedDictionary<string, DNAGroupEditor>();
public DNASingleEditor(UMADnaBase dna)
{
var fields = dna.GetType().GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType != typeof(float))
{
continue;
}
string fieldName;
string groupName;
GetNamesFromField(field, out fieldName, out groupName);
DNAGroupEditor group;
_groups.TryGetValue(groupName, out @group);
if (group == null)
{
@group = new DNAGroupEditor(groupName);
_groups.Add(groupName, @group);
}
var entry = new DNAFieldEditor(fieldName, field, dna);
@group.Add(entry);
}
foreach (var group in _groups.Values)
@group.Sort();
}
private static void GetNamesFromField(FieldInfo field, out string fieldName, out string groupName)
{
fieldName = ObjectNames.NicifyVariableName(field.Name);
groupName = "Other";
string[] chunks = fieldName.Split(' ');
if (chunks.Length > 1)
{
groupName = chunks[0];
fieldName = fieldName.Substring(groupName.Length + 1);
}
}
public bool OnGUI()
{
bool changed = false;
foreach (var dnaGroup in _groups.Values)
{
changed |= dnaGroup.OnGUI();
}
return changed;
}
}
public class DNAGroupEditor
{
private readonly List<DNAFieldEditor> _fields = new List<DNAFieldEditor>();
private readonly string _groupName;
private bool _foldout = true;
public DNAGroupEditor(string groupName)
{
_groupName = groupName;
}
public bool OnGUI()
{
_foldout = EditorGUILayout.Foldout(_foldout, _groupName);
if (!_foldout)
return false;
bool changed = false;
GUILayout.BeginVertical(EditorStyles.textField);
foreach (var field in _fields)
{
changed |= field.OnGUI();
}
GUILayout.EndVertical();
return changed;
}
public void Add(DNAFieldEditor field)
{
_fields.Add(field);
}
public void Sort()
{
_fields.Sort(DNAFieldEditor.comparer);
}
}
public class DNAFieldEditor
{
public static Comparer comparer = new Comparer();
private readonly UMADnaBase _dna;
private readonly FieldInfo _field;
private readonly string _name;
private readonly float _value;
public DNAFieldEditor(string name, FieldInfo field, UMADnaBase dna)
{
_name = name;
_field = field;
_dna = dna;
_value = (float)field.GetValue(dna);
}
public bool OnGUI()
{
float newValue = EditorGUILayout.Slider(_name, _value, 0f, 1f);
//float newValue = EditorGUILayout.FloatField(_name, _value);
if (newValue != _value)
{
_field.SetValue(_dna, newValue);
return true;
}
return false;
}
public class Comparer : IComparer <DNAFieldEditor>
{
public int Compare(DNAFieldEditor x, DNAFieldEditor y)
{
return String.CompareOrdinal(x._name, y._name);
}
}
}
public class SharedColorsCollectionEditor
{
private bool _foldout = true;
static int selectedChannelCount = 2;
String[] names = new string[4] { "1", "2", "3", "4" };
int[] channels = new int[4] { 1, 2, 3, 4 };
static bool[] _ColorFoldouts = new bool[0];
public bool OnGUI (UMAData.UMARecipe _recipe)
{
GUILayout.BeginHorizontal (EditorStyles.toolbarButton);
GUILayout.Space (10);
_foldout = EditorGUILayout.Foldout (_foldout, "Shared Colors");
GUILayout.EndHorizontal ();
if (_foldout) {
bool changed = false;
GUIHelper.BeginVerticalPadded (10, new Color (0.75f, 0.875f, 1f));
EditorGUILayout.BeginHorizontal ();
if (_recipe.sharedColors == null)
_recipe.sharedColors = new OverlayColorData[0];
if (_recipe.sharedColors.Length == 0) {
selectedChannelCount = EditorGUILayout.IntPopup ("Channels", selectedChannelCount, names, channels);
} else {
selectedChannelCount = _recipe.sharedColors [0].channelMask.Length;
}
if (GUILayout.Button ("Add Shared Color")) {
List<OverlayColorData> sharedColors = new List<OverlayColorData> ();
sharedColors.AddRange (_recipe.sharedColors);
sharedColors.Add (new OverlayColorData (selectedChannelCount));
_recipe.sharedColors = sharedColors.ToArray ();
changed = true;
}
if (GUILayout.Button ("Save Collection")) {
changed = true;
}
EditorGUILayout.EndHorizontal ();
if (_ColorFoldouts.Length != _recipe.sharedColors.Length) {
Array.Resize<bool> (ref _ColorFoldouts, _recipe.sharedColors.Length);
}
for (int i = 0; i < _recipe.sharedColors.Length; i++) {
bool del = false;
OverlayColorData ocd = _recipe.sharedColors [i];
GUIHelper.FoldoutBar (ref _ColorFoldouts [i], i + ": " + ocd.name, out del);
if (del) {
List<OverlayColorData> temp = new List<OverlayColorData> ();
temp.AddRange (_recipe.sharedColors);
temp.RemoveAt (i);
_recipe.sharedColors = temp.ToArray ();
// TODO: search the overlays and adjust the shared colors
break;
}
if (_ColorFoldouts [i]) {
if (ocd.name == null)
ocd.name = "";
string NewName = EditorGUILayout.TextField ("Name", ocd.name);
if (NewName != ocd.name) {
ocd.name = NewName;
//changed = true;
}
Color NewChannelMask = EditorGUILayout.ColorField ("Color Multiplier", ocd.channelMask [0]);
if (ocd.channelMask [0] != NewChannelMask) {
ocd.channelMask [0] = NewChannelMask;
changed = true;
}
Color NewChannelAdditiveMask = EditorGUILayout.ColorField ("Color Additive", ocd.channelAdditiveMask [0]);
if (ocd.channelAdditiveMask [0] != NewChannelAdditiveMask) {
ocd.channelAdditiveMask [0] = NewChannelAdditiveMask;
changed = true;
}
for (int j = 1; j < ocd.channelMask.Length; j++) {
NewChannelMask = EditorGUILayout.ColorField ("Texture " + j + "multiplier", ocd.channelMask [j]);
if (ocd.channelMask [j] != NewChannelMask) {
ocd.channelMask [j] = NewChannelMask;
changed = true;
}
NewChannelAdditiveMask = EditorGUILayout.ColorField ("Texture " + j + " additive", ocd.channelAdditiveMask [j]);
if (ocd.channelAdditiveMask [j] != NewChannelAdditiveMask) {
ocd.channelAdditiveMask [j] = NewChannelAdditiveMask;
changed = true;
}
}
}
}
GUIHelper.EndVerticalPadded (10);
return changed;
}
return false;
}
}
public class SlotMasterEditor
{
private readonly UMAData.UMARecipe _recipe;
private readonly List<SlotEditor> _slotEditors = new List<SlotEditor>();
private readonly SharedColorsCollectionEditor _sharedColorsEditor = new SharedColorsCollectionEditor ();
public SlotMasterEditor(UMAData.UMARecipe recipe)
{
_recipe = recipe;
if (recipe.slotDataList == null)
{
recipe.slotDataList = new SlotData[0];
}
for (int i = 0; i < recipe.slotDataList.Length; i++ )
{
var slot = recipe.slotDataList[i];
if (slot == null)
continue;
_slotEditors.Add(new SlotEditor(_recipe, slot, i));
}
_slotEditors.Sort(SlotEditor.comparer);
if (_slotEditors.Count > 1)
{
var overlays1 = _slotEditors[0].GetOverlays();
var overlays2 = _slotEditors[1].GetOverlays();
for (int i = 0; i < _slotEditors.Count - 2; i++ )
{
if (overlays1 == overlays2)
_slotEditors[i].sharedOverlays = true;
overlays1 = overlays2;
overlays2 = _slotEditors[i + 2].GetOverlays();
}
}
}
public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
bool changed = false;
// Have to be able to assign a race on a new recipe.
RaceData newRace = (RaceData)EditorGUILayout.ObjectField("RaceData",_recipe.raceData,typeof(RaceData),false);
if (_recipe.raceData == null) {
GUIHelper.BeginVerticalPadded (10, new Color (0.55f, 0.25f, 0.25f));
GUILayout.Label ("Warning: No race data is set!");
GUIHelper.EndVerticalPadded (10);
}
if (_recipe.raceData != newRace)
{
_recipe.SetRace(newRace);
changed = true;
}
if (GUILayout.Button("Remove Nulls"))
{
var newList = new List<SlotData>(_recipe.slotDataList.Length);
foreach (var slotData in _recipe.slotDataList)
{
if (slotData != null) newList.Add(slotData);
}
_recipe.slotDataList = newList.ToArray();
changed |= true;
_dnaDirty |= true;
_textureDirty |= true;
_meshDirty |= true;
}
if (_sharedColorsEditor.OnGUI (_recipe)) {
changed = true;
_textureDirty = true;
}
var added = (SlotDataAsset)EditorGUILayout.ObjectField("Add Slot", null, typeof(SlotDataAsset), false);
if (added != null)
{
var slot = new SlotData(added);
_recipe.MergeSlot(slot, false);
changed |= true;
_dnaDirty |= true;
_textureDirty |= true;
_meshDirty |= true;
}
for (int i = 0; i < _slotEditors.Count; i++)
{
var editor = _slotEditors[i];
if (editor == null)
{
GUILayout.Label("Empty Slot");
continue;
}
changed |= editor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty);
if (editor.Delete)
{
_dnaDirty = true;
_textureDirty = true;
_meshDirty = true;
_slotEditors.RemoveAt(i);
_recipe.SetSlot(editor.idx, null);
i--;
changed = true;
}
}
return changed;
}
}
public class SlotEditor
{
private readonly UMAData.UMARecipe _recipe;
private readonly SlotData _slotData;
private readonly List<OverlayData> _overlayData = new List<OverlayData>();
private readonly List<OverlayEditor> _overlayEditors = new List<OverlayEditor>();
private readonly string _name;
public bool Delete { get; private set; }
private bool _foldout = true;
public bool sharedOverlays = false;
public int idx;
public SlotEditor(UMAData.UMARecipe recipe, SlotData slotData, int index)
{
_recipe = recipe;
_slotData = slotData;
_overlayData = slotData.GetOverlayList();
this.idx = index;
_name = slotData.asset.slotName;
for (int i = 0; i < _overlayData.Count; i++)
{
_overlayEditors.Add(new OverlayEditor(_recipe, slotData, _overlayData[i]));
}
}
public List<OverlayData> GetOverlays()
{
return _overlayData;
}
public bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
bool delete;
GUIHelper.FoldoutBar(ref _foldout, _name, out delete);
if (!_foldout)
return false;
Delete = delete;
bool changed = false;
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
if (sharedOverlays)
{
EditorGUILayout.LabelField("Shared Overlays");
}
else
{
var added = (OverlayDataAsset)EditorGUILayout.ObjectField("Add Overlay", null, typeof(OverlayDataAsset), false);
if (added != null)
{
var newOverlay = new OverlayData(added);
_overlayEditors.Add(new OverlayEditor(_recipe, _slotData, newOverlay));
_overlayData.Add(newOverlay);
_dnaDirty = true;
_textureDirty = true;
_meshDirty = true;
changed = true;
}
var addedSlot = (SlotDataAsset)EditorGUILayout.ObjectField("Add Slot", null, typeof(SlotDataAsset), false);
if (addedSlot != null)
{
var newSlot = new SlotData(addedSlot);
newSlot.SetOverlayList(_slotData.GetOverlayList());
_recipe.MergeSlot(newSlot, false);
_dnaDirty = true;
_textureDirty = true;
_meshDirty = true;
changed = true;
}
for (int i = 0; i < _overlayEditors.Count; i++)
{
var overlayEditor = _overlayEditors[i];
if (overlayEditor.OnGUI())
{
_textureDirty = true;
changed = true;
}
if (overlayEditor.Delete)
{
_overlayEditors.RemoveAt(i);
_overlayData.RemoveAt(i);
_textureDirty = true;
changed = true;
i--;
}
}
for (int i = 0; i < _overlayEditors.Count; i++)
{
var overlayEditor = _overlayEditors[i];
if (overlayEditor.move > 0 && i + 1 < _overlayEditors.Count)
{
_overlayEditors[i] = _overlayEditors[i + 1];
_overlayEditors[i + 1] = overlayEditor;
var overlayData = _overlayData[i];
_overlayData[i] = _overlayData[i + 1];
_overlayData[i + 1] = overlayData;
overlayEditor.move = 0;
_textureDirty = true;
changed = true;
continue;
}
if (overlayEditor.move < 0 && i > 0)
{
_overlayEditors[i] = _overlayEditors[i - 1];
_overlayEditors[i - 1] = overlayEditor;
var overlayData = _overlayData[i];
_overlayData[i] = _overlayData[i - 1];
_overlayData[i - 1] = overlayData;
overlayEditor.move = 0;
_textureDirty = true;
changed = true;
continue;
}
}
}
GUIHelper.EndVerticalPadded(10);
return changed;
}
public static Comparer comparer = new Comparer();
public class Comparer : IComparer <SlotEditor>
{
public int Compare(SlotEditor x, SlotEditor y)
{
if (x._overlayData == y._overlayData)
return 0;
if (x._overlayData == null)
return 1;
if (y._overlayData == null)
return -1;
return x._overlayData.GetHashCode() - y._overlayData.GetHashCode();
}
}
}
public class OverlayEditor
{
private readonly UMAData.UMARecipe _recipe;
protected readonly SlotData _slotData;
private readonly OverlayData _overlayData;
private ColorEditor[] _colors;
private bool _sharedColors;
private readonly TextureEditor[] _textures;
private bool _foldout = true;
public bool Delete { get; private set; }
public int move;
private static OverlayData showExtendedRangeForOverlay;
public OverlayEditor(UMAData.UMARecipe recipe, SlotData slotData, OverlayData overlayData)
{
_recipe = recipe;
_overlayData = overlayData;
_slotData = slotData;
_sharedColors = false;
if (_recipe.sharedColors != null)
{
_sharedColors = ArrayUtility.Contains<OverlayColorData>(_recipe.sharedColors, _overlayData.colorData);
}
if (_sharedColors && (_overlayData.colorData.name == OverlayColorData.UNSHARED))
{
_sharedColors = false;
}
_textures = new TextureEditor[overlayData.asset.textureList.Length];
for (int i = 0; i < overlayData.asset.textureList.Length; i++)
{
_textures[i] = new TextureEditor(overlayData.asset.textureList[i]);
}
BuildColorEditors();
}
private void BuildColorEditors()
{
_colors = new ColorEditor[_overlayData.colorData.channelMask.Length * 2];
for (int i = 0; i < _overlayData.colorData.channelMask.Length; i++)
{
_colors[i * 2] = new ColorEditor(
_overlayData.colorData.channelMask[i],
String.Format(i == 0
? "Color multiplier"
: "Texture {0} multiplier", i));
_colors[i * 2 + 1] = new ColorEditor(
_overlayData.colorData.channelAdditiveMask[i],
String.Format(i == 0
? "Color additive"
: "Texture {0} additive", i));
}
}
public bool OnGUI()
{
bool delete;
GUIHelper.FoldoutBar(ref _foldout, _overlayData.asset.overlayName, out move, out delete);
if (!_foldout)
return false;
Delete = delete;
GUIHelper.BeginHorizontalPadded(10, Color.white);
GUILayout.BeginVertical();
bool changed = OnColorGUI();
GUILayout.BeginHorizontal();
foreach (var texture in _textures)
{
changed |= texture.OnGUI();
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUIHelper.EndVerticalPadded(10);
return changed;
}
public bool OnColorGUI ()
{
bool changed = false;
int currentsharedcol = 0;
string[] sharednames = new string[_recipe.sharedColors.Length];
if (_sharedColors) {
GUIHelper.BeginVerticalPadded (2f, new Color (0.75f, 0.875f, 1f));
GUILayout.BeginHorizontal ();
if (GUILayout.Toggle (true, "Use Shared Color") == false) {
// Unshare color
_overlayData.colorData = _overlayData.colorData.Duplicate ();
_overlayData.colorData.name = OverlayColorData.UNSHARED;
changed = true;
}
for (int i = 0; i < _recipe.sharedColors.Length; i++) {
sharednames [i] = i + ": " + _recipe.sharedColors [i].name;
if (_overlayData.colorData.GetHashCode () == _recipe.sharedColors [i].GetHashCode ()) {
currentsharedcol = i;
}
}
int newcol = EditorGUILayout.Popup (currentsharedcol, sharednames);
if (newcol != currentsharedcol) {
changed = true;
_overlayData.colorData = _recipe.sharedColors [newcol];
}
GUILayout.EndHorizontal ();
GUIHelper.EndVerticalPadded (2f);
GUILayout.Space (2f);
return changed;
}
GUIHelper.BeginVerticalPadded (2f, new Color (0.75f, 0.875f, 1f));
GUILayout.BeginHorizontal ();
if (_recipe.sharedColors.Length > 0) {
if (GUILayout.Toggle (false, "Use Shared Color")) {
// If we got rid of resetting the name above, we could try to match the last shared color?
// Just set to default for now.
_overlayData.colorData = _recipe.sharedColors [0];
changed = true;
}
}
GUILayout.EndHorizontal ();
bool showExtendedRanges = showExtendedRangeForOverlay == _overlayData;
var newShowExtendedRanges = EditorGUILayout.Toggle ("Show Extended Ranges", showExtendedRanges);
if (showExtendedRanges != newShowExtendedRanges) {
if (newShowExtendedRanges) {
showExtendedRangeForOverlay = _overlayData;
} else {
showExtendedRangeForOverlay = null;
}
}
for (int k = 0; k < _colors.Length; k++) {
Color color;
if (showExtendedRanges && k % 2 == 0) {
Vector4 colorVector = new Vector4 (_colors [k].color.r, _colors [k].color.g, _colors [k].color.b, _colors [k].color.a);
colorVector = EditorGUILayout.Vector4Field (_colors [k].description, colorVector);
color = new Color (colorVector.x, colorVector.y, colorVector.z, colorVector.w);
} else {
color = EditorGUILayout.ColorField (_colors [k].description, _colors [k].color);
}
if (color.r != _colors [k].color.r ||
color.g != _colors [k].color.g ||
color.b != _colors [k].color.b ||
color.a != _colors [k].color.a) {
if (k % 2 == 0) {
_overlayData.colorData.channelMask [k / 2] = color;
} else {
_overlayData.colorData.channelAdditiveMask [k / 2] = color;
}
changed = true;
}
}
GUIHelper.EndVerticalPadded (2f);
GUILayout.Space (2f);
return changed;
}
}
public class TextureEditor
{
private Texture _texture;
public TextureEditor(Texture texture)
{
_texture = texture;
}
public bool OnGUI()
{
bool changed = false;
float origLabelWidth = EditorGUIUtility.labelWidth;
int origIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
EditorGUIUtility.labelWidth = 0;
var newTexture = (Texture)EditorGUILayout.ObjectField("", _texture, typeof(Texture), false, GUILayout.Width(100));
EditorGUI.indentLevel = origIndentLevel;
EditorGUIUtility.labelWidth = origLabelWidth;
if (newTexture != _texture)
{
_texture = newTexture;
changed = true;
}
return changed;
}
}
public class ColorEditor
{
public Color color;
public string description;
public ColorEditor(Color color, string description)
{
this.color = color;
this.description = description;
}
}
public abstract class CharacterBaseEditor : Editor
{
protected readonly string[] toolbar =
{
"DNA", "Slots"
};
protected string _description;
protected string _errorMessage;
protected bool _needsUpdate;
protected bool _dnaDirty;
protected bool _textureDirty;
protected bool _meshDirty;
protected Object _oldTarget;
protected bool showBaseEditor;
protected bool _rebuildOnLayout = false;
protected UMAData.UMARecipe _recipe;
protected int _toolbarIndex = 0;
protected DNAMasterEditor dnaEditor;
protected SlotMasterEditor slotEditor;
protected bool NeedsReenable()
{
if (dnaEditor == null || dnaEditor.NeedsReenable())
return true;
if (_oldTarget == target)
return false;
_oldTarget = target;
return true;
}
/// <summary>
/// Override PreInspectorGUI in any derived editors to allow editing of new properties added to recipes.
/// </summary>
public virtual bool PreInspectorGUI()
{
return false;
}
public override void OnInspectorGUI()
{
GUILayout.Label(_description);
if (_errorMessage != null)
{
GUI.color = Color.red;
GUILayout.Label(_errorMessage);
if (_recipe != null && GUILayout.Button("Clear"))
{
_errorMessage = null;
} else
{
return;
}
}
try
{
if (target != _oldTarget)
{
_rebuildOnLayout = true;
_oldTarget = target;
}
if (_rebuildOnLayout && Event.current.type == EventType.layout)
{
Rebuild();
}
_needsUpdate = PreInspectorGUI();
if (ToolbarGUI())
{
_needsUpdate = true;
}
if (_needsUpdate)
{
DoUpdate();
}
} catch (UMAResourceNotFoundException e)
{
_errorMessage = e.Message;
}
if (showBaseEditor)
{
base.OnInspectorGUI();
}
}
protected abstract void DoUpdate();
protected virtual void Rebuild()
{
_rebuildOnLayout = false;
if (_recipe != null)
{
int oldViewDNA = dnaEditor.viewDna;
UMAData.UMARecipe oldRecipe = dnaEditor.recipe;
dnaEditor = new DNAMasterEditor(_recipe);
if (oldRecipe == _recipe)
{
dnaEditor.viewDna = oldViewDNA;
}
slotEditor = new SlotMasterEditor(_recipe);
}
}
private bool ToolbarGUI()
{
_toolbarIndex = GUILayout.Toolbar(_toolbarIndex, toolbar);
switch (_toolbarIndex)
{
case 0:
if (!dnaEditor.IsValid) return false;
return dnaEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty);
case 1:
return slotEditor.OnGUI(ref _dnaDirty, ref _textureDirty, ref _meshDirty);
}
return false;
}
}
}
#endif
| |
//
// 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;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Management.Network
{
/// <summary>
/// The Windows Azure Network management API provides a RESTful set of web
/// services that interact with Windows Azure Networks service to manage
/// your network resrources. The API has entities that capture the
/// relationship between an end user and the Windows Azure Networks
/// service.
/// </summary>
public static partial class NetworkInterfaceOperationsExtensions
{
/// <summary>
/// The Put NetworkInterface operation creates/updates a
/// networkInterface
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/update NetworkInterface
/// operation
/// </param>
/// <returns>
/// Response for PutNetworkInterface Api servive call
/// </returns>
public static NetworkInterfacePutResponse BeginCreateOrUpdating(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, networkInterfaceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a
/// networkInterface
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/update NetworkInterface
/// operation
/// </param>
/// <returns>
/// Response for PutNetworkInterface Api servive call
/// </returns>
public static Task<NetworkInterfacePutResponse> BeginCreateOrUpdatingAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return operations.BeginCreateOrUpdatingAsync(resourceGroupName, networkInterfaceName, parameters, CancellationToken.None);
}
/// <summary>
/// The delete netwokInterface operation deletes the specified
/// netwokInterface.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public static UpdateOperationResponse BeginDeleting(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).BeginDeletingAsync(resourceGroupName, networkInterfaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The delete netwokInterface operation deletes the specified
/// netwokInterface.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public static Task<UpdateOperationResponse> BeginDeletingAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.BeginDeletingAsync(resourceGroupName, networkInterfaceName, CancellationToken.None);
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a
/// networkInterface
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/update NetworkInterface
/// operation
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static AzureAsyncOperationResponse CreateOrUpdate(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put NetworkInterface operation creates/updates a
/// networkInterface
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the create/update NetworkInterface
/// operation
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters, CancellationToken.None);
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).DeleteAsync(resourceGroupName, networkInterfaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.DeleteAsync(resourceGroupName, networkInterfaceName, CancellationToken.None);
}
/// <summary>
/// The Get ntework interface operation retreives information about the
/// specified network interface.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <returns>
/// Response for GetNetworkInterface Api service call
/// </returns>
public static NetworkInterfaceGetResponse Get(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).GetAsync(resourceGroupName, networkInterfaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get ntework interface operation retreives information about the
/// specified network interface.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// Required. The name of the network interface.
/// </param>
/// <returns>
/// Response for GetNetworkInterface Api service call
/// </returns>
public static Task<NetworkInterfaceGetResponse> GetAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName)
{
return operations.GetAsync(resourceGroupName, networkInterfaceName, CancellationToken.None);
}
/// <summary>
/// The List networkInterfaces opertion retrieves all the
/// networkInterfaces in a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
public static NetworkInterfaceListResponse List(this INetworkInterfaceOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List networkInterfaces opertion retrieves all the
/// networkInterfaces in a resource group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
public static Task<NetworkInterfaceListResponse> ListAsync(this INetworkInterfaceOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
/// <summary>
/// The List networkInterfaces opertion retrieves all the
/// networkInterfaces in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
public static NetworkInterfaceListResponse ListAll(this INetworkInterfaceOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkInterfaceOperations)s).ListAllAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List networkInterfaces opertion retrieves all the
/// networkInterfaces in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.INetworkInterfaceOperations.
/// </param>
/// <returns>
/// Response for ListNetworkInterface Api service call
/// </returns>
public static Task<NetworkInterfaceListResponse> ListAllAsync(this INetworkInterfaceOperations operations)
{
return operations.ListAllAsync(CancellationToken.None);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SkinningSample.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using SkinnedModel;
using Primitives3D;
#endregion
namespace SkinningSample
{
/// <summary>
/// Sample game showing how to display skinned character animation.
/// </summary>
public class SkinningSampleGame : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
KeyboardState currentKeyboardState = new KeyboardState();
GamePadState currentGamePadState = new GamePadState();
KeyboardState previousKeyboardState = new KeyboardState();
GamePadState previousGamePadState = new GamePadState();
SkinnedSphere[] skinnedSpheres;
BoundingSphere[] boundingSpheres;
bool showSpheres;
SpherePrimitive spherePrimitive;
Model currentModel;
AnimationPlayer animationPlayer;
SkinningData skinningData;
Matrix[] boneTransforms;
Model baseballBat;
float cameraArc = 0;
float cameraRotation = 0;
float cameraDistance = 100;
#endregion
#region Initialization
public SkinningSampleGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if WINDOWS_PHONE
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
graphics.IsFullScreen = true;
#endif
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load the model.
currentModel = Content.Load<Model>("dude");
// Look up our custom skinning information.
skinningData = currentModel.Tag as SkinningData;
if (skinningData == null)
throw new InvalidOperationException
("This model does not contain a SkinningData tag.");
boneTransforms = new Matrix[skinningData.BindPose.Count];
// Load the baseball bat model.
baseballBat = Content.Load<Model>("baseballbat");
// Create an animation player, and start decoding an animation clip.
animationPlayer = new AnimationPlayer(skinningData);
AnimationClip clip = skinningData.AnimationClips["Take 001"];
animationPlayer.StartClip(clip);
// Load the bounding spheres.
skinnedSpheres = Content.Load<SkinnedSphere[]>("CollisionSpheres");
boundingSpheres = new BoundingSphere[skinnedSpheres.Length];
spherePrimitive = new SpherePrimitive(GraphicsDevice, 1, 12);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
HandleInput();
UpdateCamera(gameTime);
// Read gamepad inputs.
float headRotation = currentGamePadState.ThumbSticks.Left.X;
float armRotation = Math.Max(currentGamePadState.ThumbSticks.Left.Y, 0);
// Read keyboard inputs.
if (currentKeyboardState.IsKeyDown(Keys.PageUp))
headRotation = -1;
else if (currentKeyboardState.IsKeyDown(Keys.PageDown))
headRotation = 1;
if (currentKeyboardState.IsKeyDown(Keys.Space))
armRotation = 0.5f;
// Create rotation matrices for the head and arm bones.
Matrix headTransform = Matrix.CreateRotationX(headRotation);
Matrix armTransform = Matrix.CreateRotationY(-armRotation);
// Tell the animation player to compute the latest bone transform matrices.
animationPlayer.UpdateBoneTransforms(gameTime.ElapsedGameTime, true);
// Copy the transforms into our own array, so we can safely modify the values.
animationPlayer.GetBoneTransforms().CopyTo(boneTransforms, 0);
// Modify the transform matrices for the head and upper-left arm bones.
int headIndex = skinningData.BoneIndices["Head"];
int armIndex = skinningData.BoneIndices["L_UpperArm"];
boneTransforms[headIndex] = headTransform * boneTransforms[headIndex];
boneTransforms[armIndex] = armTransform * boneTransforms[armIndex];
// Tell the animation player to recompute the world and skin matrices.
animationPlayer.UpdateWorldTransforms(Matrix.Identity, boneTransforms);
animationPlayer.UpdateSkinTransforms();
UpdateBoundingSpheres();
base.Update(gameTime);
}
/// <summary>
/// Updates the boundingSpheres array to match the current animation state.
/// </summary>
void UpdateBoundingSpheres()
{
// Look up the current world space bone positions.
Matrix[] worldTransforms = animationPlayer.GetWorldTransforms();
for (int i = 0; i < skinnedSpheres.Length; i++)
{
// Convert the SkinnedSphere description to a BoundingSphere.
SkinnedSphere source = skinnedSpheres[i];
Vector3 center = new Vector3(source.Offset, 0, 0);
BoundingSphere sphere = new BoundingSphere(center, source.Radius);
// Transform the BoundingSphere by its parent bone matrix,
// and store the result into the boundingSpheres array.
int boneIndex = skinningData.BoneIndices[source.BoneName];
boundingSpheres[i] = sphere.Transform(worldTransforms[boneIndex]);
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice device = graphics.GraphicsDevice;
device.Clear(Color.CornflowerBlue);
Matrix[] bones = animationPlayer.GetSkinTransforms();
// Compute camera matrices.
Matrix view = Matrix.CreateTranslation(0, -40, 0) *
Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) *
Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
Matrix.CreateLookAt(new Vector3(0, 0, -cameraDistance),
new Vector3(0, 0, 0), Vector3.Up);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
device.Viewport.AspectRatio,
1,
10000);
// Render the skinned mesh.
foreach (ModelMesh mesh in currentModel.Meshes)
{
foreach (SkinnedEffect effect in mesh.Effects)
{
effect.SetBoneTransforms(bones);
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.SpecularColor = new Vector3(0.25f);
effect.SpecularPower = 16;
}
mesh.Draw();
}
DrawBaseballBat(view, projection);
if (showSpheres)
{
DrawBoundingSpheres(view, projection);
}
base.Draw(gameTime);
}
/// <summary>
/// Draws the animated bounding spheres.
/// </summary>
void DrawBoundingSpheres(Matrix view, Matrix projection)
{
GraphicsDevice.RasterizerState = Wireframe;
foreach (BoundingSphere sphere in boundingSpheres)
{
Matrix world = Matrix.CreateScale(sphere.Radius) *
Matrix.CreateTranslation(sphere.Center);
spherePrimitive.Draw(world, view, projection, Color.White);
}
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
}
static RasterizerState Wireframe = new RasterizerState
{
FillMode = FillMode.WireFrame
};
/// <summary>
/// Draws the baseball bat.
/// </summary>
void DrawBaseballBat(Matrix view, Matrix projection)
{
int handIndex = skinningData.BoneIndices["L_Index1"];
Matrix[] worldTransforms = animationPlayer.GetWorldTransforms();
// Nudge the bat over so it appears between the left thumb and index finger.
Matrix batWorldTransform = Matrix.CreateTranslation(-1.3f, 2.1f, 0.1f) *
worldTransforms[handIndex];
foreach (ModelMesh mesh in baseballBat.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = batWorldTransform;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
}
mesh.Draw();
}
}
#endregion
#region Handle Input
/// <summary>
/// Handles input for quitting the game.
/// </summary>
private void HandleInput()
{
previousKeyboardState = currentKeyboardState;
previousGamePadState = currentGamePadState;
currentKeyboardState = Keyboard.GetState();
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Check for exit.
if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
currentGamePadState.Buttons.Back == ButtonState.Pressed)
{
Exit();
}
// Toggle the collision sphere display.
if ((currentKeyboardState.IsKeyDown(Keys.Enter) &&
previousKeyboardState.IsKeyUp(Keys.Enter)) ||
(currentGamePadState.IsButtonDown(Buttons.A) &&
previousGamePadState.IsButtonUp(Buttons.A)))
{
showSpheres = !showSpheres;
}
}
/// <summary>
/// Handles camera input.
/// </summary>
private void UpdateCamera(GameTime gameTime)
{
float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;
// Check for input to rotate the camera up and down around the model.
if (currentKeyboardState.IsKeyDown(Keys.Up) ||
currentKeyboardState.IsKeyDown(Keys.W))
{
cameraArc += time * 0.1f;
}
if (currentKeyboardState.IsKeyDown(Keys.Down) ||
currentKeyboardState.IsKeyDown(Keys.S))
{
cameraArc -= time * 0.1f;
}
cameraArc += currentGamePadState.ThumbSticks.Right.Y * time * 0.25f;
// Limit the arc movement.
if (cameraArc > 90.0f)
cameraArc = 90.0f;
else if (cameraArc < -90.0f)
cameraArc = -90.0f;
// Check for input to rotate the camera around the model.
if (currentKeyboardState.IsKeyDown(Keys.Right) ||
currentKeyboardState.IsKeyDown(Keys.D))
{
cameraRotation += time * 0.1f;
}
if (currentKeyboardState.IsKeyDown(Keys.Left) ||
currentKeyboardState.IsKeyDown(Keys.A))
{
cameraRotation -= time * 0.1f;
}
cameraRotation += currentGamePadState.ThumbSticks.Right.X * time * 0.25f;
// Check for input to zoom camera in and out.
if (currentKeyboardState.IsKeyDown(Keys.Z))
cameraDistance += time * 0.25f;
if (currentKeyboardState.IsKeyDown(Keys.X))
cameraDistance -= time * 0.25f;
cameraDistance += currentGamePadState.Triggers.Left * time * 0.5f;
cameraDistance -= currentGamePadState.Triggers.Right * time * 0.5f;
// Limit the camera distance.
if (cameraDistance > 500.0f)
cameraDistance = 500.0f;
else if (cameraDistance < 10.0f)
cameraDistance = 10.0f;
if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed ||
currentKeyboardState.IsKeyDown(Keys.R))
{
cameraArc = 0;
cameraRotation = 0;
cameraDistance = 100;
}
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (SkinningSampleGame game = new SkinningSampleGame())
{
game.Run();
}
}
}
#endregion
}
| |
namespace Checkers
{
partial class NewGameDialog
{
/// <summary>
/// Disposes of the resources (other than memory) used by the <see cref="T:System.Windows.Forms.Form"/>.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if(disposing)
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(NewGameDialog));
this.imlGameType = new System.Windows.Forms.ImageList(this.components);
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.tabGame = new System.Windows.Forms.TabControl();
this.tabGame1P = new System.Windows.Forms.TabPage();
this.grpPlayerSettings1P = new System.Windows.Forms.GroupBox();
this.txtPlayerName1P = new System.Windows.Forms.TextBox();
this.lblPlayerName1P = new System.Windows.Forms.Label();
this.grpGameSettings1P = new System.Windows.Forms.GroupBox();
this.panImageSet1P = new System.Windows.Forms.Panel();
this.lblImage1P2 = new System.Windows.Forms.Label();
this.picPawn1P1 = new System.Windows.Forms.PictureBox();
this.picPawn1P2 = new System.Windows.Forms.PictureBox();
this.lblImage1P1 = new System.Windows.Forms.Label();
this.picImageSwap1P = new System.Windows.Forms.PictureBox();
this.picKing1P1 = new System.Windows.Forms.PictureBox();
this.picKing1P2 = new System.Windows.Forms.PictureBox();
this.lblFirstMove1P = new System.Windows.Forms.Label();
this.cmbFirstMove1P = new System.Windows.Forms.ComboBox();
this.cmbImageSet1P = new System.Windows.Forms.ComboBox();
this.lblImageSet1P = new System.Windows.Forms.Label();
this.lblGame1P = new System.Windows.Forms.Label();
this.cmbAgent1P = new System.Windows.Forms.ComboBox();
this.lblAgent1P = new System.Windows.Forms.Label();
this.tabGame2P = new System.Windows.Forms.TabPage();
this.grpPlayerSettings2P = new System.Windows.Forms.GroupBox();
this.txtPlayerName2P1 = new System.Windows.Forms.TextBox();
this.lblPlayerName2P1 = new System.Windows.Forms.Label();
this.lblPlayerName2P2 = new System.Windows.Forms.Label();
this.txtPlayerName2P2 = new System.Windows.Forms.TextBox();
this.grpGameSettings2P = new System.Windows.Forms.GroupBox();
this.panImageSet2P = new System.Windows.Forms.Panel();
this.picKing2P1 = new System.Windows.Forms.PictureBox();
this.picKing2P2 = new System.Windows.Forms.PictureBox();
this.lblImage2P2 = new System.Windows.Forms.Label();
this.picPawn2P1 = new System.Windows.Forms.PictureBox();
this.picPawn2P2 = new System.Windows.Forms.PictureBox();
this.lblImage2P1 = new System.Windows.Forms.Label();
this.picImageSwap2P = new System.Windows.Forms.PictureBox();
this.cmbImageSet2P = new System.Windows.Forms.ComboBox();
this.lblImageSet2P = new System.Windows.Forms.Label();
this.lblFirstMove2P = new System.Windows.Forms.Label();
this.cmbFirstMove2P = new System.Windows.Forms.ComboBox();
this.lblGame2P = new System.Windows.Forms.Label();
this.tabGameNet = new System.Windows.Forms.TabPage();
this.lblGameNet = new System.Windows.Forms.Label();
this.panNet = new System.Windows.Forms.Panel();
this.panGamesNet = new System.Windows.Forms.Panel();
this.lstGamesNet = new System.Windows.Forms.ListBox();
this.panConnectNet = new System.Windows.Forms.Panel();
this.txtRemoteHostNet = new System.Windows.Forms.TextBox();
this.lblRemoteHostNet = new System.Windows.Forms.Label();
this.lblGamesNet = new System.Windows.Forms.Label();
this.grpLocalInfoNet = new System.Windows.Forms.GroupBox();
this.lblIPAddress = new System.Windows.Forms.Label();
this.lnkIPAddress = new System.Windows.Forms.LinkLabel();
this.txtJoinNameNet = new System.Windows.Forms.TextBox();
this.lblJoinNameNet = new System.Windows.Forms.Label();
this.lblNetGameType = new System.Windows.Forms.Label();
this.cmbNetGameType = new System.Windows.Forms.ComboBox();
this.btnCreateNet = new System.Windows.Forms.Button();
this.btnJoinNet = new System.Windows.Forms.Button();
this.panNetSettings = new System.Windows.Forms.Panel();
this.txtGameNameNet = new System.Windows.Forms.TextBox();
this.btnBackNet = new System.Windows.Forms.Button();
this.lblPlayersNet = new System.Windows.Forms.Label();
this.lblChat = new System.Windows.Forms.Label();
this.lstPlayersNet = new System.Windows.Forms.ListView();
this.colName = new System.Windows.Forms.ColumnHeader();
this.colPosition = new System.Windows.Forms.ColumnHeader();
this.btnSend = new System.Windows.Forms.Button();
this.txtSend = new System.Windows.Forms.TextBox();
this.txtChat = new System.Windows.Forms.RichTextBox();
this.menuChat = new System.Windows.Forms.ContextMenu();
this.menuChatCopy = new System.Windows.Forms.MenuItem();
this.menuChatLine01 = new System.Windows.Forms.MenuItem();
this.menuChatClear = new System.Windows.Forms.MenuItem();
this.menuChatLine02 = new System.Windows.Forms.MenuItem();
this.menuChatSelectAll = new System.Windows.Forms.MenuItem();
this.grpPlayerSettingsNet = new System.Windows.Forms.GroupBox();
this.panImageSetNet = new System.Windows.Forms.Panel();
this.picKingNet1 = new System.Windows.Forms.PictureBox();
this.picKingNet2 = new System.Windows.Forms.PictureBox();
this.lblImageNet2 = new System.Windows.Forms.Label();
this.picPawnNet1 = new System.Windows.Forms.PictureBox();
this.picPawnNet2 = new System.Windows.Forms.PictureBox();
this.lblImageNet1 = new System.Windows.Forms.Label();
this.picImageSwapNet = new System.Windows.Forms.PictureBox();
this.lblFirstMoveNet = new System.Windows.Forms.Label();
this.chkLockImagesNet = new System.Windows.Forms.CheckBox();
this.txtFirstMoveNet = new System.Windows.Forms.TextBox();
this.cmbFirstMoveNet = new System.Windows.Forms.ComboBox();
this.txtPlayerNameNet = new System.Windows.Forms.TextBox();
this.imlImageSet = new System.Windows.Forms.ImageList(this.components);
this.menuImage = new System.Windows.Forms.ContextMenu();
this.menuImageDefault = new System.Windows.Forms.MenuItem();
this.menuImageLine = new System.Windows.Forms.MenuItem();
this.menuImagePreset = new System.Windows.Forms.MenuItem();
this.menuImagePresetsBuiltIn = new System.Windows.Forms.MenuItem();
this.menuImagePresetRed = new System.Windows.Forms.MenuItem();
this.menuImagePresetBlack = new System.Windows.Forms.MenuItem();
this.menuImagePresetWhite = new System.Windows.Forms.MenuItem();
this.menuImagePresetGold = new System.Windows.Forms.MenuItem();
this.menuImagePresetLine = new System.Windows.Forms.MenuItem();
this.menuImagePresetsNone = new System.Windows.Forms.MenuItem();
this.menuImageBrowse = new System.Windows.Forms.MenuItem();
this.menuImageChooseColor = new System.Windows.Forms.MenuItem();
this.dlgOpenImage = new System.Windows.Forms.OpenFileDialog();
this.dlgSelectColor = new System.Windows.Forms.ColorDialog();
this.imlKing = new System.Windows.Forms.ImageList(this.components);
this.tmrConnection = new System.Windows.Forms.Timer(this.components);
this.tabGame.SuspendLayout();
this.tabGame1P.SuspendLayout();
this.grpPlayerSettings1P.SuspendLayout();
this.grpGameSettings1P.SuspendLayout();
this.panImageSet1P.SuspendLayout();
this.tabGame2P.SuspendLayout();
this.grpPlayerSettings2P.SuspendLayout();
this.grpGameSettings2P.SuspendLayout();
this.panImageSet2P.SuspendLayout();
this.tabGameNet.SuspendLayout();
this.panNet.SuspendLayout();
this.panGamesNet.SuspendLayout();
this.panConnectNet.SuspendLayout();
this.grpLocalInfoNet.SuspendLayout();
this.panNetSettings.SuspendLayout();
this.grpPlayerSettingsNet.SuspendLayout();
this.panImageSetNet.SuspendLayout();
this.SuspendLayout();
//
// imlGameType
//
this.imlGameType.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imlGameType.ImageSize = new System.Drawing.Size(32, 32);
this.imlGameType.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imlGameType.ImageStream")));
this.imlGameType.TransparentColor = System.Drawing.Color.Transparent;
//
// btnCancel
//
this.btnCancel.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(512, 344);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(88, 36);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "&Cancel";
//
// btnOK
//
this.btnOK.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(416, 344);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(88, 36);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "&OK";
//
// tabGame
//
this.tabGame.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.tabGame.Appearance = System.Windows.Forms.TabAppearance.Buttons;
this.tabGame.Controls.AddRange(new System.Windows.Forms.Control[] {
this.tabGame1P,
this.tabGame2P,
this.tabGameNet});
this.tabGame.ImageList = this.imlGameType;
this.tabGame.ItemSize = new System.Drawing.Size(38, 38);
this.tabGame.Location = new System.Drawing.Point(4, 12);
this.tabGame.Name = "tabGame";
this.tabGame.SelectedIndex = 0;
this.tabGame.ShowToolTips = true;
this.tabGame.Size = new System.Drawing.Size(600, 324);
this.tabGame.SizeMode = System.Windows.Forms.TabSizeMode.Fixed;
this.tabGame.TabIndex = 1;
this.tabGame.TabStop = false;
this.tabGame.SelectedIndexChanged += new System.EventHandler(this.tabGame_SelectedIndexChanged);
//
// tabGame1P
//
this.tabGame1P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.grpPlayerSettings1P,
this.grpGameSettings1P,
this.lblGame1P,
this.cmbAgent1P,
this.lblAgent1P});
this.tabGame1P.ImageIndex = 0;
this.tabGame1P.Location = new System.Drawing.Point(4, 42);
this.tabGame1P.Name = "tabGame1P";
this.tabGame1P.Size = new System.Drawing.Size(592, 278);
this.tabGame1P.TabIndex = 0;
this.tabGame1P.ToolTipText = "Single Player Game";
//
// grpPlayerSettings1P
//
this.grpPlayerSettings1P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.txtPlayerName1P,
this.lblPlayerName1P});
this.grpPlayerSettings1P.Location = new System.Drawing.Point(280, 32);
this.grpPlayerSettings1P.Name = "grpPlayerSettings1P";
this.grpPlayerSettings1P.Size = new System.Drawing.Size(268, 72);
this.grpPlayerSettings1P.TabIndex = 2;
this.grpPlayerSettings1P.TabStop = false;
this.grpPlayerSettings1P.Text = "Player Settings";
//
// txtPlayerName1P
//
this.txtPlayerName1P.Location = new System.Drawing.Point(8, 44);
this.txtPlayerName1P.MaxLength = 128;
this.txtPlayerName1P.Name = "txtPlayerName1P";
this.txtPlayerName1P.Size = new System.Drawing.Size(252, 20);
this.txtPlayerName1P.TabIndex = 1;
this.txtPlayerName1P.Text = "Player";
//
// lblPlayerName1P
//
this.lblPlayerName1P.Location = new System.Drawing.Point(8, 24);
this.lblPlayerName1P.Name = "lblPlayerName1P";
this.lblPlayerName1P.Size = new System.Drawing.Size(252, 20);
this.lblPlayerName1P.TabIndex = 0;
this.lblPlayerName1P.Text = "Player Name:";
//
// grpGameSettings1P
//
this.grpGameSettings1P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panImageSet1P,
this.lblFirstMove1P,
this.cmbFirstMove1P,
this.cmbImageSet1P,
this.lblImageSet1P});
this.grpGameSettings1P.Location = new System.Drawing.Point(0, 32);
this.grpGameSettings1P.Name = "grpGameSettings1P";
this.grpGameSettings1P.Size = new System.Drawing.Size(268, 200);
this.grpGameSettings1P.TabIndex = 1;
this.grpGameSettings1P.TabStop = false;
this.grpGameSettings1P.Text = "Game Settings";
//
// panImageSet1P
//
this.panImageSet1P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lblImage1P2,
this.picPawn1P1,
this.picPawn1P2,
this.lblImage1P1,
this.picImageSwap1P,
this.picKing1P1,
this.picKing1P2});
this.panImageSet1P.Location = new System.Drawing.Point(8, 72);
this.panImageSet1P.Name = "panImageSet1P";
this.panImageSet1P.Size = new System.Drawing.Size(252, 92);
this.panImageSet1P.TabIndex = 6;
//
// lblImage1P2
//
this.lblImage1P2.Location = new System.Drawing.Point(168, 20);
this.lblImage1P2.Name = "lblImage1P2";
this.lblImage1P2.Size = new System.Drawing.Size(80, 20);
this.lblImage1P2.TabIndex = 1;
this.lblImage1P2.Text = "Opponent";
this.lblImage1P2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// picPawn1P1
//
this.picPawn1P1.BackColor = System.Drawing.Color.White;
this.picPawn1P1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picPawn1P1.Location = new System.Drawing.Point(88, 4);
this.picPawn1P1.Name = "picPawn1P1";
this.picPawn1P1.Size = new System.Drawing.Size(34, 34);
this.picPawn1P1.TabIndex = 11;
this.picPawn1P1.TabStop = false;
this.picPawn1P1.Click += new System.EventHandler(this.picImage_Click);
this.picPawn1P1.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picPawn1P1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// picPawn1P2
//
this.picPawn1P2.BackColor = System.Drawing.Color.White;
this.picPawn1P2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picPawn1P2.Location = new System.Drawing.Point(128, 4);
this.picPawn1P2.Name = "picPawn1P2";
this.picPawn1P2.Size = new System.Drawing.Size(34, 34);
this.picPawn1P2.TabIndex = 11;
this.picPawn1P2.TabStop = false;
this.picPawn1P2.Click += new System.EventHandler(this.picImage_Click);
this.picPawn1P2.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picPawn1P2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// lblImage1P1
//
this.lblImage1P1.Location = new System.Drawing.Point(4, 4);
this.lblImage1P1.Name = "lblImage1P1";
this.lblImage1P1.Size = new System.Drawing.Size(80, 20);
this.lblImage1P1.TabIndex = 0;
this.lblImage1P1.Text = "Player";
this.lblImage1P1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// picImageSwap1P
//
this.picImageSwap1P.Image = ((System.Drawing.Bitmap)(resources.GetObject("picImageSwap1P.Image")));
this.picImageSwap1P.Location = new System.Drawing.Point(92, 40);
this.picImageSwap1P.Name = "picImageSwap1P";
this.picImageSwap1P.Size = new System.Drawing.Size(65, 8);
this.picImageSwap1P.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.picImageSwap1P.TabIndex = 14;
this.picImageSwap1P.TabStop = false;
this.picImageSwap1P.Click += new System.EventHandler(this.picImageSwap1P_Click);
//
// picKing1P1
//
this.picKing1P1.BackColor = System.Drawing.Color.White;
this.picKing1P1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picKing1P1.Location = new System.Drawing.Point(88, 52);
this.picKing1P1.Name = "picKing1P1";
this.picKing1P1.Size = new System.Drawing.Size(34, 34);
this.picKing1P1.TabIndex = 11;
this.picKing1P1.TabStop = false;
this.picKing1P1.Visible = false;
this.picKing1P1.Click += new System.EventHandler(this.picImage_Click);
this.picKing1P1.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picKing1P1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// picKing1P2
//
this.picKing1P2.BackColor = System.Drawing.Color.White;
this.picKing1P2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picKing1P2.Location = new System.Drawing.Point(128, 52);
this.picKing1P2.Name = "picKing1P2";
this.picKing1P2.Size = new System.Drawing.Size(34, 34);
this.picKing1P2.TabIndex = 11;
this.picKing1P2.TabStop = false;
this.picKing1P2.Visible = false;
this.picKing1P2.Click += new System.EventHandler(this.picImage_Click);
this.picKing1P2.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picKing1P2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// lblFirstMove1P
//
this.lblFirstMove1P.Location = new System.Drawing.Point(8, 24);
this.lblFirstMove1P.Name = "lblFirstMove1P";
this.lblFirstMove1P.Size = new System.Drawing.Size(84, 20);
this.lblFirstMove1P.TabIndex = 0;
this.lblFirstMove1P.Text = "First Move:";
this.lblFirstMove1P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cmbFirstMove1P
//
this.cmbFirstMove1P.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbFirstMove1P.Items.AddRange(new object[] {
"Player",
"Computer"});
this.cmbFirstMove1P.Location = new System.Drawing.Point(96, 24);
this.cmbFirstMove1P.Name = "cmbFirstMove1P";
this.cmbFirstMove1P.Size = new System.Drawing.Size(164, 21);
this.cmbFirstMove1P.TabIndex = 1;
//
// cmbImageSet1P
//
this.cmbImageSet1P.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbImageSet1P.Items.AddRange(new object[] {
"Standard",
"Standard (Black)",
"Tournament",
"Custom"});
this.cmbImageSet1P.Location = new System.Drawing.Point(96, 48);
this.cmbImageSet1P.Name = "cmbImageSet1P";
this.cmbImageSet1P.Size = new System.Drawing.Size(164, 21);
this.cmbImageSet1P.TabIndex = 5;
this.cmbImageSet1P.SelectedIndexChanged += new System.EventHandler(this.cmbImageSet_SelectedIndexChanged);
//
// lblImageSet1P
//
this.lblImageSet1P.Location = new System.Drawing.Point(8, 48);
this.lblImageSet1P.Name = "lblImageSet1P";
this.lblImageSet1P.Size = new System.Drawing.Size(84, 20);
this.lblImageSet1P.TabIndex = 4;
this.lblImageSet1P.Text = "Image Set:";
this.lblImageSet1P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblGame1P
//
this.lblGame1P.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.lblGame1P.BackColor = System.Drawing.SystemColors.Info;
this.lblGame1P.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblGame1P.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblGame1P.Name = "lblGame1P";
this.lblGame1P.Size = new System.Drawing.Size(608, 20);
this.lblGame1P.TabIndex = 0;
this.lblGame1P.Text = "Single Player";
this.lblGame1P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cmbAgent1P
//
this.cmbAgent1P.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbAgent1P.Location = new System.Drawing.Point(280, 132);
this.cmbAgent1P.Name = "cmbAgent1P";
this.cmbAgent1P.Size = new System.Drawing.Size(252, 21);
this.cmbAgent1P.TabIndex = 1;
//
// lblAgent1P
//
this.lblAgent1P.Location = new System.Drawing.Point(280, 112);
this.lblAgent1P.Name = "lblAgent1P";
this.lblAgent1P.Size = new System.Drawing.Size(252, 20);
this.lblAgent1P.TabIndex = 0;
this.lblAgent1P.Text = "Difficulty:";
this.lblAgent1P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tabGame2P
//
this.tabGame2P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.grpPlayerSettings2P,
this.grpGameSettings2P,
this.lblGame2P});
this.tabGame2P.ImageIndex = 1;
this.tabGame2P.Location = new System.Drawing.Point(4, 42);
this.tabGame2P.Name = "tabGame2P";
this.tabGame2P.Size = new System.Drawing.Size(592, 278);
this.tabGame2P.TabIndex = 2;
this.tabGame2P.ToolTipText = "Multiplayer Game";
//
// grpPlayerSettings2P
//
this.grpPlayerSettings2P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.txtPlayerName2P1,
this.lblPlayerName2P1,
this.lblPlayerName2P2,
this.txtPlayerName2P2});
this.grpPlayerSettings2P.Location = new System.Drawing.Point(280, 32);
this.grpPlayerSettings2P.Name = "grpPlayerSettings2P";
this.grpPlayerSettings2P.Size = new System.Drawing.Size(268, 128);
this.grpPlayerSettings2P.TabIndex = 2;
this.grpPlayerSettings2P.TabStop = false;
this.grpPlayerSettings2P.Text = "Player Settings";
//
// txtPlayerName2P1
//
this.txtPlayerName2P1.Location = new System.Drawing.Point(8, 44);
this.txtPlayerName2P1.MaxLength = 128;
this.txtPlayerName2P1.Name = "txtPlayerName2P1";
this.txtPlayerName2P1.Size = new System.Drawing.Size(252, 20);
this.txtPlayerName2P1.TabIndex = 1;
this.txtPlayerName2P1.Text = "Player 1";
//
// lblPlayerName2P1
//
this.lblPlayerName2P1.Location = new System.Drawing.Point(8, 24);
this.lblPlayerName2P1.Name = "lblPlayerName2P1";
this.lblPlayerName2P1.Size = new System.Drawing.Size(252, 20);
this.lblPlayerName2P1.TabIndex = 0;
this.lblPlayerName2P1.Text = "Player 1 Name:";
//
// lblPlayerName2P2
//
this.lblPlayerName2P2.Location = new System.Drawing.Point(8, 76);
this.lblPlayerName2P2.Name = "lblPlayerName2P2";
this.lblPlayerName2P2.Size = new System.Drawing.Size(252, 20);
this.lblPlayerName2P2.TabIndex = 2;
this.lblPlayerName2P2.Text = "Player 2 Name:";
//
// txtPlayerName2P2
//
this.txtPlayerName2P2.Location = new System.Drawing.Point(8, 96);
this.txtPlayerName2P2.MaxLength = 128;
this.txtPlayerName2P2.Name = "txtPlayerName2P2";
this.txtPlayerName2P2.Size = new System.Drawing.Size(252, 20);
this.txtPlayerName2P2.TabIndex = 3;
this.txtPlayerName2P2.Text = "Player 2";
//
// grpGameSettings2P
//
this.grpGameSettings2P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panImageSet2P,
this.cmbImageSet2P,
this.lblImageSet2P,
this.lblFirstMove2P,
this.cmbFirstMove2P});
this.grpGameSettings2P.Location = new System.Drawing.Point(0, 32);
this.grpGameSettings2P.Name = "grpGameSettings2P";
this.grpGameSettings2P.Size = new System.Drawing.Size(268, 200);
this.grpGameSettings2P.TabIndex = 1;
this.grpGameSettings2P.TabStop = false;
this.grpGameSettings2P.Text = "Game Settings";
//
// panImageSet2P
//
this.panImageSet2P.Controls.AddRange(new System.Windows.Forms.Control[] {
this.picKing2P1,
this.picKing2P2,
this.lblImage2P2,
this.picPawn2P1,
this.picPawn2P2,
this.lblImage2P1,
this.picImageSwap2P});
this.panImageSet2P.Location = new System.Drawing.Point(8, 72);
this.panImageSet2P.Name = "panImageSet2P";
this.panImageSet2P.Size = new System.Drawing.Size(252, 92);
this.panImageSet2P.TabIndex = 6;
//
// picKing2P1
//
this.picKing2P1.BackColor = System.Drawing.Color.White;
this.picKing2P1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picKing2P1.Location = new System.Drawing.Point(88, 52);
this.picKing2P1.Name = "picKing2P1";
this.picKing2P1.Size = new System.Drawing.Size(34, 34);
this.picKing2P1.TabIndex = 16;
this.picKing2P1.TabStop = false;
this.picKing2P1.Visible = false;
this.picKing2P1.Click += new System.EventHandler(this.picImage_Click);
this.picKing2P1.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picKing2P1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// picKing2P2
//
this.picKing2P2.BackColor = System.Drawing.Color.White;
this.picKing2P2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picKing2P2.Location = new System.Drawing.Point(128, 52);
this.picKing2P2.Name = "picKing2P2";
this.picKing2P2.Size = new System.Drawing.Size(34, 34);
this.picKing2P2.TabIndex = 15;
this.picKing2P2.TabStop = false;
this.picKing2P2.Visible = false;
this.picKing2P2.Click += new System.EventHandler(this.picImage_Click);
this.picKing2P2.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picKing2P2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// lblImage2P2
//
this.lblImage2P2.Location = new System.Drawing.Point(168, 20);
this.lblImage2P2.Name = "lblImage2P2";
this.lblImage2P2.Size = new System.Drawing.Size(80, 20);
this.lblImage2P2.TabIndex = 1;
this.lblImage2P2.Text = "Player 2";
this.lblImage2P2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// picPawn2P1
//
this.picPawn2P1.BackColor = System.Drawing.Color.White;
this.picPawn2P1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picPawn2P1.Location = new System.Drawing.Point(88, 4);
this.picPawn2P1.Name = "picPawn2P1";
this.picPawn2P1.Size = new System.Drawing.Size(34, 34);
this.picPawn2P1.TabIndex = 11;
this.picPawn2P1.TabStop = false;
this.picPawn2P1.Click += new System.EventHandler(this.picImage_Click);
this.picPawn2P1.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picPawn2P1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// picPawn2P2
//
this.picPawn2P2.BackColor = System.Drawing.Color.White;
this.picPawn2P2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picPawn2P2.Location = new System.Drawing.Point(128, 4);
this.picPawn2P2.Name = "picPawn2P2";
this.picPawn2P2.Size = new System.Drawing.Size(34, 34);
this.picPawn2P2.TabIndex = 11;
this.picPawn2P2.TabStop = false;
this.picPawn2P2.Click += new System.EventHandler(this.picImage_Click);
this.picPawn2P2.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picPawn2P2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// lblImage2P1
//
this.lblImage2P1.Location = new System.Drawing.Point(4, 4);
this.lblImage2P1.Name = "lblImage2P1";
this.lblImage2P1.Size = new System.Drawing.Size(80, 20);
this.lblImage2P1.TabIndex = 0;
this.lblImage2P1.Text = "Player 1";
this.lblImage2P1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// picImageSwap2P
//
this.picImageSwap2P.Image = ((System.Drawing.Bitmap)(resources.GetObject("picImageSwap2P.Image")));
this.picImageSwap2P.Location = new System.Drawing.Point(92, 40);
this.picImageSwap2P.Name = "picImageSwap2P";
this.picImageSwap2P.Size = new System.Drawing.Size(65, 8);
this.picImageSwap2P.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.picImageSwap2P.TabIndex = 14;
this.picImageSwap2P.TabStop = false;
this.picImageSwap2P.Click += new System.EventHandler(this.picImageSwap2P_Click);
//
// cmbImageSet2P
//
this.cmbImageSet2P.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbImageSet2P.Items.AddRange(new object[] {
"Standard",
"Standard (Black)",
"Tournament",
"Custom"});
this.cmbImageSet2P.Location = new System.Drawing.Point(96, 48);
this.cmbImageSet2P.Name = "cmbImageSet2P";
this.cmbImageSet2P.Size = new System.Drawing.Size(164, 21);
this.cmbImageSet2P.TabIndex = 5;
this.cmbImageSet2P.SelectedIndexChanged += new System.EventHandler(this.cmbImageSet_SelectedIndexChanged);
//
// lblImageSet2P
//
this.lblImageSet2P.Location = new System.Drawing.Point(8, 48);
this.lblImageSet2P.Name = "lblImageSet2P";
this.lblImageSet2P.Size = new System.Drawing.Size(84, 20);
this.lblImageSet2P.TabIndex = 4;
this.lblImageSet2P.Text = "Image Set:";
this.lblImageSet2P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblFirstMove2P
//
this.lblFirstMove2P.Location = new System.Drawing.Point(8, 24);
this.lblFirstMove2P.Name = "lblFirstMove2P";
this.lblFirstMove2P.Size = new System.Drawing.Size(84, 20);
this.lblFirstMove2P.TabIndex = 0;
this.lblFirstMove2P.Text = "First Move:";
this.lblFirstMove2P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cmbFirstMove2P
//
this.cmbFirstMove2P.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbFirstMove2P.Items.AddRange(new object[] {
"Player 1",
"Player 2"});
this.cmbFirstMove2P.Location = new System.Drawing.Point(96, 24);
this.cmbFirstMove2P.Name = "cmbFirstMove2P";
this.cmbFirstMove2P.Size = new System.Drawing.Size(164, 21);
this.cmbFirstMove2P.TabIndex = 1;
//
// lblGame2P
//
this.lblGame2P.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.lblGame2P.BackColor = System.Drawing.SystemColors.Info;
this.lblGame2P.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblGame2P.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblGame2P.Name = "lblGame2P";
this.lblGame2P.Size = new System.Drawing.Size(592, 20);
this.lblGame2P.TabIndex = 0;
this.lblGame2P.Text = "Multiplayer";
this.lblGame2P.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// tabGameNet
//
this.tabGameNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lblGameNet,
this.panNet,
this.panNetSettings});
this.tabGameNet.ImageIndex = 2;
this.tabGameNet.Location = new System.Drawing.Point(4, 42);
this.tabGameNet.Name = "tabGameNet";
this.tabGameNet.Size = new System.Drawing.Size(592, 278);
this.tabGameNet.TabIndex = 3;
this.tabGameNet.ToolTipText = "Net Game";
//
// lblGameNet
//
this.lblGameNet.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.lblGameNet.BackColor = System.Drawing.SystemColors.Info;
this.lblGameNet.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblGameNet.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblGameNet.Name = "lblGameNet";
this.lblGameNet.Size = new System.Drawing.Size(592, 20);
this.lblGameNet.TabIndex = 0;
this.lblGameNet.Text = "Net Game";
this.lblGameNet.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// panNet
//
this.panNet.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.panNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panGamesNet,
this.grpLocalInfoNet,
this.lblNetGameType,
this.cmbNetGameType,
this.btnCreateNet,
this.btnJoinNet});
this.panNet.Location = new System.Drawing.Point(0, 20);
this.panNet.Name = "panNet";
this.panNet.Size = new System.Drawing.Size(592, 260);
this.panNet.TabIndex = 1;
this.panNet.Enter += new System.EventHandler(this.panNet_Enter);
this.panNet.Leave += new System.EventHandler(this.panNet_Leave);
//
// panGamesNet
//
this.panGamesNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lstGamesNet,
this.panConnectNet,
this.lblGamesNet});
this.panGamesNet.Location = new System.Drawing.Point(0, 60);
this.panGamesNet.Name = "panGamesNet";
this.panGamesNet.Size = new System.Drawing.Size(296, 136);
this.panGamesNet.TabIndex = 2;
//
// lstGamesNet
//
this.lstGamesNet.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstGamesNet.IntegralHeight = false;
this.lstGamesNet.Location = new System.Drawing.Point(0, 16);
this.lstGamesNet.Name = "lstGamesNet";
this.lstGamesNet.Size = new System.Drawing.Size(296, 76);
this.lstGamesNet.TabIndex = 1;
this.lstGamesNet.SelectedIndexChanged += new System.EventHandler(this.lstGamesNet_SelectedIndexChanged);
//
// panConnectNet
//
this.panConnectNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.txtRemoteHostNet,
this.lblRemoteHostNet});
this.panConnectNet.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panConnectNet.Location = new System.Drawing.Point(0, 92);
this.panConnectNet.Name = "panConnectNet";
this.panConnectNet.Size = new System.Drawing.Size(296, 44);
this.panConnectNet.TabIndex = 2;
this.panConnectNet.Visible = false;
//
// txtRemoteHostNet
//
this.txtRemoteHostNet.Location = new System.Drawing.Point(0, 24);
this.txtRemoteHostNet.Name = "txtRemoteHostNet";
this.txtRemoteHostNet.Size = new System.Drawing.Size(296, 20);
this.txtRemoteHostNet.TabIndex = 1;
this.txtRemoteHostNet.Text = "";
this.txtRemoteHostNet.TextChanged += new System.EventHandler(this.txtRemoteHostNet_TextChanged);
//
// lblRemoteHostNet
//
this.lblRemoteHostNet.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.lblRemoteHostNet.Location = new System.Drawing.Point(0, 8);
this.lblRemoteHostNet.Name = "lblRemoteHostNet";
this.lblRemoteHostNet.Size = new System.Drawing.Size(296, 16);
this.lblRemoteHostNet.TabIndex = 0;
this.lblRemoteHostNet.Text = "Remote Host:";
//
// lblGamesNet
//
this.lblGamesNet.Dock = System.Windows.Forms.DockStyle.Top;
this.lblGamesNet.Name = "lblGamesNet";
this.lblGamesNet.Size = new System.Drawing.Size(296, 16);
this.lblGamesNet.TabIndex = 0;
this.lblGamesNet.Text = "Games:";
//
// grpLocalInfoNet
//
this.grpLocalInfoNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lblIPAddress,
this.lnkIPAddress,
this.txtJoinNameNet,
this.lblJoinNameNet});
this.grpLocalInfoNet.Location = new System.Drawing.Point(308, 12);
this.grpLocalInfoNet.Name = "grpLocalInfoNet";
this.grpLocalInfoNet.Size = new System.Drawing.Size(240, 116);
this.grpLocalInfoNet.TabIndex = 5;
this.grpLocalInfoNet.TabStop = false;
this.grpLocalInfoNet.Text = "Local Information";
//
// lblIPAddress
//
this.lblIPAddress.Location = new System.Drawing.Point(12, 24);
this.lblIPAddress.Name = "lblIPAddress";
this.lblIPAddress.Size = new System.Drawing.Size(68, 16);
this.lblIPAddress.TabIndex = 0;
this.lblIPAddress.Text = "IP Address:";
//
// lnkIPAddress
//
this.lnkIPAddress.ActiveLinkColor = System.Drawing.Color.Blue;
this.lnkIPAddress.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lnkIPAddress.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.lnkIPAddress.LinkColor = System.Drawing.SystemColors.WindowText;
this.lnkIPAddress.Location = new System.Drawing.Point(84, 24);
this.lnkIPAddress.Name = "lnkIPAddress";
this.lnkIPAddress.Size = new System.Drawing.Size(148, 16);
this.lnkIPAddress.TabIndex = 1;
this.lnkIPAddress.TabStop = true;
this.lnkIPAddress.Text = "x.x.x.x";
this.lnkIPAddress.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lnkIPAddress.VisitedLinkColor = System.Drawing.SystemColors.WindowText;
this.lnkIPAddress.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkIPAddress_LinkClicked);
//
// txtJoinNameNet
//
this.txtJoinNameNet.Location = new System.Drawing.Point(84, 48);
this.txtJoinNameNet.MaxLength = 128;
this.txtJoinNameNet.Name = "txtJoinNameNet";
this.txtJoinNameNet.Size = new System.Drawing.Size(148, 20);
this.txtJoinNameNet.TabIndex = 3;
this.txtJoinNameNet.Text = "";
//
// lblJoinNameNet
//
this.lblJoinNameNet.Location = new System.Drawing.Point(12, 48);
this.lblJoinNameNet.Name = "lblJoinNameNet";
this.lblJoinNameNet.Size = new System.Drawing.Size(68, 20);
this.lblJoinNameNet.TabIndex = 2;
this.lblJoinNameNet.Text = "Name:";
this.lblJoinNameNet.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblNetGameType
//
this.lblNetGameType.Location = new System.Drawing.Point(0, 12);
this.lblNetGameType.Name = "lblNetGameType";
this.lblNetGameType.Size = new System.Drawing.Size(296, 16);
this.lblNetGameType.TabIndex = 0;
this.lblNetGameType.Text = "Game Type (Protocol):";
//
// cmbNetGameType
//
this.cmbNetGameType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbNetGameType.Items.AddRange(new object[] {
"Internet TCP/IP Connection",
"Local (LAN) TCP/IP Connection"});
this.cmbNetGameType.Location = new System.Drawing.Point(0, 28);
this.cmbNetGameType.Name = "cmbNetGameType";
this.cmbNetGameType.Size = new System.Drawing.Size(296, 21);
this.cmbNetGameType.TabIndex = 1;
this.cmbNetGameType.SelectedIndexChanged += new System.EventHandler(this.cmbNetGameType_SelectedIndexChanged);
//
// btnCreateNet
//
this.btnCreateNet.Location = new System.Drawing.Point(100, 204);
this.btnCreateNet.Name = "btnCreateNet";
this.btnCreateNet.Size = new System.Drawing.Size(96, 32);
this.btnCreateNet.TabIndex = 3;
this.btnCreateNet.Text = "&Create";
this.btnCreateNet.Click += new System.EventHandler(this.btnCreateNet_Click);
//
// btnJoinNet
//
this.btnJoinNet.Enabled = false;
this.btnJoinNet.Location = new System.Drawing.Point(200, 204);
this.btnJoinNet.Name = "btnJoinNet";
this.btnJoinNet.Size = new System.Drawing.Size(96, 32);
this.btnJoinNet.TabIndex = 4;
this.btnJoinNet.Text = "&Join";
this.btnJoinNet.Click += new System.EventHandler(this.btnJoinNet_Click);
//
// panNetSettings
//
this.panNetSettings.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.panNetSettings.Controls.AddRange(new System.Windows.Forms.Control[] {
this.txtGameNameNet,
this.btnBackNet,
this.lblPlayersNet,
this.lblChat,
this.lstPlayersNet,
this.btnSend,
this.txtSend,
this.txtChat,
this.grpPlayerSettingsNet,
this.txtPlayerNameNet});
this.panNetSettings.Location = new System.Drawing.Point(0, 20);
this.panNetSettings.Name = "panNetSettings";
this.panNetSettings.Size = new System.Drawing.Size(592, 260);
this.panNetSettings.TabIndex = 9;
this.panNetSettings.Enter += new System.EventHandler(this.panNetSettings_Enter);
this.panNetSettings.Leave += new System.EventHandler(this.panNetSettings_Leave);
//
// txtGameNameNet
//
this.txtGameNameNet.BackColor = System.Drawing.SystemColors.Info;
this.txtGameNameNet.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtGameNameNet.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtGameNameNet.Location = new System.Drawing.Point(0, 8);
this.txtGameNameNet.Name = "txtGameNameNet";
this.txtGameNameNet.ReadOnly = true;
this.txtGameNameNet.Size = new System.Drawing.Size(288, 20);
this.txtGameNameNet.TabIndex = 9;
this.txtGameNameNet.Text = "";
this.txtGameNameNet.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// btnBackNet
//
this.btnBackNet.Location = new System.Drawing.Point(504, 220);
this.btnBackNet.Name = "btnBackNet";
this.btnBackNet.Size = new System.Drawing.Size(88, 36);
this.btnBackNet.TabIndex = 7;
this.btnBackNet.Text = "&Back";
this.btnBackNet.Click += new System.EventHandler(this.btnBackNet_Click);
//
// lblPlayersNet
//
this.lblPlayersNet.Location = new System.Drawing.Point(0, 36);
this.lblPlayersNet.Name = "lblPlayersNet";
this.lblPlayersNet.Size = new System.Drawing.Size(288, 16);
this.lblPlayersNet.TabIndex = 0;
this.lblPlayersNet.Text = "Connected Players:";
//
// lblChat
//
this.lblChat.Location = new System.Drawing.Point(0, 140);
this.lblChat.Name = "lblChat";
this.lblChat.Size = new System.Drawing.Size(288, 16);
this.lblChat.TabIndex = 2;
this.lblChat.Text = "Discussion:";
//
// lstPlayersNet
//
this.lstPlayersNet.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colName,
this.colPosition});
this.lstPlayersNet.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lstPlayersNet.Location = new System.Drawing.Point(0, 52);
this.lstPlayersNet.Name = "lstPlayersNet";
this.lstPlayersNet.Size = new System.Drawing.Size(288, 80);
this.lstPlayersNet.TabIndex = 1;
this.lstPlayersNet.View = System.Windows.Forms.View.Details;
this.lstPlayersNet.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lstPlayersNet_ItemCheck);
//
// colName
//
this.colName.Text = "Player";
this.colName.Width = 120;
//
// colPosition
//
this.colPosition.Text = "Position";
this.colPosition.Width = 120;
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(244, 236);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(44, 20);
this.btnSend.TabIndex = 5;
this.btnSend.Text = "&Send";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// txtSend
//
this.txtSend.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtSend.Location = new System.Drawing.Point(0, 236);
this.txtSend.Name = "txtSend";
this.txtSend.Size = new System.Drawing.Size(240, 21);
this.txtSend.TabIndex = 4;
this.txtSend.Text = "";
this.txtSend.Leave += new System.EventHandler(this.txtSend_Leave);
this.txtSend.Enter += new System.EventHandler(this.txtSend_Enter);
//
// txtChat
//
this.txtChat.ContextMenu = this.menuChat;
this.txtChat.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtChat.Location = new System.Drawing.Point(0, 156);
this.txtChat.Name = "txtChat";
this.txtChat.ReadOnly = true;
this.txtChat.Size = new System.Drawing.Size(288, 76);
this.txtChat.TabIndex = 3;
this.txtChat.Text = "";
//
// menuChat
//
this.menuChat.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuChatCopy,
this.menuChatLine01,
this.menuChatClear,
this.menuChatLine02,
this.menuChatSelectAll});
this.menuChat.Popup += new System.EventHandler(this.menuChat_Popup);
//
// menuChatCopy
//
this.menuChatCopy.Index = 0;
this.menuChatCopy.Text = "&Copy";
this.menuChatCopy.Click += new System.EventHandler(this.menuChatCopy_Click);
//
// menuChatLine01
//
this.menuChatLine01.Index = 1;
this.menuChatLine01.Text = "-";
//
// menuChatClear
//
this.menuChatClear.Index = 2;
this.menuChatClear.Text = "&Clear Window";
this.menuChatClear.Click += new System.EventHandler(this.menuChatClear_Click);
//
// menuChatLine02
//
this.menuChatLine02.Index = 3;
this.menuChatLine02.Text = "-";
//
// menuChatSelectAll
//
this.menuChatSelectAll.Index = 4;
this.menuChatSelectAll.Text = "Select &All";
this.menuChatSelectAll.Click += new System.EventHandler(this.menuChatSelectAll_Click);
//
// grpPlayerSettingsNet
//
this.grpPlayerSettingsNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.panImageSetNet,
this.lblFirstMoveNet,
this.chkLockImagesNet,
this.txtFirstMoveNet,
this.cmbFirstMoveNet});
this.grpPlayerSettingsNet.Location = new System.Drawing.Point(304, 36);
this.grpPlayerSettingsNet.Name = "grpPlayerSettingsNet";
this.grpPlayerSettingsNet.Size = new System.Drawing.Size(288, 176);
this.grpPlayerSettingsNet.TabIndex = 6;
this.grpPlayerSettingsNet.TabStop = false;
this.grpPlayerSettingsNet.Text = "Game Settings";
//
// panImageSetNet
//
this.panImageSetNet.Controls.AddRange(new System.Windows.Forms.Control[] {
this.picKingNet1,
this.picKingNet2,
this.lblImageNet2,
this.picPawnNet1,
this.picPawnNet2,
this.lblImageNet1,
this.picImageSwapNet});
this.panImageSetNet.Location = new System.Drawing.Point(8, 52);
this.panImageSetNet.Name = "panImageSetNet";
this.panImageSetNet.Size = new System.Drawing.Size(248, 92);
this.panImageSetNet.TabIndex = 3;
//
// picKingNet1
//
this.picKingNet1.BackColor = System.Drawing.Color.White;
this.picKingNet1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picKingNet1.Location = new System.Drawing.Point(88, 52);
this.picKingNet1.Name = "picKingNet1";
this.picKingNet1.Size = new System.Drawing.Size(34, 34);
this.picKingNet1.TabIndex = 18;
this.picKingNet1.TabStop = false;
this.picKingNet1.Click += new System.EventHandler(this.picImage_Click);
this.picKingNet1.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picKingNet1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// picKingNet2
//
this.picKingNet2.BackColor = System.Drawing.Color.White;
this.picKingNet2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picKingNet2.Location = new System.Drawing.Point(128, 52);
this.picKingNet2.Name = "picKingNet2";
this.picKingNet2.Size = new System.Drawing.Size(34, 34);
this.picKingNet2.TabIndex = 17;
this.picKingNet2.TabStop = false;
this.picKingNet2.Click += new System.EventHandler(this.picImage_Click);
this.picKingNet2.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picKingNet2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// lblImageNet2
//
this.lblImageNet2.Location = new System.Drawing.Point(168, 20);
this.lblImageNet2.Name = "lblImageNet2";
this.lblImageNet2.Size = new System.Drawing.Size(80, 20);
this.lblImageNet2.TabIndex = 1;
this.lblImageNet2.Text = "Opponent";
this.lblImageNet2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// picPawnNet1
//
this.picPawnNet1.BackColor = System.Drawing.Color.White;
this.picPawnNet1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picPawnNet1.Location = new System.Drawing.Point(88, 4);
this.picPawnNet1.Name = "picPawnNet1";
this.picPawnNet1.Size = new System.Drawing.Size(34, 34);
this.picPawnNet1.TabIndex = 11;
this.picPawnNet1.TabStop = false;
this.picPawnNet1.Click += new System.EventHandler(this.picImage_Click);
this.picPawnNet1.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picPawnNet1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// picPawnNet2
//
this.picPawnNet2.BackColor = System.Drawing.Color.White;
this.picPawnNet2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picPawnNet2.Location = new System.Drawing.Point(128, 4);
this.picPawnNet2.Name = "picPawnNet2";
this.picPawnNet2.Size = new System.Drawing.Size(34, 34);
this.picPawnNet2.TabIndex = 11;
this.picPawnNet2.TabStop = false;
this.picPawnNet2.Click += new System.EventHandler(this.picImage_Click);
this.picPawnNet2.EnabledChanged += new System.EventHandler(this.picImage_EnabledChanged);
this.picPawnNet2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picImage_MouseDown);
//
// lblImageNet1
//
this.lblImageNet1.Location = new System.Drawing.Point(4, 4);
this.lblImageNet1.Name = "lblImageNet1";
this.lblImageNet1.Size = new System.Drawing.Size(80, 20);
this.lblImageNet1.TabIndex = 0;
this.lblImageNet1.Text = "Player";
this.lblImageNet1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// picImageSwapNet
//
this.picImageSwapNet.Image = ((System.Drawing.Bitmap)(resources.GetObject("picImageSwapNet.Image")));
this.picImageSwapNet.Location = new System.Drawing.Point(92, 40);
this.picImageSwapNet.Name = "picImageSwapNet";
this.picImageSwapNet.Size = new System.Drawing.Size(65, 8);
this.picImageSwapNet.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.picImageSwapNet.TabIndex = 14;
this.picImageSwapNet.TabStop = false;
this.picImageSwapNet.Click += new System.EventHandler(this.picImageSwapNet_Click);
//
// lblFirstMoveNet
//
this.lblFirstMoveNet.Location = new System.Drawing.Point(8, 24);
this.lblFirstMoveNet.Name = "lblFirstMoveNet";
this.lblFirstMoveNet.Size = new System.Drawing.Size(84, 20);
this.lblFirstMoveNet.TabIndex = 0;
this.lblFirstMoveNet.Text = "First Move:";
this.lblFirstMoveNet.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// chkLockImagesNet
//
this.chkLockImagesNet.Location = new System.Drawing.Point(8, 152);
this.chkLockImagesNet.Name = "chkLockImagesNet";
this.chkLockImagesNet.Size = new System.Drawing.Size(252, 16);
this.chkLockImagesNet.TabIndex = 4;
this.chkLockImagesNet.Text = "Lock Images";
this.chkLockImagesNet.Visible = false;
this.chkLockImagesNet.CheckedChanged += new System.EventHandler(this.chkLockImagesNet_CheckedChanged);
//
// txtFirstMoveNet
//
this.txtFirstMoveNet.Location = new System.Drawing.Point(96, 24);
this.txtFirstMoveNet.Name = "txtFirstMoveNet";
this.txtFirstMoveNet.ReadOnly = true;
this.txtFirstMoveNet.Size = new System.Drawing.Size(160, 20);
this.txtFirstMoveNet.TabIndex = 1;
this.txtFirstMoveNet.Text = "";
this.txtFirstMoveNet.Visible = false;
//
// cmbFirstMoveNet
//
this.cmbFirstMoveNet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbFirstMoveNet.Items.AddRange(new object[] {
"Host",
"Opponent"});
this.cmbFirstMoveNet.Location = new System.Drawing.Point(96, 24);
this.cmbFirstMoveNet.Name = "cmbFirstMoveNet";
this.cmbFirstMoveNet.Size = new System.Drawing.Size(160, 21);
this.cmbFirstMoveNet.TabIndex = 2;
this.cmbFirstMoveNet.Visible = false;
this.cmbFirstMoveNet.SelectedIndexChanged += new System.EventHandler(this.cmbFirstMoveNet_SelectedIndexChanged);
//
// txtPlayerNameNet
//
this.txtPlayerNameNet.BackColor = System.Drawing.SystemColors.Window;
this.txtPlayerNameNet.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtPlayerNameNet.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtPlayerNameNet.Location = new System.Drawing.Point(304, 8);
this.txtPlayerNameNet.MaxLength = 128;
this.txtPlayerNameNet.Name = "txtPlayerNameNet";
this.txtPlayerNameNet.ReadOnly = true;
this.txtPlayerNameNet.Size = new System.Drawing.Size(288, 20);
this.txtPlayerNameNet.TabIndex = 1;
this.txtPlayerNameNet.Text = "";
this.txtPlayerNameNet.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// imlImageSet
//
this.imlImageSet.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imlImageSet.ImageSize = new System.Drawing.Size(32, 32);
this.imlImageSet.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imlImageSet.ImageStream")));
this.imlImageSet.TransparentColor = System.Drawing.Color.Transparent;
//
// menuImage
//
this.menuImage.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuImageDefault,
this.menuImageLine,
this.menuImagePreset,
this.menuImageBrowse,
this.menuImageChooseColor});
this.menuImage.Popup += new System.EventHandler(this.menuImage_Popup);
//
// menuImageDefault
//
this.menuImageDefault.Index = 0;
this.menuImageDefault.Text = "&Default Image";
this.menuImageDefault.Click += new System.EventHandler(this.menuImageDefault_Click);
//
// menuImageLine
//
this.menuImageLine.Index = 1;
this.menuImageLine.Text = "-";
//
// menuImagePreset
//
this.menuImagePreset.Index = 2;
this.menuImagePreset.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuImagePresetsBuiltIn,
this.menuImagePresetLine,
this.menuImagePresetsNone});
this.menuImagePreset.Text = "&Preset Image";
//
// menuImagePresetsBuiltIn
//
this.menuImagePresetsBuiltIn.Index = 0;
this.menuImagePresetsBuiltIn.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuImagePresetRed,
this.menuImagePresetBlack,
this.menuImagePresetWhite,
this.menuImagePresetGold});
this.menuImagePresetsBuiltIn.Text = "&Built-in";
//
// menuImagePresetRed
//
this.menuImagePresetRed.Index = 0;
this.menuImagePresetRed.Text = "&Red Set";
this.menuImagePresetRed.Click += new System.EventHandler(this.menuImagePresetRed_Click);
//
// menuImagePresetBlack
//
this.menuImagePresetBlack.Index = 1;
this.menuImagePresetBlack.Text = "&Black Set";
this.menuImagePresetBlack.Click += new System.EventHandler(this.menuImagePresetBlack_Click);
//
// menuImagePresetWhite
//
this.menuImagePresetWhite.Index = 2;
this.menuImagePresetWhite.Text = "&White Set";
this.menuImagePresetWhite.Click += new System.EventHandler(this.menuImagePresetWhite_Click);
//
// menuImagePresetGold
//
this.menuImagePresetGold.Index = 3;
this.menuImagePresetGold.Text = "&Gold Set";
this.menuImagePresetGold.Click += new System.EventHandler(this.menuImagePresetGold_Click);
//
// menuImagePresetLine
//
this.menuImagePresetLine.Index = 1;
this.menuImagePresetLine.Text = "-";
//
// menuImagePresetsNone
//
this.menuImagePresetsNone.Enabled = false;
this.menuImagePresetsNone.Index = 2;
this.menuImagePresetsNone.Text = "(No Presets)";
//
// menuImageBrowse
//
this.menuImageBrowse.Index = 3;
this.menuImageBrowse.Text = "&Browse for Image...";
this.menuImageBrowse.Click += new System.EventHandler(this.menuImageBrowse_Click);
//
// menuImageChooseColor
//
this.menuImageChooseColor.Index = 4;
this.menuImageChooseColor.Text = "&Choose Color...";
this.menuImageChooseColor.Click += new System.EventHandler(this.menuImageChooseColor_Click);
//
// dlgOpenImage
//
this.dlgOpenImage.Filter = "Supported Image Files (*.bmp;*.gif;*.jpg;*.jpeg;*.tiff;*.png)|*.bmp;*.gif;*.jpg;*" +
".jpeg;*.tiff;*.png|All Files (*.*)|*.*";
this.dlgOpenImage.Title = "Open Custom Image";
//
// dlgSelectColor
//
this.dlgSelectColor.AnyColor = true;
this.dlgSelectColor.FullOpen = true;
//
// imlKing
//
this.imlKing.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imlKing.ImageSize = new System.Drawing.Size(32, 32);
this.imlKing.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imlKing.ImageStream")));
this.imlKing.TransparentColor = System.Drawing.Color.Transparent;
//
// tmrConnection
//
this.tmrConnection.Interval = 10;
this.tmrConnection.Tick += new System.EventHandler(this.tmrConnection_Tick);
//
// frmNewGame
//
this.AcceptButton = this.btnOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(606, 387);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnCancel,
this.btnOK,
this.tabGame});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "frmNewGame";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "New Checkers Game";
this.Closing += new System.ComponentModel.CancelEventHandler(this.frmNewGame_Closing);
this.Load += new System.EventHandler(this.frmNewGame_Load);
this.Activated += new System.EventHandler(this.frmNewGame_Activated);
this.tabGame.ResumeLayout(false);
this.tabGame1P.ResumeLayout(false);
this.grpPlayerSettings1P.ResumeLayout(false);
this.grpGameSettings1P.ResumeLayout(false);
this.panImageSet1P.ResumeLayout(false);
this.tabGame2P.ResumeLayout(false);
this.grpPlayerSettings2P.ResumeLayout(false);
this.grpGameSettings2P.ResumeLayout(false);
this.panImageSet2P.ResumeLayout(false);
this.tabGameNet.ResumeLayout(false);
this.panNet.ResumeLayout(false);
this.panGamesNet.ResumeLayout(false);
this.panConnectNet.ResumeLayout(false);
this.grpLocalInfoNet.ResumeLayout(false);
this.panNetSettings.ResumeLayout(false);
this.grpPlayerSettingsNet.ResumeLayout(false);
this.panImageSetNet.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
private System.Windows.Forms.ImageList imlGameType;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.TabControl tabGame;
private System.Windows.Forms.TabPage tabGame1P;
private System.Windows.Forms.TabPage tabGame2P;
private System.Windows.Forms.TabPage tabGameNet;
private System.Windows.Forms.Label lblGame1P;
private System.Windows.Forms.Label lblGame2P;
private System.Windows.Forms.Label lblGameNet;
private System.Windows.Forms.ComboBox cmbFirstMove2P;
private System.Windows.Forms.Label lblFirstMove2P;
private System.Windows.Forms.Panel panNetSettings;
private System.Windows.Forms.Panel panNet;
private System.Windows.Forms.RichTextBox txtChat;
private System.Windows.Forms.TextBox txtSend;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.ComboBox cmbNetGameType;
private System.Windows.Forms.GroupBox grpGameSettings1P;
private System.Windows.Forms.GroupBox grpGameSettings2P;
private System.Windows.Forms.GroupBox grpPlayerSettingsNet;
private System.Windows.Forms.Label lblFirstMoveNet;
private System.Windows.Forms.ComboBox cmbFirstMoveNet;
private System.Windows.Forms.ListView lstPlayersNet;
private System.Windows.Forms.Label lblChat;
private System.Windows.Forms.Label lblPlayersNet;
private System.Windows.Forms.Label lblNetGameType;
private System.Windows.Forms.GroupBox grpLocalInfoNet;
private System.Windows.Forms.LinkLabel lnkIPAddress;
private System.Windows.Forms.Label lblIPAddress;
private System.Windows.Forms.ComboBox cmbImageSet2P;
private System.Windows.Forms.Label lblImageSet2P;
private System.Windows.Forms.ComboBox cmbImageSet1P;
private System.Windows.Forms.Label lblImageSet1P;
private System.Windows.Forms.Label lblFirstMove1P;
private System.Windows.Forms.ComboBox cmbFirstMove1P;
private System.Windows.Forms.ColumnHeader colName;
private System.Windows.Forms.ColumnHeader colPosition;
private System.Windows.Forms.ImageList imlImageSet;
private System.Windows.Forms.Label lblImage1P1;
private System.Windows.Forms.ContextMenu menuImage;
private System.Windows.Forms.MenuItem menuImageBrowse;
private System.Windows.Forms.MenuItem menuImageChooseColor;
private System.Windows.Forms.OpenFileDialog dlgOpenImage;
private System.Windows.Forms.ColorDialog dlgSelectColor;
private System.Windows.Forms.Panel panImageSet1P;
private System.Windows.Forms.Label lblImage1P2;
private System.Windows.Forms.Panel panImageSet2P;
private System.Windows.Forms.PictureBox picImageSwap1P;
private System.Windows.Forms.Label lblImage2P2;
private System.Windows.Forms.Label lblImage2P1;
private System.Windows.Forms.PictureBox picImageSwap2P;
private System.Windows.Forms.Panel panImageSetNet;
private System.Windows.Forms.PictureBox picImageSwapNet;
private System.Windows.Forms.ImageList imlKing;
private System.Windows.Forms.Label lblImageNet2;
private System.Windows.Forms.Label lblImageNet1;
private System.Windows.Forms.PictureBox picPawn1P1;
private System.Windows.Forms.PictureBox picPawn1P2;
private System.Windows.Forms.PictureBox picKing1P1;
private System.Windows.Forms.PictureBox picKing1P2;
private System.Windows.Forms.PictureBox picPawn2P1;
private System.Windows.Forms.PictureBox picPawn2P2;
private System.Windows.Forms.PictureBox picPawnNet1;
private System.Windows.Forms.PictureBox picPawnNet2;
private System.Windows.Forms.PictureBox picKing2P1;
private System.Windows.Forms.PictureBox picKing2P2;
private System.Windows.Forms.PictureBox picKingNet1;
private System.Windows.Forms.PictureBox picKingNet2;
private System.Windows.Forms.MenuItem menuImageDefault;
private System.Windows.Forms.MenuItem menuImageLine;
private System.Windows.Forms.GroupBox grpPlayerSettings1P;
private System.Windows.Forms.GroupBox grpPlayerSettings2P;
private System.Windows.Forms.Label lblPlayerName1P;
private System.Windows.Forms.Label lblPlayerName2P1;
private System.Windows.Forms.Label lblPlayerName2P2;
private System.Windows.Forms.TextBox txtPlayerName1P;
private System.Windows.Forms.TextBox txtPlayerName2P1;
private System.Windows.Forms.TextBox txtPlayerName2P2;
private System.Windows.Forms.MenuItem menuImagePreset;
private System.Windows.Forms.MenuItem menuImagePresetRed;
private System.Windows.Forms.MenuItem menuImagePresetBlack;
private System.Windows.Forms.MenuItem menuImagePresetWhite;
private System.Windows.Forms.MenuItem menuImagePresetGold;
private System.Windows.Forms.MenuItem menuImagePresetLine;
private System.Windows.Forms.MenuItem menuImagePresetsNone;
private System.Windows.Forms.Button btnBackNet;
private System.Windows.Forms.Label lblGamesNet;
private System.Windows.Forms.ListBox lstGamesNet;
private System.Windows.Forms.Panel panConnectNet;
private System.Windows.Forms.TextBox txtRemoteHostNet;
private System.Windows.Forms.Label lblRemoteHostNet;
private System.Windows.Forms.Button btnCreateNet;
private System.Windows.Forms.Button btnJoinNet;
private System.Windows.Forms.Panel panGamesNet;
private System.Windows.Forms.Timer tmrConnection;
private System.Windows.Forms.TextBox txtJoinNameNet;
private System.Windows.Forms.Label lblJoinNameNet;
private System.Windows.Forms.TextBox txtGameNameNet;
private System.Windows.Forms.TextBox txtPlayerNameNet;
private System.Windows.Forms.TextBox txtFirstMoveNet;
private System.Windows.Forms.CheckBox chkLockImagesNet;
private System.Windows.Forms.ContextMenu menuChat;
private System.Windows.Forms.MenuItem menuChatCopy;
private System.Windows.Forms.MenuItem menuChatSelectAll;
private System.Windows.Forms.MenuItem menuChatLine01;
private System.Windows.Forms.MenuItem menuChatClear;
private System.Windows.Forms.MenuItem menuChatLine02;
private System.Windows.Forms.MenuItem menuImagePresetsBuiltIn;
private System.Windows.Forms.ComboBox cmbAgent1P;
private System.Windows.Forms.Label lblAgent1P;
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search.Spans
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
using TFIDFSimilarity = Lucene.Net.Search.Similarities.TFIDFSimilarity;
[TestFixture]
public class TestFieldMaskingSpanQuery : LuceneTestCase
{
protected internal static Document Doc(Field[] fields)
{
Document doc = new Document();
for (int i = 0; i < fields.Length; i++)
{
doc.Add(fields[i]);
}
return doc;
}
protected internal Field GetField(string name, string value)
{
return NewTextField(name, value, Field.Store.NO);
}
protected internal static IndexSearcher searcher;
protected internal static Directory directory;
protected internal static IndexReader reader;
/// <summary>
/// LUCENENET specific
/// Is non-static because NewIndexWriterConfig is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
writer.AddDocument(Doc(new Field[] { GetField("id", "0"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "1"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "smith"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "2"), GetField("gender", "female"), GetField("first", "greta"), GetField("last", "jones"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "smith"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "3"), GetField("gender", "female"), GetField("first", "lisa"), GetField("last", "jones"), GetField("gender", "male"), GetField("first", "bob"), GetField("last", "costas") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "4"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "smith"), GetField("gender", "female"), GetField("first", "linda"), GetField("last", "dixit"), GetField("gender", "male"), GetField("first", "bubba"), GetField("last", "jones") }));
reader = writer.GetReader();
writer.Dispose();
searcher = NewSearcher(reader);
}
[OneTimeTearDown]
public override void AfterClass()
{
searcher = null;
reader.Dispose();
reader = null;
directory.Dispose();
directory = null;
base.AfterClass();
}
protected internal virtual void Check(SpanQuery q, int[] docs)
{
CheckHits.CheckHitCollector(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, q, null, searcher, docs);
}
[Test]
public virtual void TestRewrite0()
{
SpanQuery q = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
q.Boost = 8.7654321f;
SpanQuery qr = (SpanQuery)searcher.Rewrite(q);
QueryUtils.CheckEqual(q, qr);
ISet<Term> terms = new JCG.HashSet<Term>();
qr.ExtractTerms(terms);
Assert.AreEqual(1, terms.Count);
}
[Test]
public virtual void TestRewrite1()
{
// mask an anon SpanQuery class that rewrites to something else.
SpanQuery q = new FieldMaskingSpanQuery(new SpanTermQueryAnonymousClass(this, new Term("last", "sally")), "first");
SpanQuery qr = (SpanQuery)searcher.Rewrite(q);
QueryUtils.CheckUnequal(q, qr);
ISet<Term> terms = new JCG.HashSet<Term>();
qr.ExtractTerms(terms);
Assert.AreEqual(2, terms.Count);
}
private class SpanTermQueryAnonymousClass : SpanTermQuery
{
private readonly TestFieldMaskingSpanQuery outerInstance;
public SpanTermQueryAnonymousClass(TestFieldMaskingSpanQuery outerInstance, Term term)
: base(term)
{
this.outerInstance = outerInstance;
}
public override Query Rewrite(IndexReader reader)
{
return new SpanOrQuery(new SpanTermQuery(new Term("first", "sally")), new SpanTermQuery(new Term("first", "james")));
}
}
[Test]
public virtual void TestRewrite2()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "last") }, 1, true);
Query qr = searcher.Rewrite(q);
QueryUtils.CheckEqual(q, qr);
ISet<Term> set = new JCG.HashSet<Term>();
qr.ExtractTerms(set);
Assert.AreEqual(2, set.Count);
}
[Test]
public virtual void TestEquality1()
{
SpanQuery q1 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
SpanQuery q2 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
SpanQuery q3 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "XXXXX");
SpanQuery q4 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "XXXXX")), "first");
SpanQuery q5 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("xXXX", "sally")), "first");
QueryUtils.CheckEqual(q1, q2);
QueryUtils.CheckUnequal(q1, q3);
QueryUtils.CheckUnequal(q1, q4);
QueryUtils.CheckUnequal(q1, q5);
SpanQuery qA = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
qA.Boost = 9f;
SpanQuery qB = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
QueryUtils.CheckUnequal(qA, qB);
qB.Boost = 9f;
QueryUtils.CheckEqual(qA, qB);
}
[Test]
public virtual void TestNoop0()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "sally"));
SpanQuery q = new FieldMaskingSpanQuery(q1, "first");
Check(q, new int[] { }); // :EMPTY:
}
[Test]
public virtual void TestNoop1()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "last") }, 0, true);
Check(q, new int[] { 1, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "last"), new FieldMaskingSpanQuery(q2, "last") }, 0, true);
Check(q, new int[] { 1, 2 });
}
[Test]
public virtual void TestSimple1()
{
SpanQuery q1 = new SpanTermQuery(new Term("first", "james"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "first") }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q2, "first"), q1 }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { q2, new FieldMaskingSpanQuery(q1, "last") }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "last"), q2 }, -1, false);
Check(q, new int[] { 0, 2 });
}
[Test]
public virtual void TestSimple2()
{
AssumeTrue("Broken scoring: LUCENE-3723", searcher.Similarity is TFIDFSimilarity);
SpanQuery q1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "gender") }, -1, false);
Check(q, new int[] { 2, 4 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "id"), new FieldMaskingSpanQuery(q2, "id") }, -1, false);
Check(q, new int[] { 2, 4 });
}
[Test]
public virtual void TestSpans0()
{
SpanQuery q1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery q2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery q = new SpanOrQuery(q1, new FieldMaskingSpanQuery(q2, "gender"));
Check(q, new int[] { 0, 1, 2, 3, 4 });
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 1, 2), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 1, 2), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 2, 3), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(3, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(4, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(4, 1, 2), s(span));
Assert.AreEqual(false, span.MoveNext());
}
[Test]
public virtual void TestSpans1()
{
SpanQuery q1 = new SpanTermQuery(new Term("first", "sally"));
SpanQuery q2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery qA = new SpanOrQuery(q1, q2);
SpanQuery qB = new FieldMaskingSpanQuery(qA, "id");
Check(qA, new int[] { 0, 1, 2, 4 });
Check(qB, new int[] { 0, 1, 2, 4 });
Spans spanA = MultiSpansWrapper.Wrap(searcher.TopReaderContext, qA);
Spans spanB = MultiSpansWrapper.Wrap(searcher.TopReaderContext, qB);
while (spanA.MoveNext())
{
Assert.IsTrue(spanB.MoveNext(), "spanB not still going");
Assert.AreEqual(s(spanA), s(spanB), "spanA not equal spanB");
}
Assert.IsTrue(!(spanB.MoveNext()), "spanB still going even tough spanA is done");
}
[Test]
public virtual void TestSpans2()
{
AssumeTrue("Broken scoring: LUCENE-3723", searcher.Similarity is TFIDFSimilarity);
SpanQuery qA1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery qA2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery qA = new SpanOrQuery(qA1, new FieldMaskingSpanQuery(qA2, "gender"));
SpanQuery qB = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(qA, "id"), new FieldMaskingSpanQuery(qB, "id") }, -1, false);
Check(q, new int[] { 0, 1, 2, 3 });
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 1, 2), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 0, 1), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(2, 2, 3), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(3, 0, 1), s(span));
Assert.AreEqual(false, span.MoveNext());
}
public virtual string s(Spans span)
{
return s(span.Doc, span.Start, span.End);
}
public virtual string s(int doc, int start, int end)
{
return "s(" + doc + "," + start + "," + end + ")";
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Code adapted from Pex
//
// ==--==
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell.Interop;
using Project = EnvDTE.Project;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Contracts
{
internal static class ProjectHelper
{
public static class Properties
{
public const string ProjectGuid = "ProjectGuid";
}
public const string prjKindCSharpProject = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
public const string prjKindVBProject = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}";
public static bool IsObjectModelSupported(Project value)
{
Contract.Requires(value != null);
return
value.Kind == prjKindCSharpProject ||
value.Kind == prjKindVBProject;
}
public static bool TryGetHierarchyForProject(
IServiceProvider serviceProvider,
Project project,
out IVsHierarchy hierarchy)
{
Contract.Requires(serviceProvider != null);
Contract.Requires(project != null);
string uniqueName;
try
{
uniqueName = project.UniqueName;
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
uniqueName = null;
}
if (uniqueName == null)
{
hierarchy = null;
return false;
}
else
{
try
{
hierarchy = HierarchyFromUniqueName(
serviceProvider,
project.UniqueName);
if (hierarchy == null)
{
return false;
}
return true;
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
hierarchy = null;
return false;
}
}
}
private static IVsHierarchy HierarchyFromUniqueName(
IServiceProvider serviceProvider,
string uniqueName)
{
Contract.Requires(serviceProvider != null);
Contract.Requires(uniqueName != null);
var solution = VsServiceProviderHelper.GetService<IVsSolution>(serviceProvider);
if (solution == null)
{
return null;
}
IVsHierarchy hierarchy;
var hResult = solution.GetProjectOfUniqueName(uniqueName, out hierarchy);
if (Microsoft.VisualStudio.ErrorHandler.Failed(hResult))
throw Marshal.GetExceptionForHR(hResult);
return hierarchy;
}
/// <summary>
/// Tries to get a build property value
/// </summary>
/// <param name="project"></param>
/// <param name="configuration">may be null for 'all' configuration</param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool TryGetBuildProperty(
IServiceProvider serviceProvider,
Project project,
string configuration,
string name,
out string value)
{
Contract.Requires(serviceProvider != null);
Contract.Requires(project != null);
Contract.Requires(name != null);
if (configuration == null) configuration = String.Empty;
IVsHierarchy hierachy;
if (!TryGetHierarchyForProject(serviceProvider, project, out hierachy))
{
value = null;
return false;
}
IVsBuildPropertyStorage properties = hierachy as IVsBuildPropertyStorage;
if (properties == null)
{
value = null;
return false;
}
try
{
int hresult = properties.GetPropertyValue(
name,
configuration,
(uint)_PersistStorageType.PST_USER_FILE,
out value);
if (Microsoft.VisualStudio.ErrorHandler.Succeeded(hresult))
return true;
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
}
try
{
int hresult = properties.GetPropertyValue(
name,
configuration,
(uint)_PersistStorageType.PST_PROJECT_FILE,
out value);
return Microsoft.VisualStudio.ErrorHandler.Succeeded(hresult);
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
}
value = null;
return false;
}
public static bool TryGetActiveProject(IServiceProvider serviceProvider, out Project project)
{
Contract.Requires(serviceProvider != null);
Contract.Ensures(Contract.ValueAtReturn(out project) != null || !Contract.Result<bool>());
project = null;
try
{
var dte = VsServiceProviderHelper.GetService<DTE>(serviceProvider);
if (dte == null)
{
return false;
}
if (dte.Solution != null)
{
object[] projects = dte.ActiveSolutionProjects as object[];
if (projects != null && projects.Length == 1)
project = (Project)projects[0];
}
return project != null;
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
}
return false;
}
public static bool TryGetProperty(
IServiceProvider serviceProvider,
Project project, string propertyName, out string value)
{
Contract.Requires(serviceProvider != null);
Contract.Requires(project != null);
Contract.Requires(propertyName != null);
try
{
var properties = project.Properties;
if (properties != null)
{
var property = project.Properties.Item(propertyName);
if (property != null)
{
value = (string)property.Value;
return true;
}
}
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
}
// try msbuild properties
return
TryGetBuildProperty(
serviceProvider,
project,
null,
propertyName,
out value);
}
public static void SaveAllFiles(IServiceProvider serviceProvider)
{
Contract.Requires(serviceProvider != null);
DTE dte = VsServiceProviderHelper.GetService<DTE>(serviceProvider);
if (dte != null)
{
dte.ExecuteCommand("File.SaveAll", "");
}
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
public static bool TryGetActiveSolutionConfiguration(
IServiceProvider serviceProvider,
out SolutionBuild solutionBuild,
out SolutionConfiguration2 activeConfiguration)
{
Contract.Requires(serviceProvider != null);
Contract.Ensures(Contract.ValueAtReturn(out solutionBuild) != null || !Contract.Result<bool>());
Contract.Ensures(Contract.ValueAtReturn(out activeConfiguration) != null || !Contract.Result<bool>());
solutionBuild = null;
activeConfiguration = null;
DTE dte = VsServiceProviderHelper.GetService<DTE>(serviceProvider);
if (dte == null)
return false;
var solution = dte.Solution;
if (solution == null)
return false;
solutionBuild = solution.SolutionBuild;
Contract.Assume(solutionBuild != null);
activeConfiguration = solutionBuild.ActiveConfiguration as SolutionConfiguration2;
return solutionBuild != null && activeConfiguration != null;
}
public static bool TryBuildProject(ContractsVsPackage package, Project project)
{
Contract.Requires(package != null);
Contract.Requires(project != null);
SolutionBuild solutionBuild;
SolutionConfiguration2 activeConfiguration;
if (!TryGetActiveSolutionConfiguration(package, out solutionBuild, out activeConfiguration))
return false;
string configurationName = activeConfiguration.Name;
string platformName = activeConfiguration.PlatformName;
string buildName = configurationName + '|' + platformName;
try
{
solutionBuild.BuildProject(
buildName,
project.UniqueName,
true);
}
catch (Exception ex)
{
ContractsVsPackage.SwallowedException(ex);
return false;
}
return
solutionBuild.BuildState == vsBuildState.vsBuildStateDone &&
solutionBuild.LastBuildInfo == 0;
}
public static bool TryGetProjectGuid(IServiceProvider serviceProvider, Project project, out string projectGuid)
{
Contract.Requires(serviceProvider != null);
Contract.Requires(project != null);
return ProjectHelper.TryGetProperty(serviceProvider, project, Properties.ProjectGuid, out projectGuid);
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.10.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google OAuth2 API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/accounts/docs/OAuth2'>Google OAuth2 API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20160217 (412)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/accounts/docs/OAuth2'>
* https://developers.google.com/accounts/docs/OAuth2</a>
* <tr><th>Discovery Name<td>oauth2
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google OAuth2 API can be found at
* <a href='https://developers.google.com/accounts/docs/OAuth2'>https://developers.google.com/accounts/docs/OAuth2</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Oauth2.v1
{
/// <summary>The Oauth2 Service.</summary>
public class Oauth2Service : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public Oauth2Service() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public Oauth2Service(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
userinfo = new UserinfoResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "oauth2"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
/// <summary>Available OAuth 2.0 scopes for use with the Google OAuth2 API.</summary>
public class Scope
{
/// <summary>Know the list of people in your circles, your age range, and language</summary>
public static string PlusLogin = "https://www.googleapis.com/auth/plus.login";
/// <summary>Know who you are on Google</summary>
public static string PlusMe = "https://www.googleapis.com/auth/plus.me";
/// <summary>View your email address</summary>
public static string UserinfoEmail = "https://www.googleapis.com/auth/userinfo.email";
/// <summary>View your basic profile info</summary>
public static string UserinfoProfile = "https://www.googleapis.com/auth/userinfo.profile";
}
public virtual GetCertForOpenIdConnectRequest GetCertForOpenIdConnect()
{
return new GetCertForOpenIdConnectRequest(this);
}
public class GetCertForOpenIdConnectRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.X509>
{
/// <summary>Constructs a new GetCertForOpenIdConnect request.</summary>
public GetCertForOpenIdConnectRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getCertForOpenIdConnect"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "oauth2/v1/certs"; }
}
/// <summary>Initializes GetCertForOpenIdConnect parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
public virtual GetCertForOpenIdConnectRawRequest GetCertForOpenIdConnectRaw()
{
return new GetCertForOpenIdConnectRawRequest(this);
}
public class GetCertForOpenIdConnectRawRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.Raw>
{
/// <summary>Constructs a new GetCertForOpenIdConnectRaw request.</summary>
public GetCertForOpenIdConnectRawRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getCertForOpenIdConnectRaw"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "oauth2/v1/raw_public_keys"; }
}
/// <summary>Initializes GetCertForOpenIdConnectRaw parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <param name="robotEmail">The email of robot account.</param>
public virtual GetRobotJwkRequest GetRobotJwk(string robotEmail)
{
return new GetRobotJwkRequest(this, robotEmail);
}
public class GetRobotJwkRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.Jwk>
{
/// <summary>Constructs a new GetRobotJwk request.</summary>
public GetRobotJwkRequest(Google.Apis.Services.IClientService service, string robotEmail)
: base(service)
{
RobotEmail = robotEmail;
InitParameters();
}
/// <summary>The email of robot account.</summary>
[Google.Apis.Util.RequestParameterAttribute("robotEmail", Google.Apis.Util.RequestParameterType.Path)]
public virtual string RobotEmail { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getRobotJwk"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "service_accounts/v1/jwk/{robotEmail}"; }
}
/// <summary>Initializes GetRobotJwk parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"robotEmail", new Google.Apis.Discovery.Parameter
{
Name = "robotEmail",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <param name="robotEmail">The email of robot account.</param>
public virtual GetRobotMetadataRawRequest GetRobotMetadataRaw(string robotEmail)
{
return new GetRobotMetadataRawRequest(this, robotEmail);
}
public class GetRobotMetadataRawRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.Raw>
{
/// <summary>Constructs a new GetRobotMetadataRaw request.</summary>
public GetRobotMetadataRawRequest(Google.Apis.Services.IClientService service, string robotEmail)
: base(service)
{
RobotEmail = robotEmail;
InitParameters();
}
/// <summary>The email of robot account.</summary>
[Google.Apis.Util.RequestParameterAttribute("robotEmail", Google.Apis.Util.RequestParameterType.Path)]
public virtual string RobotEmail { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getRobotMetadataRaw"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "service_accounts/v1/metadata/raw/{robotEmail}"; }
}
/// <summary>Initializes GetRobotMetadataRaw parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"robotEmail", new Google.Apis.Discovery.Parameter
{
Name = "robotEmail",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <param name="robotEmail">The email of robot account.</param>
public virtual GetRobotMetadataX509Request GetRobotMetadataX509(string robotEmail)
{
return new GetRobotMetadataX509Request(this, robotEmail);
}
public class GetRobotMetadataX509Request : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.X509>
{
/// <summary>Constructs a new GetRobotMetadataX509 request.</summary>
public GetRobotMetadataX509Request(Google.Apis.Services.IClientService service, string robotEmail)
: base(service)
{
RobotEmail = robotEmail;
InitParameters();
}
/// <summary>The email of robot account.</summary>
[Google.Apis.Util.RequestParameterAttribute("robotEmail", Google.Apis.Util.RequestParameterType.Path)]
public virtual string RobotEmail { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getRobotMetadataX509"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "service_accounts/v1/metadata/x509/{robotEmail}"; }
}
/// <summary>Initializes GetRobotMetadataX509 parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"robotEmail", new Google.Apis.Discovery.Parameter
{
Name = "robotEmail",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}/// <summary>Get token info</summary>
public virtual TokeninfoRequest Tokeninfo()
{
return new TokeninfoRequest(this);
}
/// <summary>Get token info</summary>
public class TokeninfoRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.Tokeninfo>
{
/// <summary>Constructs a new Tokeninfo request.</summary>
public TokeninfoRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>The oauth2 access token</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>The ID token</summary>
[Google.Apis.Util.RequestParameterAttribute("id_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string IdToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "tokeninfo"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "oauth2/v1/tokeninfo"; }
}
/// <summary>Initializes Tokeninfo parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"id_token", new Google.Apis.Discovery.Parameter
{
Name = "id_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
private readonly UserinfoResource userinfo;
/// <summary>Gets the Userinfo resource.</summary>
public virtual UserinfoResource Userinfo
{
get { return userinfo; }
}
}
///<summary>A base abstract class for Oauth2 requests.</summary>
public abstract class Oauth2BaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new Oauth2BaseServiceRequest instance.</summary>
protected Oauth2BaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Oauth2 parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "userinfo" collection of methods.</summary>
public class UserinfoResource
{
private const string Resource = "userinfo";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public UserinfoResource(Google.Apis.Services.IClientService service)
{
this.service = service;
v2 = new V2Resource(service);
}
private readonly V2Resource v2;
/// <summary>Gets the V2 resource.</summary>
public virtual V2Resource V2
{
get { return v2; }
}
/// <summary>The "v2" collection of methods.</summary>
public class V2Resource
{
private const string Resource = "v2";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public V2Resource(Google.Apis.Services.IClientService service)
{
this.service = service;
me = new MeResource(service);
}
private readonly MeResource me;
/// <summary>Gets the Me resource.</summary>
public virtual MeResource Me
{
get { return me; }
}
/// <summary>The "me" collection of methods.</summary>
public class MeResource
{
private const string Resource = "me";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MeResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Get user info</summary>
public virtual GetRequest Get()
{
return new GetRequest(service);
}
/// <summary>Get user info</summary>
public class GetRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.Userinfoplus>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "userinfo/v2/me"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
/// <summary>Get user info</summary>
public virtual GetRequest Get()
{
return new GetRequest(service);
}
/// <summary>Get user info</summary>
public class GetRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v1.Data.Userinfoplus>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "oauth2/v1/userinfo"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.Oauth2.v1.Data
{
public class Jwk : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("keys")]
public virtual System.Collections.Generic.IList<Jwk.KeysData> Keys { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
public class KeysData
{
[Newtonsoft.Json.JsonPropertyAttribute("alg")]
public virtual string Alg { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("e")]
public virtual string E { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("kid")]
public virtual string Kid { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("kty")]
public virtual string Kty { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("n")]
public virtual string N { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("use")]
public virtual string Use { get; set; }
}
}
public class Raw : Google.Apis.Requests.IDirectResponseSchema
{
[Newtonsoft.Json.JsonPropertyAttribute("keyvalues")]
public virtual System.Collections.Generic.IList<Raw.KeyvaluesData> Keyvalues { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
public class KeyvaluesData
{
[Newtonsoft.Json.JsonPropertyAttribute("algorithm")]
public virtual string Algorithm { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("exponent")]
public virtual string Exponent { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("keyid")]
public virtual string Keyid { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("modulus")]
public virtual string Modulus { get; set; }
}
}
public class Tokeninfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The access type granted with this token. It can be offline or online.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("access_type")]
public virtual string AccessType { get; set; }
/// <summary>Who is the intended audience for this token. In general the same as issued_to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audience")]
public virtual string Audience { get; set; }
/// <summary>The email address of the user. Present only if the email scope is present in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email")]
public virtual string Email { get; set; }
/// <summary>Boolean flag which is true if the email address is verified. Present only if the email scope is
/// present in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email_verified")]
public virtual System.Nullable<bool> EmailVerified { get; set; }
/// <summary>The expiry time of the token, as number of seconds left until expiry.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expires_in")]
public virtual System.Nullable<int> ExpiresIn { get; set; }
/// <summary>The issue time of the token, as number of seconds.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issued_at")]
public virtual System.Nullable<int> IssuedAt { get; set; }
/// <summary>To whom was the token issued to. In general the same as audience.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issued_to")]
public virtual string IssuedTo { get; set; }
/// <summary>Who issued the token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuer")]
public virtual string Issuer { get; set; }
/// <summary>Nonce of the id token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nonce")]
public virtual string Nonce { get; set; }
/// <summary>The space separated list of scopes granted to this token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scope")]
public virtual string Scope { get; set; }
/// <summary>The obfuscated user id.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("user_id")]
public virtual string UserId { get; set; }
/// <summary>Boolean flag which is true if the email address is verified. Present only if the email scope is
/// present in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verified_email")]
public virtual System.Nullable<bool> VerifiedEmail { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class Userinfoplus : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The user's email address.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email")]
public virtual string Email { get; set; }
/// <summary>The user's last name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("family_name")]
public virtual string FamilyName { get; set; }
/// <summary>The user's gender.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gender")]
public virtual string Gender { get; set; }
/// <summary>The user's first name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("given_name")]
public virtual string GivenName { get; set; }
/// <summary>The hosted domain e.g. example.com if the user is Google apps user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hd")]
public virtual string Hd { get; set; }
/// <summary>The obfuscated ID of the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>URL of the profile page.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("link")]
public virtual string Link { get; set; }
/// <summary>The user's preferred locale.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locale")]
public virtual string Locale { get; set; }
/// <summary>The user's full name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>URL of the user's picture image.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("picture")]
public virtual string Picture { get; set; }
/// <summary>Boolean flag which is true if the email address is verified. Always verified because we only return
/// the user's primary email address.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verified_email")]
public virtual System.Nullable<bool> VerifiedEmail { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.