context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Camera/Camera Motion Blur") ]
public class CameraMotionBlur : PostEffectsBase
{
// make sure to match this to MAX_RADIUS in shader ('k' in paper)
static float MAX_RADIUS = 10.0f;
public enum MotionBlurFilter {
CameraMotion = 0, // global screen blur based on cam motion
LocalBlur = 1, // cheap blur, no dilation or scattering
Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper
ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper
ReconstructionDisc = 4, // advanced filter using scaled poisson disc sampling
}
// settings
public MotionBlurFilter filterType = MotionBlurFilter.Reconstruction;
public bool preview = false; // show how blur would look like in action ...
public Vector3 previewScale = Vector3.one; // ... given this movement vector
// params
public float movementScale = 0.0f;
public float rotationScale = 1.0f;
public float maxVelocity = 8.0f; // maximum velocity in pixels
public float minVelocity = 0.1f; // minimum velocity in pixels
public float velocityScale = 0.375f; // global velocity scale
public float softZDistance = 0.005f; // for z overlap check softness (reconstruction filter only)
public int velocityDownsample = 1; // low resolution velocity buffer? (optimization)
public LayerMask excludeLayers = 0;
private GameObject tmpCam = null;
// resources
public Shader shader;
public Shader dx11MotionBlurShader;
public Shader replacementClear;
private Material motionBlurMaterial = null;
private Material dx11MotionBlurMaterial = null;
public Texture2D noiseTexture = null;
public float jitter = 0.05f;
// (internal) debug
public bool showVelocity = false;
public float showVelocityScale = 1.0f;
// camera transforms
private Matrix4x4 currentViewProjMat;
private Matrix4x4 prevViewProjMat;
private int prevFrameCount;
private bool wasActive;
// shortcuts to calculate global blur direction when using 'CameraMotion'
private Vector3 prevFrameForward = Vector3.forward;
private Vector3 prevFrameUp = Vector3.up;
private Vector3 prevFramePos = Vector3.zero;
private Camera _camera;
private void CalculateViewProjection () {
Matrix4x4 viewMat = _camera.worldToCameraMatrix;
Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true);
currentViewProjMat = projMat * viewMat;
}
new void Start () {
CheckResources ();
if (_camera == null)
_camera = GetComponent<Camera>();
wasActive = gameObject.activeInHierarchy;
CalculateViewProjection ();
Remember ();
wasActive = false; // hack to fake position/rotation update and prevent bad blurs
}
void OnEnable () {
if (_camera == null)
_camera = GetComponent<Camera>();
_camera.depthTextureMode |= DepthTextureMode.Depth;
}
void OnDisable () {
if (null != motionBlurMaterial) {
DestroyImmediate (motionBlurMaterial);
motionBlurMaterial = null;
}
if (null != dx11MotionBlurMaterial) {
DestroyImmediate (dx11MotionBlurMaterial);
dx11MotionBlurMaterial = null;
}
if (null != tmpCam) {
DestroyImmediate (tmpCam);
tmpCam = null;
}
}
public override bool CheckResources () {
CheckSupport (true, true); // depth & hdr needed
motionBlurMaterial = CheckShaderAndCreateMaterial (shader, motionBlurMaterial);
if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11) {
dx11MotionBlurMaterial = CheckShaderAndCreateMaterial (dx11MotionBlurShader, dx11MotionBlurMaterial);
}
if (!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnRenderImage (RenderTexture source, RenderTexture destination) {
if (false == CheckResources ()) {
Graphics.Blit (source, destination);
return;
}
if (filterType == MotionBlurFilter.CameraMotion)
StartFrame ();
// use if possible new RG format ... fallback to half otherwise
var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;
// get temp textures
RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat);
int tileWidth = 1;
int tileHeight = 1;
maxVelocity = Mathf.Max (2.0f, maxVelocity);
float _maxVelocity = maxVelocity; // calculate 'k'
// note: 's' is hardcoded in shaders except for DX11 path
// auto DX11 fallback!
bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null;
if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) {
maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS);
tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
_maxVelocity = velBuffer.width/tileWidth;
}
else {
tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
_maxVelocity = velBuffer.width/tileWidth;
}
RenderTexture tileMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
RenderTexture neighbourMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
velBuffer.filterMode = FilterMode.Point;
tileMax.filterMode = FilterMode.Point;
neighbourMax.filterMode = FilterMode.Point;
if (noiseTexture) noiseTexture.filterMode = FilterMode.Point;
source.wrapMode = TextureWrapMode.Clamp;
velBuffer.wrapMode = TextureWrapMode.Clamp;
neighbourMax.wrapMode = TextureWrapMode.Clamp;
tileMax.wrapMode = TextureWrapMode.Clamp;
// calc correct viewprj matrix
CalculateViewProjection ();
// just started up?
if (gameObject.activeInHierarchy && !wasActive) {
Remember ();
}
wasActive = gameObject.activeInHierarchy;
// matrices
Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat);
motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj);
motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity);
motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);
motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
motionBlurMaterial.SetFloat ("_Jitter", jitter);
// texture samplers
motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
motionBlurMaterial.SetTexture ("_VelTex", velBuffer);
motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);
motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax);
if (preview) {
// generate an artifical 'previous' matrix to simulate blur look
Matrix4x4 viewMat = _camera.worldToCameraMatrix;
Matrix4x4 offset = Matrix4x4.identity;
offset.SetTRS(previewScale * 0.3333f, Quaternion.identity, Vector3.one); // using only translation
Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true);
prevViewProjMat = projMat * offset * viewMat;
motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
}
if (filterType == MotionBlurFilter.CameraMotion)
{
// build blur vector to be used in shader to create a global blur direction
Vector4 blurVector = Vector4.zero;
float lookUpDown = Vector3.Dot (transform.up, Vector3.up);
Vector3 distanceVector = prevFramePos-transform.position;
float distMag = distanceVector.magnitude;
float farHeur = 1.0f;
// pitch (vertical)
farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f);
blurVector.x = rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp)));
// yaw #1 (horizontal, faded by pitch)
farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));
// yaw #2 (when looking down, faded by 1-pitch)
farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));
if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) {
// forward (probably most important)
blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f);
// jump (maybe scale down further)
blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f);
// strafe (maybe scale down further)
blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f);
}
if (preview) // crude approximation
motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView);
else
motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector);
}
else {
// generate velocity buffer
Graphics.Blit (source, velBuffer, motionBlurMaterial, 0);
// patch up velocity buffer:
// exclude certain layers (e.g. skinned objects as we cant really support that atm)
Camera cam = null;
if (excludeLayers.value != 0)// || dynamicLayers.value)
cam = GetTmpCam ();
if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) {
cam.targetTexture = velBuffer;
cam.cullingMask = excludeLayers;
cam.RenderWithShader (replacementClear, "");
}
}
if (!preview && Time.frameCount != prevFrameCount) {
// remember current transformation data for next frame
prevFrameCount = Time.frameCount;
Remember ();
}
source.filterMode = FilterMode.Bilinear;
// debug vel buffer:
if (showVelocity) {
// generate tile max and neighbour max
//Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
//Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale);
Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1);
}
else {
if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) {
// need to reset some parameters for dx11 shader
dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter);
// texture samplers
dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer);
dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);
dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);
// generate tile max and neighbour max
Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0);
Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1);
// final blur
Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2);
}
else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) {
// 'reconstructing' properly integrated color
motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
// generate tile max and neighbour max
Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
// final blur
Graphics.Blit (source, destination, motionBlurMaterial, 4);
}
else if (filterType == MotionBlurFilter.CameraMotion) {
// orange box style motion blur
Graphics.Blit (source, destination, motionBlurMaterial, 6);
}
else if (filterType == MotionBlurFilter.ReconstructionDisc) {
// dof style motion blur defocuing and ellipse around the princical blur direction
// 'reconstructing' properly integrated color
motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
// generate tile max and neighbour max
Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
Graphics.Blit (source, destination, motionBlurMaterial, 7);
}
else {
// simple & fast blur (low quality): just blurring along velocity
Graphics.Blit (source, destination, motionBlurMaterial, 5);
}
}
// cleanup
RenderTexture.ReleaseTemporary (velBuffer);
RenderTexture.ReleaseTemporary (tileMax);
RenderTexture.ReleaseTemporary (neighbourMax);
}
void Remember () {
prevViewProjMat = currentViewProjMat;
prevFrameForward = transform.forward;
prevFrameUp = transform.up;
prevFramePos = transform.position;
}
Camera GetTmpCam () {
if (tmpCam == null) {
string name = "_" + _camera.name + "_MotionBlurTmpCam";
GameObject go = GameObject.Find (name);
if (null == go) // couldn't find, recreate
tmpCam = new GameObject (name, typeof (Camera));
else
tmpCam = go;
}
tmpCam.hideFlags = HideFlags.DontSave;
tmpCam.transform.position = _camera.transform.position;
tmpCam.transform.rotation = _camera.transform.rotation;
tmpCam.transform.localScale = _camera.transform.localScale;
tmpCam.GetComponent<Camera>().CopyFrom(_camera);
tmpCam.GetComponent<Camera>().enabled = false;
tmpCam.GetComponent<Camera>().depthTextureMode = DepthTextureMode.None;
tmpCam.GetComponent<Camera>().clearFlags = CameraClearFlags.Nothing;
return tmpCam.GetComponent<Camera>();
}
void StartFrame () {
// take only x% of positional changes into account (camera motion)
// TODO: possibly do the same for rotational part
prevFramePos = Vector3.Slerp(prevFramePos, transform.position, 0.75f);
}
static int divRoundUp (int x, int d)
{
return (x + d - 1) / d;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal sealed class XPathScanner
{
private string _xpathExpr;
private int _xpathExprIndex;
private LexKind _kind;
private char _currentChar;
private string _name;
private string _prefix;
private string _stringValue;
private double _numberValue = double.NaN;
private bool _canBeFunction;
private XmlCharType _xmlCharType = XmlCharType.Instance;
public XPathScanner(string xpathExpr)
{
if (xpathExpr == null)
{
throw XPathException.Create(SR.Xp_ExprExpected, string.Empty);
}
_xpathExpr = xpathExpr;
NextChar();
NextLex();
}
public string SourceText { get { return _xpathExpr; } }
private char CurrentChar { get { return _currentChar; } }
private bool NextChar()
{
Debug.Assert(0 <= _xpathExprIndex && _xpathExprIndex <= _xpathExpr.Length);
if (_xpathExprIndex < _xpathExpr.Length)
{
_currentChar = _xpathExpr[_xpathExprIndex++];
return true;
}
else
{
_currentChar = '\0';
return false;
}
}
#if XML10_FIFTH_EDITION
private char PeekNextChar()
{
Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length);
if (xpathExprIndex < xpathExpr.Length)
{
return xpathExpr[xpathExprIndex];
}
else
{
Debug.Assert(xpathExprIndex == xpathExpr.Length);
return '\0';
}
}
#endif
public LexKind Kind { get { return _kind; } }
public string Name
{
get
{
Debug.Assert(_kind == LexKind.Name || _kind == LexKind.Axe);
Debug.Assert(_name != null);
return _name;
}
}
public string Prefix
{
get
{
Debug.Assert(_kind == LexKind.Name);
Debug.Assert(_prefix != null);
return _prefix;
}
}
public string StringValue
{
get
{
Debug.Assert(_kind == LexKind.String);
Debug.Assert(_stringValue != null);
return _stringValue;
}
}
public double NumberValue
{
get
{
Debug.Assert(_kind == LexKind.Number);
Debug.Assert(!double.IsNaN(_numberValue));
return _numberValue;
}
}
// To parse PathExpr we need a way to distinct name from function.
// This distinction can't be done without context: "or (1 != 0)" this is a function or 'or' in OrExp
public bool CanBeFunction
{
get
{
Debug.Assert(_kind == LexKind.Name);
return _canBeFunction;
}
}
void SkipSpace()
{
while (_xmlCharType.IsWhiteSpace(this.CurrentChar) && NextChar()) ;
}
public bool NextLex()
{
SkipSpace();
switch (this.CurrentChar)
{
case '\0':
_kind = LexKind.Eof;
return false;
case ',':
case '@':
case '(':
case ')':
case '|':
case '*':
case '[':
case ']':
case '+':
case '-':
case '=':
case '#':
case '$':
_kind = (LexKind)Convert.ToInt32(this.CurrentChar, CultureInfo.InvariantCulture);
NextChar();
break;
case '<':
_kind = LexKind.Lt;
NextChar();
if (this.CurrentChar == '=')
{
_kind = LexKind.Le;
NextChar();
}
break;
case '>':
_kind = LexKind.Gt;
NextChar();
if (this.CurrentChar == '=')
{
_kind = LexKind.Ge;
NextChar();
}
break;
case '!':
_kind = LexKind.Bang;
NextChar();
if (this.CurrentChar == '=')
{
_kind = LexKind.Ne;
NextChar();
}
break;
case '.':
_kind = LexKind.Dot;
NextChar();
if (this.CurrentChar == '.')
{
_kind = LexKind.DotDot;
NextChar();
}
else if (XmlCharType.IsDigit(this.CurrentChar))
{
_kind = LexKind.Number;
_numberValue = ScanFraction();
}
break;
case '/':
_kind = LexKind.Slash;
NextChar();
if (this.CurrentChar == '/')
{
_kind = LexKind.SlashSlash;
NextChar();
}
break;
case '"':
case '\'':
_kind = LexKind.String;
_stringValue = ScanString();
break;
default:
if (XmlCharType.IsDigit(this.CurrentChar))
{
_kind = LexKind.Number;
_numberValue = ScanNumber();
}
else if (_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
)
{
_kind = LexKind.Name;
_name = ScanName();
_prefix = string.Empty;
// "foo:bar" is one lexeme not three because it doesn't allow spaces in between
// We should distinct it from "foo::" and need process "foo ::" as well
if (this.CurrentChar == ':')
{
NextChar();
// can be "foo:bar" or "foo::"
if (this.CurrentChar == ':')
{ // "foo::"
NextChar();
_kind = LexKind.Axe;
}
else
{ // "foo:*", "foo:bar" or "foo: "
_prefix = _name;
if (this.CurrentChar == '*')
{
NextChar();
_name = "*";
}
else if (_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
)
{
_name = ScanName();
}
else
{
throw XPathException.Create(SR.Xp_InvalidName, SourceText);
}
}
}
else
{
SkipSpace();
if (this.CurrentChar == ':')
{
NextChar();
// it can be "foo ::" or just "foo :"
if (this.CurrentChar == ':')
{
NextChar();
_kind = LexKind.Axe;
}
else
{
throw XPathException.Create(SR.Xp_InvalidName, SourceText);
}
}
}
SkipSpace();
_canBeFunction = (this.CurrentChar == '(');
}
else
{
throw XPathException.Create(SR.Xp_InvalidToken, SourceText);
}
break;
}
return true;
}
private double ScanNumber()
{
Debug.Assert(this.CurrentChar == '.' || XmlCharType.IsDigit(this.CurrentChar));
int start = _xpathExprIndex - 1;
int len = 0;
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
if (this.CurrentChar == '.')
{
NextChar(); len++;
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
}
return XmlConvert.ToXPathDouble(_xpathExpr.Substring(start, len));
}
private double ScanFraction()
{
Debug.Assert(XmlCharType.IsDigit(this.CurrentChar));
int start = _xpathExprIndex - 2;
Debug.Assert(0 <= start && _xpathExpr[start] == '.');
int len = 1; // '.'
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
return XmlConvert.ToXPathDouble(_xpathExpr.Substring(start, len));
}
private string ScanString()
{
char endChar = this.CurrentChar;
NextChar();
int start = _xpathExprIndex - 1;
int len = 0;
while (this.CurrentChar != endChar)
{
if (!NextChar())
{
throw XPathException.Create(SR.Xp_UnclosedString);
}
len++;
}
Debug.Assert(this.CurrentChar == endChar);
NextChar();
return _xpathExpr.Substring(start, len);
}
private string ScanName()
{
Debug.Assert(_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
);
int start = _xpathExprIndex - 1;
int len = 0;
for (; ;)
{
if (_xmlCharType.IsNCNameSingleChar(this.CurrentChar))
{
NextChar();
len++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(this.PeekNextChar(), this.CurerntChar))
{
NextChar();
NextChar();
len += 2;
}
#endif
else
{
break;
}
}
return _xpathExpr.Substring(start, len);
}
public enum LexKind
{
Comma = ',',
Slash = '/',
At = '@',
Dot = '.',
LParens = '(',
RParens = ')',
LBracket = '[',
RBracket = ']',
Star = '*',
Plus = '+',
Minus = '-',
Eq = '=',
Lt = '<',
Gt = '>',
Bang = '!',
Dollar = '$',
Apos = '\'',
Quote = '"',
Union = '|',
Ne = 'N', // !=
Le = 'L', // <=
Ge = 'G', // >=
And = 'A', // &&
Or = 'O', // ||
DotDot = 'D', // ..
SlashSlash = 'S', // //
Name = 'n', // XML _Name
String = 's', // Quoted string constant
Number = 'd', // _Number constant
Axe = 'a', // Axe (like child::)
Eof = 'E',
};
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
namespace ProjectFileProcessor
{
class Program
{
private static void ReadFile(string inputVcxproj, ref List<string> linesInputVcxproj)
{
try
{
using (StreamReader sr = new StreamReader(inputVcxproj))
{
while (true)
{
string line = sr.ReadLine();
if (line == null)
break;
linesInputVcxproj.Add(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
return;
}
}
private static void ExtractFileSection(
ref List<string> linesInputVcxproj,
ref List<string> filesInputVcxproj,
string rootFolder,
bool extraFilters
)
{
bool fileSectionStart = false;
bool fileSectionStop = false;
rootFolder += "\\";
for (int i = 1; i < linesInputVcxproj.Count - 1; i++)
{
string l0 = linesInputVcxproj[i - 1];
string l1 = linesInputVcxproj[i];
string l2 = linesInputVcxproj[i + 1];
if (l1.Contains("<ItemGroup>") &&
(l2.Contains("ClInclude") || l2.Contains("ClCompile")))
{
fileSectionStart = true;
}
if (fileSectionStart)
{
if (l0.Contains("</ItemGroup>") && !l1.Contains("<ItemGroup>"))
{
fileSectionStop = true;
}
}
if (fileSectionStart && !fileSectionStop)
{
string file = MakeFilePathRelative(l1, rootFolder);
if (extraFilters)
{
if (!file.Contains("ItemGroup") && !file.Contains("PrecompiledHeaderFile"))
{
filesInputVcxproj.Add(file);
}
}
else
{
filesInputVcxproj.Add(file);
}
//Console.WriteLine(l1);
}
}
}
class FileNode
{
public string cmake_vcxproj;
public string template;
public string output;
}
static void Main(string[] args)
{
string rootFolder = null;
if (args.Length == 0)
rootFolder = @"C:\git\forks\xbox-live-api";
else
rootFolder = args[0];
if (args.Length == 4 && args[1] == "diff")
{
string fileOld = args[2];
string fileNew = args[3];
DiffFiles(fileOld, fileNew, rootFolder);
return;
}
var fileNodes = new List<FileNode>();
//libHttpClient.142.UWP.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UWP.C.vcxproj",
template = @"template-libHttpClient.142.UWP.C.vcxproj",
output = @"libHttpClient.142.UWP.C.vcxproj",
});
//libHttpClient.141.UWP.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UWP.C.vcxproj",
template = @"template-libHttpClient.141.UWP.C.vcxproj",
output = @"libHttpClient.141.UWP.C.vcxproj",
});
//libHttpClient.140.UWP.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UWP.C.vcxproj",
template = @"template-libHttpClient.140.UWP.C.vcxproj",
output = @"libHttpClient.140.UWP.C.vcxproj",
});
//libHttpClient.142.Win32.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Win32.C.vcxproj",
template = @"template-libHttpClient.142.Win32.C.vcxproj",
output = @"libHttpClient.142.Win32.C.vcxproj",
});
//libHttpClient.141.Win32.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Win32.C.vcxproj",
template = @"template-libHttpClient.141.Win32.C.vcxproj",
output = @"libHttpClient.141.Win32.C.vcxproj",
});
//libHttpClient.140.Win32.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Win32.C.vcxproj",
template = @"template-libHttpClient.140.Win32.C.vcxproj",
output = @"libHttpClient.140.Win32.C.vcxproj",
});
//libHttpClient.142.Android.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Android.C.vcxproj",
template = @"template-libHttpClient.142.Android.C.vcxproj",
output = @"libHttpClient.142.Android.C.vcxproj",
});
//libHttpClient.141.Android.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Android.C.vcxproj",
template = @"template-libHttpClient.141.Android.C.vcxproj",
output = @"libHttpClient.141.Android.C.vcxproj",
});
//libHttpClient.142.XDK.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.XDK.C.vcxproj",
template = @"template-libHttpClient.142.XDK.C.vcxproj",
output = @"libHttpClient.142.XDK.C.vcxproj",
});
//libHttpClient.141.XDK.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.XDK.C.vcxproj",
template = @"template-libHttpClient.141.XDK.C.vcxproj",
output = @"libHttpClient.141.XDK.C.vcxproj",
});
//libHttpClient.140.XDK.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.XDK.C.vcxproj",
template = @"template-libHttpClient.140.XDK.C.vcxproj",
output = @"libHttpClient.140.XDK.C.vcxproj",
});
//libHttpClient.110.XDK.WinRT
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.XDK.WinRT.vcxproj",
template = @"template-libHttpClient.110.XDK.WinRT.vcxproj",
output = @"libHttpClient.110.XDK.WinRT.vcxproj",
});
//libHttpClient.140.UWP.WinRT
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UWP.WinRT.vcxproj",
template = @"template-libHttpClient.140.UWP.WinRT.vcxproj",
output = @"libHttpClient.140.UWP.WinRT.vcxproj",
});
//libHttpClient.110.XDK.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.XDK.C.vcxproj",
template = @"template-libHttpClient.110.XDK.C.vcxproj",
output = @"libHttpClient.110.XDK.C.vcxproj",
});
//libHttpClient.UnitTest.142.TAEF
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UnitTest.142.TAEF.vcxproj",
template = @"template-libHttpClient.UnitTest.142.TAEF.vcxproj",
output = @"libHttpClient.UnitTest.142.TAEF.vcxproj",
});
//libHttpClient.UnitTest.141.TAEF
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UnitTest.141.TAEF.vcxproj",
template = @"template-libHttpClient.UnitTest.141.TAEF.vcxproj",
output = @"libHttpClient.UnitTest.141.TAEF.vcxproj",
});
//libHttpClient.UnitTest.142.TE
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UnitTest.142.TE.vcxproj",
template = @"template-libHttpClient.UnitTest.142.TE.vcxproj",
output = @"libHttpClient.UnitTest.142.TE.vcxproj",
});
//libHttpClient.UnitTest.141.TE
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.UnitTest.141.TE.vcxproj",
template = @"template-libHttpClient.UnitTest.141.TE.vcxproj",
output = @"libHttpClient.UnitTest.141.TE.vcxproj",
});
//libHttpClient.110.XDK.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.110.XDK.C.vcxproj",
output = @"libHttpClient.110.XDK.Ship.C.vcxproj",
});
//libHttpClient.140.XDK.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.140.XDK.C.vcxproj",
output = @"libHttpClient.140.XDK.Ship.C.vcxproj",
});
//libHttpClient.141.XDK.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.141.XDK.C.vcxproj",
output = @"libHttpClient.141.XDK.Ship.C.vcxproj",
});
//libHttpClient.142.XDK.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.142.XDK.C.vcxproj",
output = @"libHttpClient.142.XDK.Ship.C.vcxproj",
});
//libHttpClient.140.UWP.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.140.UWP.C.vcxproj",
output = @"libHttpClient.140.UWP.Ship.C.vcxproj",
});
//libHttpClient.141.UWP.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.141.UWP.C.vcxproj",
output = @"libHttpClient.141.UWP.Ship.C.vcxproj",
});
//libHttpClient.142.UWP.Ship.Cpp
fileNodes.Add(new FileNode
{
cmake_vcxproj = @"libHttpClient.Ship.vcxproj",
template = @"template-libHttpClient.142.UWP.C.vcxproj",
output = @"libHttpClient.142.UWP.Ship.C.vcxproj",
});
foreach (FileNode fn in fileNodes)
{
var template_lines = new List<string>();
var output_lines = new List<string>();
var cmake_vcxproj_lines = new List<string>();
var cmake_vcxproj_filters_lines = new List<string>();
var cmake_vcxproj_filters_lines_filtered = new List<string>();
var cmake_vcxproj_files = new List<string>();
string cmake_vcxproj = Path.Combine(rootFolder, Path.Combine(@"Utilities\CMake\vcxprojs", fn.cmake_vcxproj));
string cmake_vcxproj_filters_name = fn.cmake_vcxproj + ".filters";
string cmake_vcxproj_filters = Path.Combine(rootFolder, Path.Combine(@"Utilities\CMake\vcxprojs", cmake_vcxproj_filters_name));
string template = Path.Combine(rootFolder, Path.Combine(@"Utilities\CMake", fn.template));
string output = Path.Combine(rootFolder, Path.Combine(@"Utilities\CMake\output", fn.output));
string outputFilterName = fn.output + ".filters";
string output_filters = Path.Combine(rootFolder, Path.Combine(@"Utilities\CMake\output", outputFilterName));
FileInfo fiInput = new FileInfo(cmake_vcxproj);
FileInfo fiInputFilters = new FileInfo(cmake_vcxproj_filters);
Console.WriteLine("inputVcxproj: " + cmake_vcxproj);
Console.WriteLine("template: " + template);
Console.WriteLine("output: " + output);
if (fiInput.Exists && fiInputFilters.Exists)
{
ReadFile(cmake_vcxproj, ref cmake_vcxproj_lines);
ReadFile(cmake_vcxproj_filters, ref cmake_vcxproj_filters_lines);
ExtractFileSection(ref cmake_vcxproj_lines, ref cmake_vcxproj_files, rootFolder, false);
ReadFile(template, ref template_lines);
ReplaceFileSection(template_lines, cmake_vcxproj_files, ref output_lines);
if(fn.cmake_vcxproj.Contains(".Ship."))
{
ReplaceProjectName(ref output_lines, fn.output);
}
Console.WriteLine("Writing " + output);
WriteFile(output_lines, output);
cmake_vcxproj_filters_lines_filtered = ProcessFiltersFile(cmake_vcxproj_filters_lines, cmake_vcxproj_filters_lines_filtered, rootFolder, fn.output);
Console.WriteLine("Writing " + output_filters);
WriteFile(cmake_vcxproj_filters_lines_filtered, output_filters);
}
else
{
Console.WriteLine("Skipping");
}
Console.WriteLine("");
}
}
private static void ReplaceProjectName(ref List<string> output_lines, string outputFileName)
{
for (int i = 0; i < output_lines.Count; i++)
{
if (output_lines[i].Contains("<ProjectName>"))
{
string projectName = outputFileName.Replace(".vcxproj", "");
output_lines[i] = " <ProjectName>" + projectName + "</ProjectName>";
}
if (output_lines[i].Contains("<ProjectGuid>"))
{
string projectGuid;
if (outputFileName.Contains("XDK"))
{
projectGuid = "{20E87245-DA60-40E5-9938-ABB445E78467}";
}
else
{
projectGuid = "{47FF466B-C455-48C0-8D89-37E3FC0897F8}";
}
output_lines[i] = " <ProjectGuid>" + projectGuid + "</ProjectGuid>";
}
}
}
public static string CaseInsenstiveReplace(
string originalString,
string oldValue,
string newValue)
{
StringComparison comparisonType = StringComparison.OrdinalIgnoreCase;
int startIndex = 0;
while (true)
{
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;
originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);
startIndex += newValue.Length;
}
return originalString;
}
private static string MakeFilePathRelative(string inputFile, string rootFolder)
{
// <ClInclude Include="C:\git\forks\xbox-live-api\Source\Services\Common\Desktop\pch.h" />
// to
// <ClInclude Include="$(MSBuildThisFileDirectory)..\..\Source\Services\Common\Desktop\pch.h" />
string filteredFile = CaseInsenstiveReplace( inputFile, rootFolder, @"$(MSBuildThisFileDirectory)..\..\");
filteredFile = filteredFile.Replace(" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\"", "");
filteredFile = filteredFile.Replace(@"..\..\Utilities\CMake\build\", "");
filteredFile = filteredFile.Replace("\" />", "\" />");
return filteredFile;
}
private static void ReplaceFileSection(
List<string> template_lines,
List<string> cmake_vcxproj_files,
ref List<string> output_lines)
{
for (int i = 0; i < template_lines.Count; i++)
{
string l = template_lines[i];
if (l.Contains("****INSERTFILES****"))
{
foreach (string s in cmake_vcxproj_files)
{
output_lines.Add(s);
}
}
else
{
output_lines.Add(l);
}
}
}
private static void WriteFile(List<string> output_lines, string outputFile)
{
FileInfo fi = new FileInfo(outputFile);
Directory.CreateDirectory(fi.DirectoryName);
using (StreamWriter outputWriter = new StreamWriter(outputFile))
{
foreach (string line in output_lines)
{
outputWriter.WriteLine(line);
}
}
}
private static List<string> ProcessFiltersFile(List<string> lines, List<string> lines_filtered, string rootFolder, string filePath)
{
rootFolder += "\\";
foreach (string line in lines)
{
string lineOutput = MakeFilePathRelative(line, rootFolder);
if(filePath.Contains(".110."))
{
lineOutput = lineOutput.Replace("ToolsVersion=\"15.0\"", "ToolsVersion=\"4.0\"");
}
lineOutput = lineOutput.Replace("<Filter>Header Files</Filter>", "<Filter>C++ Public Includes</Filter>");
lineOutput = lineOutput.Replace("<Filter Include=\"Header Files\">", "<Filter Include=\"C++ Public Includes\">");
if (filePath.Contains(".XDK."))
{
if (lineOutput.Contains("</Project>"))
{
lines_filtered.Add(@" <ItemGroup>");
lines_filtered.Add(" <None Include=\"..\\..\\Source\\Shared\\Logger\\ERA_ETW.man\">");
lines_filtered.Add(@" <Filter>C++ source\Shared\Logger</Filter>");
lines_filtered.Add(@" </None>");
lines_filtered.Add(@" </ItemGroup>");
lines_filtered.Add(@" <ItemGroup>");
lines_filtered.Add(" <ResourceCompile Include=\"..\\..\\Source\\Shared\\Logger\\ERA_ETW.rc\">");
lines_filtered.Add(@" <Filter>C++ source\Shared\Logger</Filter>");
lines_filtered.Add(@" </ResourceCompile>");
lines_filtered.Add(@" </ItemGroup>");
}
}
lines_filtered.Add(lineOutput);
}
return lines_filtered;
//// Need to sort filters file manually due to CMake bug: https://cmake.org/Bug/view.php?id=10481
//List<string> filterLines = new List<string>();
//List<List<string>> filterNodes = new List<List<string>>();
//bool captureFilters = false;
//for (int i = 0; i < lines_filtered.Count; i++)
//{
// string l1 = lines_filtered[i];
// if( l1.Contains("<ItemGroup>") )
// {
// filterLines.Add(l1);
// captureFilters = true;
// i++;
// l1 = lines_filtered[i];
// }
// if(l1.Contains("</ItemGroup>"))
// {
// var sortedList = filterNodes.OrderBy(x => x[0]);
// foreach ( var l in sortedList )
// {
// foreach( var s in l )
// {
// filterLines.Add(s);
// }
// }
// filterNodes.Clear();
// captureFilters = false;
// }
// if( captureFilters )
// {
// List<string> filter = new List<string>();
// filter.Add(lines_filtered[i]);
// filter.Add(lines_filtered[i + 1]);
// filter.Add(lines_filtered[i + 2]);
// i += 2;
// filterNodes.Add(filter);
// }
// else
// {
// filterLines.Add(l1);
// }
//}
//return filterLines;
}
private static void DiffFiles(string fileOld, string fileNew, string rootFolder)
{
FileInfo fi1 = new FileInfo(fileOld);
FileInfo fi2 = new FileInfo(fileNew);
if (!fi1.Exists)
{
Console.WriteLine("Missing: " + fileOld);
return;
}
if (!fi2.Exists)
{
Console.WriteLine("Missing: " + fileNew);
return;
}
var fileOld_lines = new List<string>();
var fileOld_files = new List<string>();
var fileOld_files_pre = new List<string>();
ReadFile(fileOld, ref fileOld_lines);
ExtractFileSection(ref fileOld_lines, ref fileOld_files_pre, rootFolder, true);
foreach (string sOld in fileOld_files_pre)
{
var s = sOld.Replace("$(MSBuildThisFileDirectory)", "");
s = s.Replace("\" />", "\" />");
s = s.Replace("<", "");
s = s.Replace("/>", "");
s = s.Replace(">", "");
s = s.Trim();
s = s.ToLower();
fileOld_files.Add(s);
}
var org_fileOld_files = new List<string>(fileOld_files);
var fileNew_lines = new List<string>();
var fileNew_files_pre = new List<string>();
var fileNew_files = new List<string>();
ReadFile(fileNew, ref fileNew_lines);
// <ClInclude Include="..\..\Include\xsapi\achievements.h" />
// <ClCompile Include="..\..\Source\Services\Achievements\achievement.cpp" />
ExtractFileSection(ref fileNew_lines, ref fileNew_files_pre, rootFolder, true);
foreach (string sNew in fileNew_files_pre)
{
var s = sNew.Replace("$(MSBuildThisFileDirectory)", "");
s = s.Replace("\" />", "\" />");
s = s.Replace("<", "");
s = s.Replace("/>", "");
s = s.Replace(">", "");
s = s.Trim();
s = s.ToLower();
fileNew_files.Add(s);
}
var org_fileNew_files = new List<string>(fileNew_files);
foreach (string sOld in fileOld_files)
{
if (sOld.Contains("achievements.h"))
{
bool contains = fileNew_files.Contains(sOld);
fileNew_files.Remove(sOld);
}
fileNew_files.Remove(sOld);
}
foreach (string sNew in org_fileNew_files)
{
fileOld_files.Remove(sNew);
}
Console.WriteLine("Diffing:");
Console.WriteLine(" " + fileOld);
Console.WriteLine(" " + fileNew);
foreach (string sOld in fileOld_files)
{
Console.WriteLine("Missing: " + sOld);
}
foreach (string sNew in fileNew_files)
{
Console.WriteLine("New: " + sNew);
}
Console.WriteLine("");
Console.WriteLine("");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Docu.Parsing.Model
{
public static class IdentifierFor
{
const string GenericTypeParameterPrefix = "`";
const string GenericMethodParamaterPrefix = "``";
const string ArrayTypeSuffix = "[]";
const char StartGenericArguments = '{';
const char EndGenericArguments = '}';
const char RefoutParameterSuffix = '@';
const string GenericTypeNamespace = "";
static Dictionary<string, Type> _nameToType;
public static TypeIdentifier Type(Type type)
{
return type.IsGenericParameter
? new TypeIdentifier(GenericMethodParamaterPrefix + type.GenericParameterPosition, GenericTypeNamespace)
: new TypeIdentifier(type.Name, type.Namespace);
}
public static TypeIdentifier ParameterType(MethodBase method, Type type)
{
if (type.IsArray)
{
var elementType = type.GetElementType();
if (elementType.IsGenericParameter)
{
return method.IsGenericMethod && method.GetGenericArguments().Any(t => t.TypeHandle.Value == elementType.TypeHandle.Value)
? new TypeIdentifier(GenericMethodParamaterPrefix + elementType.GenericParameterPosition + ArrayTypeSuffix, GenericTypeNamespace)
: new TypeIdentifier(GenericTypeParameterPrefix + elementType.GenericParameterPosition + ArrayTypeSuffix, GenericTypeNamespace);
}
}
if (type.IsGenericParameter)
{
return method.IsGenericMethod && method.GetGenericArguments().Any(t => t.TypeHandle.Value == type.TypeHandle.Value)
? new TypeIdentifier(GenericMethodParamaterPrefix + type.GenericParameterPosition, GenericTypeNamespace)
: new TypeIdentifier(GenericTypeParameterPrefix + type.GenericParameterPosition, GenericTypeNamespace);
}
return new TypeIdentifier(type.Name, type.Namespace);
}
public static MethodIdentifier Method(MethodBase method, Type type)
{
string name = method.Name;
var parameters = new List<TypeIdentifier>();
if (method.IsGenericMethod)
name += GenericMethodParamaterPrefix + method.GetGenericArguments().Length;
foreach (ParameterInfo param in method.GetParameters())
{
parameters.Add(ParameterType(method, param.ParameterType));
}
return new MethodIdentifier(name, parameters.ToArray(), method.IsStatic, method.IsPublic, method.IsConstructor, Type(type));
}
public static PropertyIdentifier Property(PropertyInfo property, Type type)
{
return new PropertyIdentifier(property.Name, property.CanRead, property.CanWrite, Type(type));
}
public static FieldIdentifier Field(FieldInfo field, Type type)
{
return new FieldIdentifier(field.Name, Type(type));
}
public static EventIdentifier Event(EventInfo ev, Type type)
{
return new EventIdentifier(ev.Name, Type(type));
}
public static NamespaceIdentifier Namespace(string ns)
{
return new NamespaceIdentifier(ns);
}
public static Identifier XmlString(string name)
{
char prefix = name[0];
string trimmedName = name.Substring(2);
if (prefix == 'T') return TypeString(trimmedName);
if (prefix == 'N') return Namespace(trimmedName);
if (prefix == 'M') return MethodName(trimmedName);
if (prefix == 'P') return new PropertyIdentifier(GetMethodName(trimmedName), false, false, TypeString(GetTypeName(trimmedName)));
if (prefix == 'E') return new EventIdentifier(GetMethodName(trimmedName), TypeString(GetTypeName(trimmedName)));
if (prefix == 'F') return new FieldIdentifier(GetMethodName(trimmedName), TypeString(GetTypeName(trimmedName)));
throw new UnsupportedDocumentationMemberException(name);
}
static MethodIdentifier MethodName(string name)
{
string typeName = GetTypeName(name);
string methodName = GetMethodName(name);
// Constructors in XML has name #ctor but in assembly .ctor
if (methodName == "#ctor")
{
methodName = ".ctor";
}
List<TypeIdentifier> parameters = GetMethodParameters(name);
return new MethodIdentifier(methodName, parameters.ToArray(), false, false, methodName == ".ctor", TypeString(typeName));
}
static TypeIdentifier TypeString(string name)
{
return name.Contains(".")
? new TypeIdentifier(name.Substring(name.LastIndexOf('.') + 1), name.Substring(0, name.LastIndexOf('.')))
: new TypeIdentifier(name, "Unknown");
}
static string GetTypeName(string fullName)
{
string name = fullName;
if (name.EndsWith(")"))
{
// has parameters, so strip them off
name = name.Substring(0, name.IndexOf("("));
}
return name.Substring(0, name.LastIndexOf("."));
}
static string GetMethodName(string fullName)
{
string name = fullName;
if (name.EndsWith(")"))
{
// has parameters, so strip them off
name = name.Substring(0, name.IndexOf("("));
}
return name.Substring(name.LastIndexOf(".") + 1);
}
static List<TypeIdentifier> GetMethodParameters(string fullName)
{
var parameters = new List<TypeIdentifier>();
if (!fullName.EndsWith(")")) return parameters;
BuildTypeLookup();
int firstCharAfterParen = fullName.IndexOf("(") + 1;
string paramList = fullName.Substring(firstCharAfterParen, fullName.Length - firstCharAfterParen - 1);
foreach (string paramName in ExtractMethodArgumentTypes(paramList))
{
if (IsGenericArgument(paramName))
{
parameters.Add(new TypeIdentifier(paramName, GenericTypeNamespace));
continue;
}
string typeNameToFind = paramName;
int startOfGenericArguments = paramName.IndexOf(StartGenericArguments);
if (startOfGenericArguments > 0)
{
string nonGenericPartOfTypeName = paramName.Substring(0, startOfGenericArguments);
int endOfGenericArguments = paramName.LastIndexOf(EndGenericArguments);
int lengthOfGenericArgumentsSection = endOfGenericArguments - startOfGenericArguments - 1;
string genericArgumentsSection = paramName.Substring(startOfGenericArguments + 1, lengthOfGenericArgumentsSection);
int countOfGenericParametersForType = CountOfGenericArguments(genericArgumentsSection);
typeNameToFind = nonGenericPartOfTypeName + GenericTypeParameterPrefix + countOfGenericParametersForType;
}
Type paramType;
bool isArray = typeNameToFind.EndsWith(ArrayTypeSuffix);
if (isArray) typeNameToFind = typeNameToFind.Substring(0, typeNameToFind.Length - 2);
if (_nameToType.TryGetValue(typeNameToFind, out paramType))
{
if (isArray) paramType = paramType.MakeArrayType();
parameters.Add(Type(paramType));
}
}
return parameters;
}
static int CountOfGenericArguments(string genericArguments)
{
int count = 1;
int startPosition = 0;
while (startPosition < genericArguments.Length)
{
int positionOfInterestingChar = genericArguments.IndexOfAny(new[] { StartGenericArguments, ',' }, startPosition);
if (positionOfInterestingChar < 0)
{
return count;
}
if (genericArguments[positionOfInterestingChar] == StartGenericArguments)
{
startPosition = IndexAfterGenericArguments(genericArguments, positionOfInterestingChar);
}
else
{
++count;
startPosition = positionOfInterestingChar + 1;
}
}
return count;
}
static bool IsGenericArgument(string parameter)
{
return parameter.StartsWith(GenericMethodParamaterPrefix) || parameter.StartsWith(GenericTypeParameterPrefix);
}
static void BuildTypeLookup()
{
if (_nameToType != null) return;
_nameToType = new Dictionary<string, Type>();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (Type type in assembly.GetTypes())
{
if (type.FullName != null)
_nameToType[type.FullName] = type;
}
}
catch (ReflectionTypeLoadException ex)
{
Console.WriteLine("Could not load types of assembly '{0}'.{1}{2}",
assembly.FullName, Environment.NewLine, ex.InnerException);
}
}
}
public static IEnumerable<string> ExtractMethodArgumentTypes(string methodParameters)
{
int startPosition = 0;
while (startPosition < methodParameters.Length)
{
int positionOfInterestingChar = methodParameters.IndexOfAny(new[] { StartGenericArguments, ',' }, startPosition);
if (positionOfInterestingChar < 0)
{
if (startPosition == 0)
{
yield return methodParameters.TrimEnd(RefoutParameterSuffix);
}
else
{
yield return methodParameters.Substring(startPosition).TrimEnd(RefoutParameterSuffix);
}
startPosition = methodParameters.Length;
}
else
{
if (methodParameters[positionOfInterestingChar] == StartGenericArguments)
{
//Generic parameter
positionOfInterestingChar = IndexAfterGenericArguments(methodParameters, positionOfInterestingChar);
}
yield return methodParameters.Substring(startPosition, positionOfInterestingChar - startPosition).TrimEnd(RefoutParameterSuffix);
startPosition = positionOfInterestingChar + 1;
}
}
}
static int IndexAfterGenericArguments(string parameterList, int startPosition)
{
// - may contain ',' for multiple generic arguments for the single parameter type: IDictionary<KEY,VALUE>
// - may contain '{' for generics of generics: IEnumerable<Nullable<int>>
int genericNesting = 1;
while (genericNesting > 0)
{
startPosition = parameterList.IndexOfAny(new[] { StartGenericArguments, EndGenericArguments }, startPosition + 1);
genericNesting += (parameterList[startPosition] == StartGenericArguments) ? 1 : -1;
}
//position needs to be the index AFTER the complete parameter string
startPosition = startPosition + 1;
return startPosition;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Factotum
{
public partial class PipeScheduleView : Form
{
// ----------------------------------------------------------------------
// Initialization
// ----------------------------------------------------------------------
// Form constructor
public PipeScheduleView()
{
InitializeComponent();
// Take care of settings that are not as easily managed in the designer.
InitializeControls();
}
// Take care of the non-default DataGridView settings that are not as easily managed
// in the designer.
private void InitializeControls()
{
}
// Set the status filter to show active tools by default
// and update the tool selector combo box
private void PipeScheduleView_Load(object sender, EventArgs e)
{
// Apply the current filters and set the selector row.
// Passing a null selects the first row if there are any rows.
UpdateSelector(null);
// Now that we have some rows and columns, we can do some customization.
CustomizeGrid();
// Need to do this because the customization clears the row selection.
SelectGridRow(null);
// Wire up the handler for the Entity changed event
EPipeSchedule.Changed += new EventHandler<EntityChangedEventArgs>(EPipeSchedule_Changed);
}
private void PipeScheduleView_FormClosed(object sender, FormClosedEventArgs e)
{
EPipeSchedule.Changed -= new EventHandler<EntityChangedEventArgs>(EPipeSchedule_Changed);
}
// ----------------------------------------------------------------------
// Event Handlers
// ----------------------------------------------------------------------
// If any of this type of entity object was saved or deleted, we want to update the selector
// The event args contain the ID of the entity that was added, mofified or deleted.
void EPipeSchedule_Changed(object sender, EntityChangedEventArgs e)
{
UpdateSelector(e.ID);
}
// Handle the user's decision to edit the current tool
private void EditCurrentSelection()
{
// Make sure there's a row selected
if (dgvPipeSchedulesList.SelectedRows.Count != 1) return;
Guid? currentEditItem = (Guid?)(dgvPipeSchedulesList.SelectedRows[0].Cells["ID"].Value);
// First check to see if an instance of the form set to the selected ID already exists
if (!Globals.CanActivateForm(this, "PipeScheduleEdit", currentEditItem))
{
// Open the edit form with the currently selected ID.
PipeScheduleEdit frm = new PipeScheduleEdit(currentEditItem);
frm.MdiParent = this.MdiParent;
frm.Show();
}
}
// This handles the datagridview double-click as well as button click
void btnEdit_Click(object sender, System.EventArgs e)
{
EditCurrentSelection();
}
private void dgvPipeSchedulesList_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
EditCurrentSelection();
}
// Handle the user's decision to add a new tool
private void btnAdd_Click(object sender, EventArgs e)
{
PipeScheduleEdit frm = new PipeScheduleEdit();
frm.MdiParent = this.MdiParent;
frm.Show();
}
// Handle the user's decision to delete the selected tool
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvPipeSchedulesList.SelectedRows.Count != 1)
{
MessageBox.Show("Please select a Calibration Block to delete first.", "Factotum");
return;
}
Guid? currentEditItem = (Guid?)(dgvPipeSchedulesList.SelectedRows[0].Cells["ID"].Value);
if (Globals.IsFormOpen(this, "PipeScheduleEdit", currentEditItem))
{
MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum");
return;
}
EPipeSchedule PipeSchedule = new EPipeSchedule(currentEditItem);
PipeSchedule.Delete(true);
if (PipeSchedule.PipeScheduleErrMsg != null)
{
MessageBox.Show(PipeSchedule.PipeScheduleErrMsg, "Factotum");
PipeSchedule.PipeScheduleErrMsg = null;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
// ----------------------------------------------------------------------
// Private utilities
// ----------------------------------------------------------------------
// Update the tool selector combo box by filling its items based on current data and filters.
// Then set the currently displayed item to that of the supplied ID.
// If the supplied ID isn't on the list because of the current filter state, just show the
// first item if there is one.
private void UpdateSelector(Guid? id)
{
// Save the sort specs if there are any, so we can re-apply them
SortOrder sortOrder = dgvPipeSchedulesList.SortOrder;
int sortCol = -1;
if (sortOrder != SortOrder.None)
sortCol = dgvPipeSchedulesList.SortedColumn.Index;
// Update the grid view selector
DataView dv = EPipeSchedule.GetDefaultDataView();
dgvPipeSchedulesList.DataSource = dv;
// Re-apply the sort specs
if (sortOrder == SortOrder.Ascending)
dgvPipeSchedulesList.Sort(dgvPipeSchedulesList.Columns[sortCol], ListSortDirection.Ascending);
else if (sortOrder == SortOrder.Descending)
dgvPipeSchedulesList.Sort(dgvPipeSchedulesList.Columns[sortCol], ListSortDirection.Descending);
// Select the current row
SelectGridRow(id);
}
private void CustomizeGrid()
{
// Apply a default sort
dgvPipeSchedulesList.Sort(dgvPipeSchedulesList.Columns["PipeScheduleSchedule"], ListSortDirection.Ascending);
// Fix up the column headings
dgvPipeSchedulesList.Columns["PipeScheduleSchedule"].HeaderText = "Schedule";
dgvPipeSchedulesList.Columns["PipeScheduleNomDia"].HeaderText = "Nominal Diameter";
dgvPipeSchedulesList.Columns["PipeScheduleOd"].HeaderText = "Outside Diameter";
dgvPipeSchedulesList.Columns["PipeScheduleNomWall"].HeaderText = "Nominal Wall";
// Hide some columns
dgvPipeSchedulesList.Columns["ID"].Visible = false;
dgvPipeSchedulesList.Columns["PipeScheduleIsLclChg"].Visible = false;
dgvPipeSchedulesList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
}
// Select the row with the specified ID if it is currently displayed and scroll to it.
// If the ID is not in the list,
private void SelectGridRow(Guid? id)
{
bool found = false;
int rows = dgvPipeSchedulesList.Rows.Count;
if (rows == 0) return;
int r = 0;
DataGridViewCell firstCell = dgvPipeSchedulesList.FirstDisplayedCell;
if (id != null)
{
// Find the row with the specified key id and select it.
for (r = 0; r < rows; r++)
{
if ((Guid?)dgvPipeSchedulesList.Rows[r].Cells["ID"].Value == id)
{
dgvPipeSchedulesList.CurrentCell = dgvPipeSchedulesList[firstCell.ColumnIndex, r];
dgvPipeSchedulesList.Rows[r].Selected = true;
found = true;
break;
}
}
}
if (found)
{
if (!dgvPipeSchedulesList.Rows[r].Displayed)
{
// Scroll to the selected row if the ID was in the list.
dgvPipeSchedulesList.FirstDisplayedScrollingRowIndex = r;
}
}
else
{
// Select the first item
dgvPipeSchedulesList.CurrentCell = firstCell;
dgvPipeSchedulesList.Rows[0].Selected = true;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace QRCode
{
public static class BitmapGenerator
{
public static int GetSize(int Version)
{
return (((Version-1)*4)+21);
}
public static int?[,] CreateNew(int Version)
{
int size = GetSize(Version);
int?[,] matrix = new int?[size, size];
AddFinderPatterns(size, matrix);
AddAlignmentPatterns(Version, matrix);
AddTimingPatterns(size, matrix);
AddDarkModule(size, matrix);
AddReservedFormatInformationArea(Version, size, matrix);
return matrix;
}
public static void SavePNG(string filename, int size, int?[,] matrix)
{
int multiplier = 2;
Bitmap bmp = new Bitmap(size*multiplier, size*multiplier);
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
Color color = (matrix[col, row] == 1) ? Color.Black : Color.White;
for (int moduleX = 0; moduleX < multiplier; moduleX++)
for (int moduleY = 0; moduleY < multiplier; moduleY++)
bmp.SetPixel(col+moduleX, row+moduleY, color);
}
}
bmp.Save(filename);
}
public static void AddDataBits(int size, int?[,] matrix, string dataBits)
{
// start in bottom right corner and go up then over two and down
// when in upward movment, place bits in zig-zag from
// bottom right to bottom left then up one and right and then left
// the only exception is when on x = vertical timing row, skip it
// zig-zag loop
int currCharIndex = 0;
for (int x = size-1; x > 0; x-=(x == 8 ? 3 : 2)) {
bool directionUp = ((((size-1) - x) / 2) % 2) == 0;
for (int y = (directionUp ? (size-1) : 0); directionUp ? y >= 0 : y < size; y+=(directionUp ? -1 : 1)) {
for (int offset = 0; offset < 2; offset++)
if (matrix[x-offset, y] == null)
matrix[x-offset, y] = int.Parse(dataBits[currCharIndex++].ToString());
}
}
}
public static void Draw(int?[,] matrix)
{
int size = (int)Math.Sqrt(matrix.Length);
Console.WriteLine("\nMatrix");
Console.WriteLine("~~~~~~");
Console.WriteLine("Size: " + size);
Console.WriteLine();
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
char moduleChar = ' ';
if (matrix[x,y] != null)
switch (matrix[x,y]) {
case 0:
moduleChar = 'o';
break;
case 1:
moduleChar = 'x';
break;
case -1:
moduleChar = '~';
break;
default:
break;
}
Console.Write(moduleChar);
}
Console.WriteLine();
}
}
public static void AddDarkModule(int size, int?[,] matrix)
{
matrix[8, size-8] = 0;
}
public static void AddReservedFormatInformationArea(int version, int size, int?[,] matrix)
{
// reserved area will be marked by -1
// Format Information Area is a set for four strips
for (int y = 0; y < 9; y++) {
matrix[8, size-1-Math.Min(y, 7)] = matrix[8, size-1-Math.Min(y, 7)] ?? -1; // bottom left, small vertical strip touching Dark Module
matrix[8, y] = matrix[8, y] ?? -1; // top left, vertical strip
}
for (int x = 0; x < 8; x++) {
matrix[size-1-x, 8] = -1; // top right, horizontal strip
if (matrix[x, 8] == null)
matrix[x, 8] = -1; // top left, horizontal strip
}
// version >= 7 have addtional Version Information Area
if (version >= 7) {
// add a 3x6 box on both opposing finder corners
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
matrix[j, size-9-i] = -1;
matrix[size-9-i, j] = -1;
}
}
}
}
public static void AddTimingPatterns(int size, int?[,] matrix)
{
// draw dotted line connecting finder patterns
for (int i = 6; i < size - 6; i++) {
matrix[i, 6] = (i % 2);
matrix[6, i] = (i % 2);
}
}
public static void AddAlignmentPatterns(int Version, int?[,] matrix)
{
/*
Draw alignment patterns in all combinations of alignment patterns for the given version
Except for the corners where the location finders are (0, 0), (max, 0), (0, max)
*/
if (!Data.AlignmentPatternLocations.ContainsKey(Version)) return;
int[] locations = Data.AlignmentPatternLocations[Version];
int numLocations = locations.Length;
for (int y = 0; y < numLocations; y++) {
for (int x = 0; x < numLocations; x++) {
bool isFinderCorner =
(x == 0 && y == 0) ||
(x == 0 && y == numLocations-1) ||
(x == numLocations-1 && y == 0);
if (!isFinderCorner) {
DrawAlignmentPattern(matrix, locations[x], locations[y]);
}
}
}
}
public static void DrawAlignmentPattern(int?[,] matrix, int xCenter, int yCenter)
{
for (int y = yCenter - 2; y <= yCenter + 2; y++) {
for (int x = xCenter - 2; x <= xCenter + 2; x++) {
bool drawDot =
((x == (xCenter-1) || x == (xCenter+1)) && (y >= yCenter-1 && y <= yCenter+1)) ||
((x == xCenter) && (y == (yCenter-1) || y == (yCenter+1)));
matrix[x, y] = drawDot ? 1 : 0;
}
}
}
public static void AddFinderPatterns(int size, int?[,] matrix)
{
// a finder patter is a set of three nested boxes
// 7x7 black with 5x5 white with 3x3 black
// finder patterns belong in three corners: top-left, top-right, bottom-left
/*
The top-left finder pattern's top left corner is always placed at (0,0).
The top-right finder pattern's top LEFT corner is always placed at ([(((V-1)*4)+21) - 7], 0)
The bottom-left finder pattern's top LEFT corner is always placed at (0,[(((V-1)*4)+21) - 7])
*/
int OppositeCornerOffset = size - 1 - 7;
for (int y = 0; y < 7; y++) {
// Vertical Separators
matrix[7, y] = 1;
matrix[OppositeCornerOffset, y] = 1;
matrix[7, OppositeCornerOffset + y + 1] = 1;
for (int x = 0; x < 7; x++) {
// Horizontal Separators
matrix[OppositeCornerOffset + x + 1, 7] = 1;
matrix[x, 7] = 1;
matrix[x, OppositeCornerOffset] = 1;
bool drawDot = (
(((x == 1) || (x == 5)) && ((y >= 1) && (y <= 5))) || // vertical lines
(((y == 1) || (y == 5)) && ((x >= 1) && (x <= 5))) || // horiztonal lines
(((x == 1) && (y == 1)) || ((x == 5) && (y == 5)) || // corners
((x == 1) && (y == 5)) || ((x == 5) && (y == 1)))
);
matrix[x, y] = drawDot ? 1 : 0;
matrix[x, size - 1 - y] = drawDot ? 1 : 0;
matrix[size - 1 - x, y] = drawDot ? 1 : 0;
}
}
// Separator corners
matrix[7, 7] = 1;
matrix[7, OppositeCornerOffset] = 1;
matrix[OppositeCornerOffset, 7] = 1;
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Infoplus.Api;
using Infoplus.Model;
using Infoplus.Client;
using System.Reflection;
namespace Infoplus.Test
{
/// <summary>
/// Class for testing Customer
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class CustomerTests
{
// TODO uncomment below to declare an instance variable for Customer
//private Customer instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of Customer
//instance = new Customer();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of Customer
/// </summary>
[Test]
public void CustomerInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" Customer
//Assert.IsInstanceOfType<Customer> (instance, "variable 'instance' is a Customer");
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Test]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'LobId'
/// </summary>
[Test]
public void LobIdTest()
{
// TODO unit test for the property 'LobId'
}
/// <summary>
/// Test the property 'CustomerNo'
/// </summary>
[Test]
public void CustomerNoTest()
{
// TODO unit test for the property 'CustomerNo'
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Test]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
/// <summary>
/// Test the property 'Attention'
/// </summary>
[Test]
public void AttentionTest()
{
// TODO unit test for the property 'Attention'
}
/// <summary>
/// Test the property 'Street'
/// </summary>
[Test]
public void StreetTest()
{
// TODO unit test for the property 'Street'
}
/// <summary>
/// Test the property 'Street2'
/// </summary>
[Test]
public void Street2Test()
{
// TODO unit test for the property 'Street2'
}
/// <summary>
/// Test the property 'Street3Province'
/// </summary>
[Test]
public void Street3ProvinceTest()
{
// TODO unit test for the property 'Street3Province'
}
/// <summary>
/// Test the property 'City'
/// </summary>
[Test]
public void CityTest()
{
// TODO unit test for the property 'City'
}
/// <summary>
/// Test the property 'State'
/// </summary>
[Test]
public void StateTest()
{
// TODO unit test for the property 'State'
}
/// <summary>
/// Test the property 'ZipCode'
/// </summary>
[Test]
public void ZipCodeTest()
{
// TODO unit test for the property 'ZipCode'
}
/// <summary>
/// Test the property 'Country'
/// </summary>
[Test]
public void CountryTest()
{
// TODO unit test for the property 'Country'
}
/// <summary>
/// Test the property 'Phone'
/// </summary>
[Test]
public void PhoneTest()
{
// TODO unit test for the property 'Phone'
}
/// <summary>
/// Test the property 'Fax'
/// </summary>
[Test]
public void FaxTest()
{
// TODO unit test for the property 'Fax'
}
/// <summary>
/// Test the property 'Email'
/// </summary>
[Test]
public void EmailTest()
{
// TODO unit test for the property 'Email'
}
/// <summary>
/// Test the property 'BossBranch'
/// </summary>
[Test]
public void BossBranchTest()
{
// TODO unit test for the property 'BossBranch'
}
/// <summary>
/// Test the property 'PackageCarrierId'
/// </summary>
[Test]
public void PackageCarrierIdTest()
{
// TODO unit test for the property 'PackageCarrierId'
}
/// <summary>
/// Test the property 'TruckCarrierId'
/// </summary>
[Test]
public void TruckCarrierIdTest()
{
// TODO unit test for the property 'TruckCarrierId'
}
/// <summary>
/// Test the property 'WeightBreak'
/// </summary>
[Test]
public void WeightBreakTest()
{
// TODO unit test for the property 'WeightBreak'
}
/// <summary>
/// Test the property 'Sector'
/// </summary>
[Test]
public void SectorTest()
{
// TODO unit test for the property 'Sector'
}
/// <summary>
/// Test the property 'Division'
/// </summary>
[Test]
public void DivisionTest()
{
// TODO unit test for the property 'Division'
}
/// <summary>
/// Test the property 'CostCenter'
/// </summary>
[Test]
public void CostCenterTest()
{
// TODO unit test for the property 'CostCenter'
}
/// <summary>
/// Test the property 'County'
/// </summary>
[Test]
public void CountyTest()
{
// TODO unit test for the property 'County'
}
/// <summary>
/// Test the property 'Area'
/// </summary>
[Test]
public void AreaTest()
{
// TODO unit test for the property 'Area'
}
/// <summary>
/// Test the property 'CustomerType'
/// </summary>
[Test]
public void CustomerTypeTest()
{
// TODO unit test for the property 'CustomerType'
}
/// <summary>
/// Test the property 'MassLevel'
/// </summary>
[Test]
public void MassLevelTest()
{
// TODO unit test for the property 'MassLevel'
}
/// <summary>
/// Test the property 'MassFactor'
/// </summary>
[Test]
public void MassFactorTest()
{
// TODO unit test for the property 'MassFactor'
}
/// <summary>
/// Test the property 'PriceLevel'
/// </summary>
[Test]
public void PriceLevelTest()
{
// TODO unit test for the property 'PriceLevel'
}
/// <summary>
/// Test the property 'OpenDate'
/// </summary>
[Test]
public void OpenDateTest()
{
// TODO unit test for the property 'OpenDate'
}
/// <summary>
/// Test the property 'CloseDate'
/// </summary>
[Test]
public void CloseDateTest()
{
// TODO unit test for the property 'CloseDate'
}
/// <summary>
/// Test the property 'RestrictionPercent'
/// </summary>
[Test]
public void RestrictionPercentTest()
{
// TODO unit test for the property 'RestrictionPercent'
}
/// <summary>
/// Test the property 'ExternalId'
/// </summary>
[Test]
public void ExternalIdTest()
{
// TODO unit test for the property 'ExternalId'
}
/// <summary>
/// Test the property 'CycleDate'
/// </summary>
[Test]
public void CycleDateTest()
{
// TODO unit test for the property 'CycleDate'
}
/// <summary>
/// Test the property 'Manager'
/// </summary>
[Test]
public void ManagerTest()
{
// TODO unit test for the property 'Manager'
}
/// <summary>
/// Test the property 'AlternateInventory'
/// </summary>
[Test]
public void AlternateInventoryTest()
{
// TODO unit test for the property 'AlternateInventory'
}
/// <summary>
/// Test the property 'Pin'
/// </summary>
[Test]
public void PinTest()
{
// TODO unit test for the property 'Pin'
}
/// <summary>
/// Test the property 'FaxGone'
/// </summary>
[Test]
public void FaxGoneTest()
{
// TODO unit test for the property 'FaxGone'
}
/// <summary>
/// Test the property 'Residential'
/// </summary>
[Test]
public void ResidentialTest()
{
// TODO unit test for the property 'Residential'
}
/// <summary>
/// Test the property 'CsrBranch'
/// </summary>
[Test]
public void CsrBranchTest()
{
// TODO unit test for the property 'CsrBranch'
}
/// <summary>
/// Test the property 'ExtrinsicText1'
/// </summary>
[Test]
public void ExtrinsicText1Test()
{
// TODO unit test for the property 'ExtrinsicText1'
}
/// <summary>
/// Test the property 'ExtrinsicText2'
/// </summary>
[Test]
public void ExtrinsicText2Test()
{
// TODO unit test for the property 'ExtrinsicText2'
}
/// <summary>
/// Test the property 'ExtrinsicText3'
/// </summary>
[Test]
public void ExtrinsicText3Test()
{
// TODO unit test for the property 'ExtrinsicText3'
}
/// <summary>
/// Test the property 'ExtrinsicNumber1'
/// </summary>
[Test]
public void ExtrinsicNumber1Test()
{
// TODO unit test for the property 'ExtrinsicNumber1'
}
/// <summary>
/// Test the property 'ExtrinsicNumber2'
/// </summary>
[Test]
public void ExtrinsicNumber2Test()
{
// TODO unit test for the property 'ExtrinsicNumber2'
}
/// <summary>
/// Test the property 'ExtrinsicDecimal1'
/// </summary>
[Test]
public void ExtrinsicDecimal1Test()
{
// TODO unit test for the property 'ExtrinsicDecimal1'
}
/// <summary>
/// Test the property 'ExtrinsicDecimal2'
/// </summary>
[Test]
public void ExtrinsicDecimal2Test()
{
// TODO unit test for the property 'ExtrinsicDecimal2'
}
/// <summary>
/// Test the property 'ModifyDate'
/// </summary>
[Test]
public void ModifyDateTest()
{
// TODO unit test for the property 'ModifyDate'
}
/// <summary>
/// Test the property 'OmsCustomerId'
/// </summary>
[Test]
public void OmsCustomerIdTest()
{
// TODO unit test for the property 'OmsCustomerId'
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
namespace SteamTrade
{
public class TradeManager
{
private const int MaxGapTimeDefault = 15;
private const int MaxTradeTimeDefault = 180;
private const int TradePollingIntervalDefault = 800;
private readonly string ApiKey;
private readonly SteamWeb SteamWeb;
private DateTime tradeStartTime;
private DateTime lastOtherActionTime;
private DateTime lastTimeoutMessage;
private Task<Inventory> myInventoryTask;
private Task<Inventory> otherInventoryTask;
/// <summary>
/// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class.
/// </summary>
/// <param name='apiKey'>
/// The Steam Web API key. Cannot be null.
/// </param>
/// <param name="steamWeb">
/// The SteamWeb instances for this bot
/// </param>
public TradeManager (string apiKey, SteamWeb steamWeb)
{
if (apiKey == null)
throw new ArgumentNullException ("apiKey");
if (steamWeb == null)
throw new ArgumentNullException ("steamWeb");
SetTradeTimeLimits (MaxTradeTimeDefault, MaxGapTimeDefault, TradePollingIntervalDefault);
ApiKey = apiKey;
SteamWeb = steamWeb;
}
#region Public Properties
/// <summary>
/// Gets or the maximum trading time the bot will take in seconds.
/// </summary>
/// <value>
/// The maximum trade time.
/// </value>
public int MaxTradeTimeSec
{
get;
private set;
}
/// <summary>
/// Gets or the maxmium amount of time the bot will wait between actions.
/// </summary>
/// <value>
/// The maximum action gap.
/// </value>
public int MaxActionGapSec
{
get;
private set;
}
/// <summary>
/// Gets the Trade polling interval in milliseconds.
/// </summary>
public int TradePollingInterval
{
get;
private set;
}
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
/// <value>
/// The bot's inventory fetched via Steam Web API.
/// </value>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the inventory of the other trade partner.
/// </summary>
/// <value>
/// The other trade partner's inventory fetched via Steam Web API.
/// </value>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets or sets a value indicating whether the trade thread running.
/// </summary>
/// <value>
/// <c>true</c> if the trade thread running; otherwise, <c>false</c>.
/// </value>
public bool IsTradeThreadRunning
{
get;
internal set;
}
#endregion Public Properties
#region Public Events
/// <summary>
/// Occurs when the trade times out because either the user didn't complete an
/// action in a set amount of time, or they took too long with the whole trade.
/// </summary>
public EventHandler OnTimeout;
#endregion Public Events
#region Public Methods
/// <summary>
/// Sets the trade time limits.
/// </summary>
/// <param name='maxTradeTime'>
/// Max trade time in seconds.
/// </param>
/// <param name='maxActionGap'>
/// Max gap between user action in seconds.
/// </param>
/// <param name='pollingInterval'>The trade polling interval in milliseconds.</param>
public void SetTradeTimeLimits (int maxTradeTime, int maxActionGap, int pollingInterval)
{
MaxTradeTimeSec = maxTradeTime;
MaxActionGapSec = maxActionGap;
TradePollingInterval = pollingInterval;
}
/// <summary>
/// Creates a trade object and returns it for use.
/// Call <see cref="InitializeTrade"/> before using this method.
/// </summary>
/// <returns>
/// The trade object to use to interact with the Steam trade.
/// </returns>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// If the needed inventories are <c>null</c> then they will be fetched.
/// </remarks>
public Trade CreateTrade (SteamID me, SteamID other)
{
if (otherInventoryTask == null || myInventoryTask == null)
InitializeTrade (me, other);
var t = new Trade (me, other, SteamWeb, myInventoryTask, otherInventoryTask);
t.OnClose += delegate
{
IsTradeThreadRunning = false;
};
return t;
}
/// <summary>
/// Stops the trade thread.
/// </summary>
/// <remarks>
/// Also, nulls out the inventory objects so they have to be fetched
/// again if a new trade is started.
/// </remarks>
public void StopTrade ()
{
// TODO: something to check that trade was the Trade returned from CreateTrade
otherInventoryTask = null;
myInventoryTask = null;
IsTradeThreadRunning = false;
}
/// <summary>
/// Fetchs the inventories of both the bot and the other user as well as the TF2 item schema.
/// </summary>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// This should be done anytime a new user is traded with or the inventories are out of date. It should
/// be done sometime before calling <see cref="CreateTrade"/>.
/// </remarks>
public void InitializeTrade (SteamID me, SteamID other)
{
// fetch other player's inventory from the Steam API.
otherInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(other.ConvertToUInt64(), ApiKey, SteamWeb));
//if (OtherInventory == null)
//{
// throw new InventoryFetchException (other);
//}
// fetch our inventory from the Steam API.
myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(me.ConvertToUInt64(), ApiKey, SteamWeb));
// check that the schema was already successfully fetched
if (Trade.CurrentSchema == null)
Trade.CurrentSchema = Schema.FetchSchema (ApiKey);
if (Trade.CurrentSchema == null)
throw new TradeException ("Could not download the latest item schema.");
}
#endregion Public Methods
/// <summary>
/// Starts the actual trade-polling thread.
/// </summary>
public void StartTradeThread (Trade trade)
{
// initialize data to use in thread
tradeStartTime = DateTime.Now;
lastOtherActionTime = DateTime.Now;
lastTimeoutMessage = DateTime.Now.AddSeconds(-1000);
var pollThread = new Thread (() =>
{
IsTradeThreadRunning = true;
DebugPrint ("Trade thread starting.");
// main thread loop for polling
try
{
while(IsTradeThreadRunning)
{
bool action = trade.Poll();
if(action)
lastOtherActionTime = DateTime.Now;
if (trade.HasTradeEnded || CheckTradeTimeout(trade))
{
IsTradeThreadRunning = false;
break;
}
Thread.Sleep(TradePollingInterval);
}
}
catch(Exception ex)
{
// TODO: find a new way to do this w/o the trade events
//if (OnError != null)
// OnError("Error Polling Trade: " + e);
// ok then we should stop polling...
IsTradeThreadRunning = false;
DebugPrint("[TRADEMANAGER] general error caught: " + ex);
trade.FireOnErrorEvent("Unknown error occurred: " + ex.ToString());
}
finally
{
DebugPrint("Trade thread shutting down.");
try
{
try //Yikes, that's a lot of nested 'try's. Is there some way to clean this up?
{
if(trade.HasTradeCompletedOk)
trade.FireOnSuccessEvent();
else if(trade.IsTradeAwaitingConfirmation)
trade.FireOnAwaitingConfirmation();
}
finally
{
//Make sure OnClose is always fired after OnSuccess, even if OnSuccess throws an exception
//(which it NEVER should, but...)
trade.FireOnCloseEvent();
}
}
catch(Exception ex)
{
trade.FireOnErrorEvent("Unknown error occurred DURING CLEANUP(!?): " + ex.ToString());
}
}
});
pollThread.Start();
}
private bool CheckTradeTimeout (Trade trade)
{
// User has accepted the trade. Disregard time out.
if (trade.OtherUserAccepted)
return false;
var now = DateTime.Now;
DateTime actionTimeout = lastOtherActionTime.AddSeconds (MaxActionGapSec);
int untilActionTimeout = (int)Math.Round ((actionTimeout - now).TotalSeconds);
DebugPrint (String.Format ("{0} {1}", actionTimeout, untilActionTimeout));
DateTime tradeTimeout = tradeStartTime.AddSeconds (MaxTradeTimeSec);
int untilTradeTimeout = (int)Math.Round ((tradeTimeout - now).TotalSeconds);
double secsSinceLastTimeoutMessage = (now - lastTimeoutMessage).TotalSeconds;
if (untilActionTimeout <= 0 || untilTradeTimeout <= 0)
{
DebugPrint ("timed out...");
if (OnTimeout != null)
{
OnTimeout (this, null);
}
trade.CancelTrade ();
return true;
}
else if (untilActionTimeout <= 20 && secsSinceLastTimeoutMessage >= 10)
{
try
{
trade.SendMessage("Are You AFK? The trade will be canceled in " + untilActionTimeout + " seconds if you don't do something.");
}
catch { }
lastTimeoutMessage = now;
}
return false;
}
[Conditional ("DEBUG_TRADE_MANAGER")]
private static void DebugPrint (string output)
{
// I don't really want to add the Logger as a dependecy to TradeManager so I
// print using the console directly. To enable this for debugging put this:
// #define DEBUG_TRADE_MANAGER
// at the first line of this file.
System.Console.WriteLine (output);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// An <see cref="IHtmlHelper"/> for Linq expressions.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
public interface IHtmlHelper<TModel> : IHtmlHelper
{
/// <summary>
/// Gets the current view data.
/// </summary>
new ViewDataDictionary<TModel> ViewData { get; }
/// <summary>
/// Returns an <input> element of type "checkbox" with value "true" and an <input> element of type
/// "hidden" with value "false" for the specified <paramref name="expression"/>. Adds a "checked" attribute to
/// the "checkbox" element based on the first non-<c>null</c> value found in:
/// the <paramref name="htmlAttributes"/> dictionary entry with key "checked", or
/// the <see cref="ActionContext.ModelState"/> entry with full name.
/// If <paramref name="expression"/> evaluates to a non-<c>null</c> value, instead uses the first
/// non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>.
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the checkbox element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the <input> elements.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set checkbox element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set checkbox element's "id" attribute.
/// </remarks>
IHtmlContent CheckBoxFor(Expression<Func<TModel, bool>> expression, object htmlAttributes);
/// <summary>
/// Returns HTML markup for the <paramref name="expression"/>, using a display template, specified HTML field
/// name, and additional view data. The template is found using the <paramref name="templateName"/> or the
/// <paramref name="expression"/>'s <see cref="ModelBinding.ModelMetadata"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="templateName">The name of the template used to create the HTML markup.</param>
/// <param name="htmlFieldName">
/// A <see cref="string"/> used to disambiguate the names of HTML elements that are created for properties
/// that have the same name.
/// </param>
/// <param name="additionalViewData">
/// An anonymous <see cref="object"/> or <see cref="IDictionary{String, Object}"/> that can contain additional
/// view data that will be merged into the <see cref="ViewDataDictionary{TModel}"/> instance created for the
/// template.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the created HTML.</returns>
/// <remarks>
/// <para>
/// For example the default <see cref="object"/> display template includes markup for each property in the
/// <paramref name="expression"/> result.
/// </para>
/// <para>
/// Custom templates are found under a <c>DisplayTemplates</c> folder. The folder name is case-sensitive on
/// case-sensitive file systems.
/// </para>
/// </remarks>
IHtmlContent DisplayFor<TResult>(
Expression<Func<TModel, TResult>> expression,
string templateName,
string htmlFieldName,
object additionalViewData);
/// <summary>
/// Returns the display name for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A <see cref="string"/> containing the display name.</returns>
string DisplayNameFor<TResult>(Expression<Func<TModel, TResult>> expression);
/// <summary>
/// Returns the display name for the specified <paramref name="expression"/>
/// if the current model represents a collection.
/// </summary>
/// <param name="expression">An expression to be evaluated against an item in the current model.</param>
/// <typeparam name="TModelItem">The type of items in the model collection.</typeparam>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A <see cref="string"/> containing the display name.</returns>
string DisplayNameForInnerType<TModelItem, TResult>(
Expression<Func<TModelItem, TResult>> expression);
/// <summary>
/// Returns the simple display text for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>
/// A <see cref="string"/> containing the simple display text.
/// If the <paramref name="expression"/> result is <c>null</c>, returns
/// <see cref="ModelBinding.ModelMetadata.NullDisplayText"/>.
/// </returns>
string DisplayTextFor<TResult>(Expression<Func<TModel, TResult>> expression);
/// <summary>
/// Returns a single-selection HTML <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="optionLabel"/> and <paramref name="selectList"/>. Adds a
/// "selected" attribute to an <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>.
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, uses the <see cref="ViewData"/> entry with
/// full name and that entry must be a collection of <see cref="SelectListItem"/> objects.
/// </param>
/// <param name="optionLabel">
/// The text for a default empty item. Does not include such an item if argument is <c>null</c>.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the <select> element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent DropDownListFor<TResult>(
Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes);
/// <summary>
/// Returns HTML markup for the <paramref name="expression"/>, using an editor template, specified HTML field
/// name, and additional view data. The template is found using the <paramref name="templateName"/> or the
/// <paramref name="expression"/>'s <see cref="ModelBinding.ModelMetadata"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="templateName">The name of the template that is used to create the HTML markup.</param>
/// <param name="htmlFieldName">
/// A <see cref="string"/> used to disambiguate the names of HTML elements that are created for properties
/// that have the same name.
/// </param>
/// <param name="additionalViewData">
/// An anonymous <see cref="object"/> or <see cref="IDictionary{String, Object}"/> that can contain additional
/// view data that will be merged into the <see cref="ViewDataDictionary{TModel}"/> instance created for the
/// template.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <input> element(s).</returns>
/// <remarks>
/// <para>
/// For example the default <see cref="object"/> editor template includes <label> and <input>
/// elements for each property in the <paramref name="expression"/> result.
/// </para>
/// <para>
/// Custom templates are found under a <c>EditorTemplates</c> folder. The folder name is case-sensitive on
/// case-sensitive file systems.
/// </para>
/// </remarks>
IHtmlContent EditorFor<TResult>(
Expression<Func<TModel, TResult>> expression,
string templateName,
string htmlFieldName,
object additionalViewData);
/// <inheritdoc cref="IHtmlHelper.Encode(object)"/>
new string Encode(object value);
/// <inheritdoc cref="IHtmlHelper.Encode(string)"/>
new string Encode(string value);
/// <summary>
/// Returns an <input> element of type "hidden" for the specified <paramref name="expression"/>. Adds a
/// "value" attribute to the element containing the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name,
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>, or
/// the <paramref name="htmlAttributes"/> dictionary entry with key "value".
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <input> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <input> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent HiddenFor<TResult>(
Expression<Func<TModel, TResult>> expression,
object htmlAttributes);
/// <summary>
/// Returns the HTML element Id for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A <see cref="string"/> containing the element Id.</returns>
string IdFor<TResult>(Expression<Func<TModel, TResult>> expression);
/// <summary>
/// Returns a <label> element for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="labelText">The inner text of the element.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <label> element.</returns>
IHtmlContent LabelFor<TResult>(
Expression<Func<TModel, TResult>> expression,
string labelText,
object htmlAttributes);
/// <summary>
/// Returns a multi-selection <select> element for the <paramref name="expression"/>. Adds
/// <option> elements based on <paramref name="selectList"/>. Adds a "selected" attribute to an
/// <option> if its <see cref="SelectListItem.Value"/> (if non-<c>null</c>) or
/// <see cref="SelectListItem.Text"/> matches an entry in the first non-<c>null</c> collection found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>.
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="selectList">
/// A collection of <see cref="SelectListItem"/> objects used to populate the <select> element with
/// <optgroup> and <option> elements. If <c>null</c>, finds the <see cref="SelectListItem"/>
/// collection with name <paramref name="expression"/> in <see cref="ViewData"/>.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the <select> element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <select> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent ListBoxFor<TResult>(
Expression<Func<TModel, TResult>> expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes);
/// <summary>
/// Returns the full HTML element name for the specified <paramref name="expression"/>. Uses
/// <see cref="TemplateInfo.HtmlFieldPrefix"/> (if non-empty) to reflect relationship between current
/// <see cref="ViewDataDictionary.Model"/> and the top-level view's model.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A <see cref="string"/> containing the element name.</returns>
string NameFor<TResult>(Expression<Func<TModel, TResult>> expression);
/// <summary>
/// Returns an <input> element of type "password" for the specified <paramref name="expression"/>. Adds a
/// "value" attribute containing the <paramref name="htmlAttributes"/> dictionary entry with key "value" (if
/// any).
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <input> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <input> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent PasswordFor<TResult>(
Expression<Func<TModel, TResult>> expression,
object htmlAttributes);
/// <summary>
/// Returns an <input> element of type "radio" for the specified <paramref name="expression"/>.
/// Adds a "value" attribute to the element containing the first non-<c>null</c> value found in:
/// the <paramref name="value"/> parameter, or
/// the <paramref name="htmlAttributes"/> dictionary entry with key "value".
/// Adds a "checked" attribute to the element if <paramref name="value"/> matches the first non-<c>null</c>
/// value found in:
/// the <paramref name="htmlAttributes"/> dictionary entry with key "checked", or
/// the <see cref="ActionContext.ModelState"/> entry with full name.
/// If <paramref name="expression"/> evaluates to a non-<c>null</c> value, instead uses the first
/// non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>.
/// See <see cref="NameFor"/> for more information about a "full name".
/// Adds a "value" attribute to the element containing the <paramref name="value"/> parameter.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="value">Value to include in the element. Must not be <c>null</c>.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <input> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <select> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent RadioButtonFor<TResult>(
Expression<Func<TModel, TResult>> expression,
object value,
object htmlAttributes);
/// <inheritdoc cref="IHtmlHelper.Raw(object)"/>
new IHtmlContent Raw(object value);
/// <inheritdoc cref="IHtmlHelper.Raw(string)"/>
new IHtmlContent Raw(string value);
/// <summary>
/// Returns a <textarea> element for the specified <paramref name="expression"/>. Adds content to the
/// element body based on the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>.
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="rows">Number of rows in the textarea.</param>
/// <param name="columns">Number of columns in the textarea.</param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <textarea> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <textarea> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent TextAreaFor<TResult>(
Expression<Func<TModel, TResult>> expression,
int rows,
int columns,
object htmlAttributes);
/// <summary>
/// Returns an <input> element of type "text" for the specified <paramref name="expression"/>. Adds a
/// "value" attribute to the element containing the first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name,
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>, or
/// the <paramref name="htmlAttributes"/> dictionary entry with key "value".
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="format">
/// The format string (see https://msdn.microsoft.com/en-us/library/txafckwd.aspx) used to format the
/// <paramref name="expression"/> value when using that in the "value" attribute.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an
/// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A new <see cref="IHtmlContent"/> containing the <input> element.</returns>
/// <remarks>
/// Combines <see cref="TemplateInfo.HtmlFieldPrefix"/> and the string representation of the
/// <paramref name="expression"/> to set <input> element's "name" attribute. Sanitizes the string
/// representation of the <paramref name="expression"/> to set element's "id" attribute.
/// </remarks>
IHtmlContent TextBoxFor<TResult>(
Expression<Func<TModel, TResult>> expression,
string format,
object htmlAttributes);
/// <summary>
/// Returns the validation message if an error exists in the <see cref="ModelBinding.ModelStateDictionary"/>
/// object for the specified <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="message">
/// The message to be displayed. If <c>null</c> or empty, method extracts an error string from the
/// <see cref="ModelBinding.ModelStateDictionary"/> object. Message will always be visible but client-side
/// validation may update the associated CSS class.
/// </param>
/// <param name="htmlAttributes">
/// An <see cref="object"/> that contains the HTML attributes for the <paramref name="tag"/> element.
/// Alternatively, an <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.
/// </param>
/// <param name="tag">
/// The tag to wrap the <paramref name="message"/> in the generated HTML. Its default value is
/// <see cref="ViewContext.ValidationMessageElement"/>.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>
/// A new <see cref="IHtmlContent"/> containing the <paramref name="tag"/> element. <c>null</c> if the
/// <paramref name="expression"/> is valid and client-side validation is disabled.
/// </returns>
IHtmlContent ValidationMessageFor<TResult>(
Expression<Func<TModel, TResult>> expression,
string message,
object htmlAttributes,
string tag);
/// <summary>
/// Returns the formatted value for the specified <paramref name="expression"/>. Specifically, returns the
/// first non-<c>null</c> value found in:
/// the <see cref="ActionContext.ModelState"/> entry with full name, or
/// the <paramref name="expression"/> evaluated against <see cref="ViewDataDictionary.Model"/>.
/// See <see cref="NameFor"/> for more information about a "full name".
/// </summary>
/// <param name="expression">An expression to be evaluated against the current model.</param>
/// <param name="format">
/// The format string (see https://msdn.microsoft.com/en-us/library/txafckwd.aspx) used to format the
/// <paramref name="expression"/> value when returning that value.
/// </param>
/// <typeparam name="TResult">The type of the <paramref name="expression"/> result.</typeparam>
/// <returns>A <see cref="string"/> containing the formatted value.</returns>
/// <remarks>
/// Converts the <paramref name="expression"/> result to a <see cref="string"/> directly if
/// <paramref name="format"/> is <c>null</c> or empty.
/// </remarks>
string ValueFor<TResult>(
Expression<Func<TModel, TResult>> expression,
string format);
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
namespace Aurora.Modules.Friends
{
public class FriendsModule : ISharedRegionModule, IFriendsModule
{
protected Dictionary<UUID, UserFriendData> m_Friends =
new Dictionary<UUID, UserFriendData>();
protected List<IScene> m_Scenes = new List<IScene>();
public bool m_enabled = true;
protected bool m_firstStart = true;
protected Dictionary<UUID, List<UUID>> m_friendsToInformOfStatusChanges = new Dictionary<UUID, List<UUID>>();
protected IFriendsService FriendsService
{
get { return m_Scenes[0].RequestModuleInterface<IFriendsService>(); }
}
protected IGridService GridService
{
get
{
if (m_Scenes.Count == 0)
return null;
return m_Scenes[0].GridService;
}
}
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
}
public IAsyncMessagePostService AsyncMessagePostService
{
get { return m_Scenes[0].RequestModuleInterface<IAsyncMessagePostService>(); }
}
public ISyncMessagePosterService SyncMessagePosterService
{
get { return m_Scenes[0].RequestModuleInterface<ISyncMessagePosterService>(); }
}
public IAsyncMessageRecievedService AsyncMessageRecievedService
{
get { return m_Scenes[0].RequestModuleInterface<IAsyncMessageRecievedService>(); }
}
#region IFriendsModule Members
public int GetFriendPerms(UUID principalID, UUID friendID)
{
FriendInfo[] friends = GetFriends(principalID);
#if (!ISWIN)
foreach (FriendInfo fi in friends)
{
if (fi.Friend == friendID.ToString())
{
return fi.TheirFlags;
}
}
#else
foreach (FriendInfo fi in friends.Where(fi => fi.Friend == friendID.ToString()))
{
return fi.TheirFlags;
}
#endif
return -1;
}
public void SendFriendsStatusMessage(UUID FriendToInformID, UUID userID, bool online)
{
// Try local
IClientAPI friendClient = LocateClientObject(FriendToInformID);
if (friendClient != null)
{
//MainConsole.Instance.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
// the friend in this sim as root agent
if (online)
friendClient.SendAgentOnline(new[] {userID});
else
friendClient.SendAgentOffline(new[] {userID});
// we're done
return;
}
lock (m_friendsToInformOfStatusChanges)
{
if (!m_friendsToInformOfStatusChanges.ContainsKey(FriendToInformID))
m_friendsToInformOfStatusChanges.Add(FriendToInformID, new List<UUID>());
m_friendsToInformOfStatusChanges[FriendToInformID].Add(userID);
}
// Friend is not online. Ignore.
}
public FriendInfo[] GetFriends(UUID agentID)
{
UserFriendData friendsData;
lock (m_Friends)
{
if (m_Friends.TryGetValue(agentID, out friendsData))
return friendsData.Friends;
else
{
UpdateFriendsCache(agentID);
if (m_Friends.TryGetValue(agentID, out friendsData))
return friendsData.Friends;
}
}
return new FriendInfo[0];
}
public FriendInfo[] GetFriendsRequest(UUID agentID)
{
UserFriendData friendsData;
lock (m_Friends)
{
if (m_Friends.TryGetValue(agentID, out friendsData))
return friendsData.Friends;
else
{
UpdateFriendsCache(agentID);
if (m_Friends.TryGetValue(agentID, out friendsData))
return friendsData.Friends;
}
}
return new FriendInfo[0];
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(IScene scene)
{
if (!m_enabled)
return;
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnClosingClient += OnClosingClient;
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
}
public void RegionLoaded(IScene scene)
{
if (m_firstStart)
AsyncMessageRecievedService.OnMessageReceived += OnMessageReceived;
m_firstStart = false;
}
public void RemoveRegion(IScene scene)
{
if (!m_enabled)
return;
m_Scenes.Remove(scene);
scene.UnregisterModuleInterface<IFriendsModule>(this);
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnClosingClient -= OnClosingClient;
scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent;
}
public string Name
{
get { return "FriendsModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
protected OSDMap OnMessageReceived(OSDMap message)
{
if (!message.ContainsKey("Method"))
return null;
if (message["Method"] == "FriendGrantRights")
{
UUID Requester = message["Requester"].AsUUID();
UUID Target = message["Target"].AsUUID();
int MyFlags = message["MyFlags"].AsInteger();
int Rights = message["Rights"].AsInteger();
LocalGrantRights(Requester, Target, MyFlags, Rights);
}
else if (message["Method"] == "FriendTerminated")
{
UUID Requester = message["Requester"].AsUUID();
UUID ExFriend = message["ExFriend"].AsUUID();
LocalFriendshipTerminated(ExFriend, Requester);
}
else if (message["Method"] == "FriendshipOffered")
{
//UUID Requester = message["Requester"].AsUUID();
UUID Friend = message["Friend"].AsUUID();
GridInstantMessage im = new GridInstantMessage();
im.FromOSD((OSDMap) message["Message"]);
LocalFriendshipOffered(Friend, im);
}
else if (message["Method"] == "FriendshipDenied")
{
UUID Requester = message["Requester"].AsUUID();
string ClientName = message["ClientName"].AsString();
UUID FriendID = message["FriendID"].AsUUID();
LocalFriendshipDenied(Requester, ClientName, FriendID);
}
else if (message["Method"] == "FriendshipApproved")
{
UUID Requester = message["Requester"].AsUUID();
string ClientName = message["ClientName"].AsString();
UUID FriendID = message["FriendID"].AsUUID();
LocalFriendshipApproved(Requester, ClientName, null, FriendID);
}
return null;
}
private void OnClosingClient(IClientAPI client)
{
client.OnInstantMessage -= OnInstantMessage;
client.OnApproveFriendRequest -= OnApproveFriendRequest;
client.OnDenyFriendRequest -= OnDenyFriendRequest;
client.OnTerminateFriendship -= OnTerminateFriendship;
client.OnGrantUserRights -= OnGrantUserRights;
}
private void OnNewClient(IClientAPI client)
{
client.OnInstantMessage += OnInstantMessage;
client.OnApproveFriendRequest += OnApproveFriendRequest;
client.OnDenyFriendRequest += OnDenyFriendRequest;
client.OnTerminateFriendship += OnTerminateFriendship;
client.OnGrantUserRights += OnGrantUserRights;
OfflineFriendRequest(client);
//Only send if they are root!
//Util.FireAndForget(delegate(object o)
//{
// SendFriendsOnlineIfNeeded(client);
//});
}
private void OnMakeRootAgent(IScenePresence presence)
{
//Only send if they are root!
Util.FireAndForget(delegate { SendFriendsOnlineIfNeeded(presence.ControllingClient); });
}
public void SendFriendsOnlineIfNeeded(IClientAPI client)
{
UUID agentID = client.AgentId;
// Send outstanding friendship offers
List<string> outstanding = new List<string>();
FriendInfo[] friends = GetFriends(agentID);
foreach (FriendInfo fi in friends)
{
UUID friendID;
string url = "", first = "", last = "", secret = "";
HGUtil.ParseUniversalUserIdentifier(fi.Friend, out friendID, out url, out first, out last,
out secret);
if (friendID != UUID.Zero)
{
if (fi.TheirFlags == -1)
outstanding.Add(fi.Friend);
}
}
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, String.Empty, agentID,
(byte) InstantMessageDialog.FriendshipOffered,
"Will you be my friend?", true, Vector3.Zero);
foreach (string fid in outstanding)
{
UUID fromAgentID;
string url = "", first = "", last = "", secret = "";
if (!UUID.TryParse(fid, out fromAgentID))
if (
!HGUtil.ParseUniversalUserIdentifier(fid, out fromAgentID, out url, out first, out last,
out secret))
continue;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.AllScopeIDs,
fromAgentID);
im.fromAgentID = fromAgentID;
if (account != null)
im.fromAgentName = account.Name;
else
im.fromAgentName = first + " " + last;
im.offline = 1;
im.imSessionID = im.fromAgentID;
// Finally
LocalFriendshipOffered(agentID, im);
}
lock (m_friendsToInformOfStatusChanges)
{
if (m_friendsToInformOfStatusChanges.ContainsKey(agentID))
{
List<UUID> onlineFriends = new List<UUID>(m_friendsToInformOfStatusChanges[agentID]);
foreach (UUID friend in onlineFriends)
{
SendFriendsStatusMessage(agentID, friend, true);
}
m_friendsToInformOfStatusChanges.Remove(agentID);
}
}
}
/// <summary>
/// Find the client for a ID
/// </summary>
public IClientAPI LocateClientObject(UUID agentID)
{
IScene scene = GetClientScene(agentID);
if (scene != null)
{
IScenePresence presence = scene.GetScenePresence(agentID);
if (presence != null)
return presence.ControllingClient;
}
return null;
}
/// <summary>
/// Find the scene for an agent
/// </summary>
public IScene GetClientScene(UUID agentId)
{
lock (m_Scenes)
{
foreach (IScene scene in from scene in m_Scenes let presence = scene.GetScenePresence(agentId) where presence != null && !presence.IsChildAgent select scene)
{
return scene;
}
}
return null;
}
private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if ((InstantMessageDialog) im.dialog == InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = im.fromAgentID;
UUID friendID = im.toAgentID;
//Can't trust the incoming name for friend offers, so we have to find it ourselves.
UserAccount sender = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.AllScopeIDs, principalID);
im.fromAgentName = sender.Name;
UserAccount reciever = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.AllScopeIDs, friendID);
MainConsole.Instance.DebugFormat("[FRIENDS]: {0} offered friendship to {1}", sender.Name, reciever.Name);
// This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online
FriendsService.StoreFriend(friendID, principalID.ToString(), 0);
// Now let's ask the other user to be friends with this user
ForwardFriendshipOffer(principalID, friendID, im);
}
}
private void ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
// !!!!!!!! This is a hack so that we don't have to keep state (transactionID/imSessionID)
// We stick this agent's ID as imSession, so that it's directly available on the receiving end
im.imSessionID = im.fromAgentID;
// Try the local sim
UserAccount account = UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.AllScopeIDs, agentID);
im.fromAgentName = (account == null) ? "Unknown" : account.Name;
if (LocalFriendshipOffered(friendID, im))
return;
// The prospective friend is not here [as root]. Let's4 forward.
SyncMessagePosterService.Post(SyncMessageHelper.FriendshipOffered(
agentID, friendID, im, m_Scenes[0].RegionInfo.RegionHandle), m_Scenes[0].RegionInfo.RegionHandle);
// If the prospective friend is not online, he'll get the message upon login.
}
private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID,
List<UUID> callingCardFolders)
{
MainConsole.Instance.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", agentID, friendID);
FriendsService.StoreFriend(agentID, friendID.ToString(), 1);
FriendsService.StoreFriend(friendID, agentID.ToString(), 1);
// Update the local cache
UpdateFriendsCache(agentID);
//
// Notify the friend
//
//
// Send calling card to the local user
//
ICallingCardModule ccmodule = client.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccmodule != null)
{
UserAccount account = client.Scene.UserAccountService.GetUserAccount(client.AllScopeIDs, friendID);
UUID folderID =
client.Scene.InventoryService.GetFolderForType(agentID, InventoryType.Unknown, AssetType.CallingCard)
.ID;
if (account != null)
ccmodule.CreateCallingCard(client, friendID, folderID, account.Name);
}
// Try Local
if (LocalFriendshipApproved(agentID, client.Name, client, friendID))
return;
SyncMessagePosterService.Post(SyncMessageHelper.FriendshipApproved(
agentID, client.Name, friendID, m_Scenes[0].RegionInfo.RegionHandle),
m_Scenes[0].RegionInfo.RegionHandle);
}
private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
{
MainConsole.Instance.DebugFormat("[FRIENDS]: {0} denied friendship to {1}", agentID, friendID);
FriendInfo[] friends = FriendsService.GetFriendsRequest(agentID).ToArray();
foreach (FriendInfo fi in friends)
{
if (fi.MyFlags == 0)
{
UUID fromAgentID;
string url = "", first = "", last = "", secret = "";
if (!UUID.TryParse(fi.Friend, out fromAgentID))
if (
!HGUtil.ParseUniversalUserIdentifier(fi.Friend, out fromAgentID, out url, out first, out last, out secret))
continue;
if (fromAgentID == friendID)//Get those pesky HG travelers as well
FriendsService.Delete(agentID, fi.Friend);
}
}
FriendsService.Delete(friendID, agentID.ToString());
//
// Notify the friend
//
// Try local
if (LocalFriendshipDenied(agentID, client.Name, friendID))
return;
SyncMessagePosterService.Post(SyncMessageHelper.FriendshipDenied(
agentID, client.Name, friendID, m_Scenes[0].RegionInfo.RegionHandle),
m_Scenes[0].RegionInfo.RegionHandle);
}
private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID)
{
FriendsService.Delete(agentID, exfriendID.ToString());
FriendsService.Delete(exfriendID, agentID.ToString());
// Update local cache
UpdateFriendsCache(agentID);
client.SendTerminateFriend(exfriendID);
//
// Notify the friend
//
// Try local
if (LocalFriendshipTerminated(exfriendID, agentID))
return;
SyncMessagePosterService.Post(SyncMessageHelper.FriendTerminated(
agentID, exfriendID, m_Scenes[0].RegionInfo.RegionHandle), m_Scenes[0].RegionInfo.RegionHandle);
}
private void OnGrantUserRights(IClientAPI remoteClient, UUID requester, UUID target, int rights)
{
FriendInfo[] friends = GetFriends(remoteClient.AgentId);
if (friends.Length == 0)
return;
MainConsole.Instance.DebugFormat("[FRIENDS MODULE]: User {0} changing rights to {1} for friend {2}", requester, rights,
target);
// Let's find the friend in this user's friend list
FriendInfo friend = null;
#if (!ISWIN)
foreach (FriendInfo fi in friends)
{
if (fi.Friend == target.ToString())
{
friend = fi;
}
}
#else
foreach (FriendInfo fi in friends.Where(fi => fi.Friend == target.ToString()))
{
friend = fi;
}
#endif
if (friend != null) // Found it
{
// Store it on the DB
FriendsService.StoreFriend(requester, target.ToString(), rights);
// Store it in the local cache
int myFlags = friend.MyFlags;
friend.MyFlags = rights;
// Always send this back to the original client
remoteClient.SendChangeUserRights(requester, target, rights);
//
// Notify the friend
//
// Try local
if (!LocalGrantRights(requester, target, myFlags, rights))
{
SyncMessagePosterService.Post(SyncMessageHelper.FriendGrantRights(
requester, target, myFlags, rights, m_Scenes[0].RegionInfo.RegionHandle),
m_Scenes[0].RegionInfo.RegionHandle);
}
}
}
public void OfflineFriendRequest(IClientAPI client)
{
// Barrowed a few lines from SendFriendsOnlineIfNeeded() above.
UUID agentID = client.AgentId;
FriendInfo[] friends = FriendsService.GetFriendsRequest(agentID).ToArray();
GridInstantMessage im = new GridInstantMessage(client.Scene, UUID.Zero, String.Empty, agentID,
(byte)InstantMessageDialog.FriendshipOffered,
"Will you be my friend?", true, Vector3.Zero);
foreach (FriendInfo fi in friends)
{
if(fi.MyFlags == 0)
{
UUID fromAgentID;
string url = "", first = "", last = "", secret = "";
if (!UUID.TryParse(fi.Friend, out fromAgentID))
if (
!HGUtil.ParseUniversalUserIdentifier(fi.Friend, out fromAgentID, out url, out first, out last, out secret))
continue;
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.AllScopeIDs, fromAgentID);
im.fromAgentID = fromAgentID;
if (account != null)
im.fromAgentName = account.Name;
else
im.fromAgentName = first + " " + last;
im.offline = 1;
im.imSessionID = im.fromAgentID;
LocalFriendshipOffered(agentID, im);
}
}
}
private void UpdateFriendsCache(UUID agentID)
{
UserFriendData friendsData = new UserFriendData
{
PrincipalID = agentID,
Refcount = 0,
Friends = FriendsService.GetFriends(agentID).ToArray()
};
lock (m_Friends)
{
m_Friends[agentID] = friendsData;
}
}
#region Local
public bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
IClientAPI friendClient = LocateClientObject(toID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipApproved(UUID userID, string name, IClientAPI us, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
//They are online, send the online message
if (us != null)
us.SendAgentOnline(new[] {friendID});
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(m_Scenes[0], userID, name, friendID,
(byte) InstantMessageDialog.FriendshipAccepted,
userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// Update the local cache
UpdateFriendsCache(friendID);
//
// put a calling card into the inventory of the friend
//
ICallingCardModule ccmodule = friendClient.Scene.RequestModuleInterface<ICallingCardModule>();
if (ccmodule != null)
{
UserAccount account = friendClient.Scene.UserAccountService.GetUserAccount(friendClient.AllScopeIDs,
userID);
UUID folderID =
friendClient.Scene.InventoryService.GetFolderForType(friendID, InventoryType.Unknown,
AssetType.CallingCard).ID;
ccmodule.CreateCallingCard(friendClient, userID, folderID, account.Name);
}
// we're done
return true;
}
return false;
}
public bool LocalFriendshipDenied(UUID userID, string userName, UUID friendID)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
// the prospective friend in this sim as root agent
GridInstantMessage im = new GridInstantMessage(m_Scenes[0], userID, userName, friendID,
(byte) InstantMessageDialog.FriendshipDeclined,
userID.ToString(), false, Vector3.Zero);
friendClient.SendInstantMessage(im);
// we're done
return true;
}
return false;
}
public bool LocalFriendshipTerminated(UUID exfriendID, UUID terminatingUser)
{
IClientAPI friendClient = LocateClientObject(exfriendID);
if (friendClient != null)
{
// update local cache
UpdateFriendsCache(exfriendID);
// the friend in this sim as root agent
// you do NOT send the friend his uuid... /me sighs... - Revolution
friendClient.SendTerminateFriend(terminatingUser);
return true;
}
return false;
}
public bool LocalGrantRights(UUID userID, UUID friendID, int userFlags, int rights)
{
IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null)
{
bool onlineBitChanged = ((rights ^ userFlags) & (int) FriendRights.CanSeeOnline) != 0;
if (onlineBitChanged)
{
if ((rights & (int) FriendRights.CanSeeOnline) == 1)
friendClient.SendAgentOnline(new[] {new UUID(userID)});
else
friendClient.SendAgentOffline(new[] {new UUID(userID)});
}
else
{
bool canEditObjectsChanged = ((rights ^ userFlags) & (int) FriendRights.CanModifyObjects) != 0;
if (canEditObjectsChanged)
friendClient.SendChangeUserRights(userID, friendID, rights);
}
// Update local cache
FriendInfo[] friends = GetFriends(friendID);
lock (m_Friends)
{
#if (!ISWIN)
foreach (FriendInfo finfo in friends)
{
if (finfo.Friend == userID.ToString())
{
finfo.TheirFlags = rights;
}
}
#else
foreach (FriendInfo finfo in friends.Where(finfo => finfo.Friend == userID.ToString()))
{
finfo.TheirFlags = rights;
}
#endif
}
friends = GetFriends(userID);
lock (m_Friends)
{
#if (!ISWIN)
foreach (FriendInfo finfo in friends)
{
if (finfo.Friend == friendID.ToString())
{
finfo.MyFlags = rights;
}
}
#else
foreach (FriendInfo finfo in friends.Where(finfo => finfo.Friend == friendID.ToString()))
{
finfo.MyFlags = rights;
}
#endif
}
//Add primFlag updates for all the prims in the sim with the owner, so that the new permissions are set up correctly
IScenePresence friendSP = friendClient.Scene.GetScenePresence(friendClient.AgentId);
#if (!ISWIN)
foreach (ISceneEntity entity in friendClient.Scene.Entities.GetEntities())
{
if (entity.OwnerID == userID)
{
entity.ScheduleGroupUpdateToAvatar(friendSP, PrimUpdateFlags.PrimFlags);
}
}
#else
foreach (ISceneEntity entity in friendClient.Scene.Entities.GetEntities().Where(entity => entity.OwnerID == userID))
{
entity.ScheduleGroupUpdateToAvatar(friendSP, PrimUpdateFlags.PrimFlags);
}
#endif
return true;
}
return false;
}
#endregion
#region Nested type: UserFriendData
protected class UserFriendData
{
public FriendInfo[] Friends;
public UUID PrincipalID;
public int Refcount;
public bool IsFriend(string friend)
{
#if (!ISWIN)
foreach (FriendInfo fi in Friends)
{
if (fi.Friend == friend) return true;
}
return false;
#else
return Friends.Any(fi => fi.Friend == friend);
#endif
}
}
#endregion
}
}
| |
using Content.Client.Tabletop.Components;
using Content.Client.Tabletop.UI;
using Content.Client.Viewport;
using Content.Shared.Tabletop;
using Content.Shared.Tabletop.Events;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.Player;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Input;
using Robust.Shared.Input.Binding;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Timing;
using static Robust.Shared.Input.Binding.PointerInputCmdHandler;
using DrawDepth = Content.Shared.DrawDepth.DrawDepth;
namespace Content.Client.Tabletop
{
[UsedImplicitly]
public sealed class TabletopSystem : SharedTabletopSystem
{
[Dependency] private readonly IInputManager _inputManager = default!;
[Dependency] private readonly IUserInterfaceManager _uiManger = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
// Time in seconds to wait until sending the location of a dragged entity to the server again
private const float Delay = 1f / 10; // 10 Hz
private float _timePassed; // Time passed since last update sent to the server.
private EntityUid? _draggedEntity; // Entity being dragged
private ScalingViewport? _viewport; // Viewport currently being used
private DefaultWindow? _window; // Current open tabletop window (only allow one at a time)
private EntityUid? _table; // The table entity of the currently open game session
public override void Initialize()
{
UpdatesOutsidePrediction = true;
CommandBinds.Builder
.Bind(EngineKeyFunctions.Use, new PointerInputCmdHandler(OnUse, false))
.Register<TabletopSystem>();
SubscribeNetworkEvent<TabletopPlayEvent>(OnTabletopPlay);
SubscribeLocalEvent<TabletopDraggableComponent, ComponentHandleState>(HandleComponentState);
}
public override void Update(float frameTime)
{
// don't send network messages when doing prediction.
if (!_gameTiming.IsFirstTimePredicted)
return;
// If there is no player entity, return
if (_playerManager.LocalPlayer is not {ControlledEntity: { } playerEntity}) return;
if (StunnedOrNoHands(playerEntity))
{
StopDragging();
}
if (!CanSeeTable(playerEntity, _table))
{
StopDragging();
_window?.Close();
return;
}
// If no entity is being dragged or no viewport is clicked, return
if (_draggedEntity == null || _viewport == null) return;
// Make sure the dragged entity has a draggable component
if (!EntityManager.TryGetComponent<TabletopDraggableComponent>(_draggedEntity.Value, out var draggableComponent)) return;
// If the dragged entity has another dragging player, drop the item
// This should happen if the local player is dragging an item, and another player grabs it out of their hand
if (draggableComponent.DraggingPlayer != null &&
draggableComponent.DraggingPlayer != _playerManager.LocalPlayer?.Session.UserId)
{
StopDragging(false);
return;
}
// Map mouse position to EntityCoordinates
var coords = _viewport.ScreenToMap(_inputManager.MouseScreenPosition.Position);
// Clamp coordinates to viewport
var clampedCoords = ClampPositionToViewport(coords, _viewport);
if (clampedCoords.Equals(MapCoordinates.Nullspace)) return;
// Move the entity locally every update
EntityManager.GetComponent<TransformComponent>(_draggedEntity.Value).WorldPosition = clampedCoords.Position;
// Increment total time passed
_timePassed += frameTime;
// Only send new position to server when Delay is reached
if (_timePassed >= Delay && _table != null)
{
RaiseNetworkEvent(new TabletopMoveEvent(_draggedEntity.Value, clampedCoords, _table.Value));
_timePassed -= Delay;
}
}
#region Event handlers
/// <summary>
/// Runs when the player presses the "Play Game" verb on a tabletop game.
/// Opens a viewport where they can then play the game.
/// </summary>
private void OnTabletopPlay(TabletopPlayEvent msg)
{
// Close the currently opened window, if it exists
_window?.Close();
_table = msg.TableUid;
// Get the camera entity that the server has created for us
var camera = msg.CameraUid;
if (!EntityManager.TryGetComponent<EyeComponent>(camera, out var eyeComponent))
{
// If there is no eye, print error and do not open any window
Logger.Error("Camera entity does not have eye component!");
return;
}
// Create a window to contain the viewport
_window = new TabletopWindow(eyeComponent.Eye, (msg.Size.X, msg.Size.Y))
{
MinWidth = 500,
MinHeight = 436,
Title = msg.Title
};
_window.OnClose += OnWindowClose;
}
private void HandleComponentState(EntityUid uid, TabletopDraggableComponent component, ref ComponentHandleState args)
{
if (args.Current is not TabletopDraggableComponentState state) return;
component.DraggingPlayer = state.DraggingPlayer;
}
private void OnWindowClose()
{
if (_table != null)
{
RaiseNetworkEvent(new TabletopStopPlayingEvent(_table.Value));
}
StopDragging();
_window = null;
}
private bool OnUse(in PointerInputCmdArgs args)
{
return args.State switch
{
BoundKeyState.Down => OnMouseDown(args),
BoundKeyState.Up => OnMouseUp(args),
_ => false
};
}
private bool OnMouseDown(in PointerInputCmdArgs args)
{
// Return if no player entity
if (_playerManager.LocalPlayer is not {ControlledEntity: { } playerEntity})
return false;
// Return if can not see table or stunned/no hands
if (!CanSeeTable(playerEntity, _table) || StunnedOrNoHands(playerEntity))
{
return false;
}
var draggedEntity = args.EntityUid;
// Set the entity being dragged and the viewport under the mouse
if (!EntityManager.EntityExists(draggedEntity))
{
return false;
}
// Make sure that entity can be dragged
if (!EntityManager.HasComponent<TabletopDraggableComponent>(draggedEntity))
{
return false;
}
// Try to get the viewport under the cursor
if (_uiManger.MouseGetControl(args.ScreenCoordinates) as ScalingViewport is not { } viewport)
{
return false;
}
StartDragging(draggedEntity, viewport);
return true;
}
private bool OnMouseUp(in PointerInputCmdArgs args)
{
StopDragging();
return false;
}
#endregion
#region Utility
/// <summary>
/// Start dragging an entity in a specific viewport.
/// </summary>
/// <param name="draggedEntity">The entity that we start dragging.</param>
/// <param name="viewport">The viewport in which we are dragging.</param>
private void StartDragging(EntityUid draggedEntity, ScalingViewport viewport)
{
RaiseNetworkEvent(new TabletopDraggingPlayerChangedEvent(draggedEntity, true));
if (EntityManager.TryGetComponent<AppearanceComponent>(draggedEntity, out var appearance))
{
appearance.SetData(TabletopItemVisuals.Scale, new Vector2(1.25f, 1.25f));
appearance.SetData(TabletopItemVisuals.DrawDepth, (int) DrawDepth.Items + 1);
}
_draggedEntity = draggedEntity;
_viewport = viewport;
}
/// <summary>
/// Stop dragging the entity.
/// </summary>
/// <param name="broadcast">Whether to tell other clients that we stopped dragging.</param>
private void StopDragging(bool broadcast = true)
{
// Set the dragging player on the component to noone
if (broadcast && _draggedEntity != null && EntityManager.HasComponent<TabletopDraggableComponent>(_draggedEntity.Value))
{
RaiseNetworkEvent(new TabletopDraggingPlayerChangedEvent(_draggedEntity.Value, false));
}
_draggedEntity = null;
_viewport = null;
}
/// <summary>
/// Clamps coordinates within a viewport. ONLY WORKS FOR 90 DEGREE ROTATIONS!
/// </summary>
/// <param name="coordinates">The coordinates to be clamped.</param>
/// <param name="viewport">The viewport to clamp the coordinates to.</param>
/// <returns>Coordinates clamped to the viewport.</returns>
private static MapCoordinates ClampPositionToViewport(MapCoordinates coordinates, ScalingViewport viewport)
{
if (coordinates == MapCoordinates.Nullspace) return MapCoordinates.Nullspace;
var eye = viewport.Eye;
if (eye == null) return MapCoordinates.Nullspace;
var size = (Vector2) viewport.ViewportSize / EyeManager.PixelsPerMeter; // Convert to tiles instead of pixels
var eyePosition = eye.Position.Position;
var eyeRotation = eye.Rotation;
var eyeScale = eye.Scale;
var min = (eyePosition - size / 2) / eyeScale;
var max = (eyePosition + size / 2) / eyeScale;
// If 90/270 degrees rotated, flip X and Y
if (MathHelper.CloseToPercent(eyeRotation.Degrees % 180d, 90d) || MathHelper.CloseToPercent(eyeRotation.Degrees % 180d, -90d))
{
(min.Y, min.X) = (min.X, min.Y);
(max.Y, max.X) = (max.X, max.Y);
}
var clampedPosition = Vector2.Clamp(coordinates.Position, min, max);
// Use the eye's map ID, we don't want anything moving to a different map!
return new MapCoordinates(clampedPosition, eye.Position.MapId);
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Security.Cryptography;
/**
static executor for AssetBundleGraph's data.
*/
namespace AssetBundleGraph {
public class AssetBundleBuildReport {
private class AssetBundleBuildReportManager {
private List<AssetBundleBuildReport> m_buildReports;
private List<ExportReport> m_exportReports;
public List<AssetBundleBuildReport> BuildReports {
get {
return m_buildReports;
}
}
public List<ExportReport> ExportReports {
get {
return m_exportReports;
}
}
public AssetBundleBuildReportManager() {
m_buildReports = new List<AssetBundleBuildReport>();
m_exportReports = new List<ExportReport>();
}
}
private static AssetBundleBuildReportManager s_mgr;
private static AssetBundleBuildReportManager Manager {
get {
if(s_mgr == null) {
s_mgr = new AssetBundleBuildReportManager();
}
return s_mgr;
}
}
static public void ClearReports() {
Manager.BuildReports.Clear();
Manager.ExportReports.Clear();
}
static public void AddBuildReport(AssetBundleBuildReport r) {
Manager.BuildReports.Add(r);
}
static public void AddExportReport(ExportReport r) {
Manager.ExportReports.Add(r);
}
static public IEnumerable<AssetBundleBuildReport> BuildReports {
get {
return Manager.BuildReports;
}
}
static public IEnumerable<ExportReport> ExportReports {
get {
return Manager.ExportReports;
}
}
private NodeData m_node;
private AssetBundleManifest m_manifest;
private AssetBundleBuild[] m_bundleBuild;
private List<AssetReference> m_builtBundles;
private Dictionary<string, List<AssetReference>> m_assetGroups;
private Dictionary<string, List<string>> m_bundleNamesAndVariants;
public NodeData Node {
get {
return m_node;
}
}
public AssetBundleManifest Manifest {
get {
return m_manifest;
}
}
public AssetBundleBuild[] BundleBuild {
get {
return m_bundleBuild;
}
}
public List<AssetReference> BuiltBundleFiles {
get {
return m_builtBundles;
}
}
public Dictionary<string, List<AssetReference>> AssetGroups {
get {
return m_assetGroups;
}
}
public IEnumerable<string> BundleNames {
get {
return m_bundleNamesAndVariants.Keys;
}
}
public List<string> GetVariantNames(string bundleName) {
if(m_bundleNamesAndVariants.ContainsKey(bundleName)) {
return m_bundleNamesAndVariants[bundleName];
}
return null;
}
public AssetBundleBuildReport(
NodeData node,
AssetBundleManifest m,
AssetBundleBuild[] bb,
List<AssetReference> builtBundles,
Dictionary<string, List<AssetReference>> ag,
Dictionary<string, List<string>> names) {
m_node = node;
m_manifest = m;
m_bundleBuild = bb;
m_builtBundles = builtBundles;
m_assetGroups = ag;
m_bundleNamesAndVariants = names;
}
}
public class ExportReport {
public class Entry {
public string source;
public string destination;
public Entry(string src, string dst) {
source = src;
destination = dst;
}
}
public class ErrorEntry {
public string source;
public string destination;
public string reason;
public ErrorEntry(string src, string dst, string r) {
source = src;
destination = dst;
reason = r;
}
}
private NodeData m_nodeData;
private List<Entry> m_exportedItems;
private List<ErrorEntry> m_failedItems;
public List<Entry> ExportedItems {
get {
return m_exportedItems;
}
}
public List<ErrorEntry> Errors {
get {
return m_failedItems;
}
}
public NodeData Node {
get {
return m_nodeData;
}
}
public ExportReport(NodeData node) {
m_nodeData = node;
m_exportedItems = new List<Entry>();
m_failedItems = new List<ErrorEntry> ();
}
public void AddExportedEntry(string src, string dst) {
m_exportedItems.Add(new Entry(src, dst));
}
public void AddErrorEntry(string src, string dst, string reason) {
m_failedItems.Add(new ErrorEntry(src, dst, reason));
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using ZXing.Aztec;
using ZXing.Datamatrix;
using ZXing.IMB;
using ZXing.Maxicode;
using ZXing.OneD;
using ZXing.PDF417;
using ZXing.QrCode;
namespace ZXing
{
/// <summary>
/// MultiFormatReader is a convenience class and the main entry point into the library for most uses.
/// By default it attempts to decode all barcode formats that the library supports. Optionally, you
/// can provide a hints object to request different behavior, for example only decoding QR codes.
/// </summary>
/// <author>Sean Owen</author>
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source</author>
public sealed class MultiFormatReader : Reader
{
private IDictionary<DecodeHintType, object> hints;
private IList<Reader> readers;
/// <summary> This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
/// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
/// Use setHints() followed by decodeWithState() for continuous scan applications.
///
/// </summary>
/// <param name="image">The pixel data to decode
/// </param>
/// <returns> The contents of the image
/// </returns>
/// <throws> ReaderException Any errors which occurred </throws>
public Result decode(BinaryBitmap image)
{
Hints = null;
return decodeInternal(image);
}
/// <summary> Decode an image using the hints provided. Does not honor existing state.
///
/// </summary>
/// <param name="image">The pixel data to decode
/// </param>
/// <param name="hints">The hints to use, clearing the previous state.
/// </param>
/// <returns> The contents of the image
/// </returns>
/// <throws> ReaderException Any errors which occurred </throws>
public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
{
Hints = hints;
return decodeInternal(image);
}
/// <summary> Decode an image using the state set up by calling setHints() previously. Continuous scan
/// clients will get a <b>large</b> speed increase by using this instead of decode().
///
/// </summary>
/// <param name="image">The pixel data to decode
/// </param>
/// <returns> The contents of the image
/// </returns>
/// <throws> ReaderException Any errors which occurred </throws>
public Result decodeWithState(BinaryBitmap image)
{
// Make sure to set up the default state so we don't crash
if (readers == null)
{
Hints = null;
}
return decodeInternal(image);
}
/// <summary> This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls
/// to decodeWithState(image) can reuse the same set of readers without reallocating memory. This
/// is important for performance in continuous scan clients.
///
/// </summary>
/// <param name="hints">The set of hints to use for subsequent calls to decode(image)
/// </param>
public IDictionary<DecodeHintType, object> Hints
{
set
{
hints = value;
var tryHarder = value != null && value.ContainsKey(DecodeHintType.TRY_HARDER);
var formats = value == null || !value.ContainsKey(DecodeHintType.POSSIBLE_FORMATS) ? null : (IList<BarcodeFormat>)value[DecodeHintType.POSSIBLE_FORMATS];
if (formats != null)
{
bool addOneDReader =
formats.Contains(BarcodeFormat.All_1D) ||
formats.Contains(BarcodeFormat.UPC_A) ||
formats.Contains(BarcodeFormat.UPC_E) ||
formats.Contains(BarcodeFormat.EAN_13) ||
formats.Contains(BarcodeFormat.EAN_8) ||
formats.Contains(BarcodeFormat.CODABAR) ||
formats.Contains(BarcodeFormat.CODE_39) ||
formats.Contains(BarcodeFormat.CODE_93) ||
formats.Contains(BarcodeFormat.CODE_128) ||
formats.Contains(BarcodeFormat.ITF) ||
formats.Contains(BarcodeFormat.RSS_14) ||
formats.Contains(BarcodeFormat.RSS_EXPANDED);
readers = new List<Reader>();
// Put 1D readers upfront in "normal" mode
if (addOneDReader && !tryHarder)
{
readers.Add(new MultiFormatOneDReader(value));
}
if (formats.Contains(BarcodeFormat.QR_CODE))
{
readers.Add(new QRCodeReader());
}
if (formats.Contains(BarcodeFormat.DATA_MATRIX))
{
readers.Add(new DataMatrixReader());
}
if (formats.Contains(BarcodeFormat.AZTEC))
{
readers.Add(new AztecReader());
}
if (formats.Contains(BarcodeFormat.PDF_417))
{
readers.Add(new PDF417Reader());
}
if (formats.Contains(BarcodeFormat.MAXICODE))
{
readers.Add(new MaxiCodeReader());
}
if (formats.Contains(BarcodeFormat.IMB))
{
readers.Add(new IMBReader());
}
// At end in "try harder" mode
if (addOneDReader && tryHarder)
{
readers.Add(new MultiFormatOneDReader(value));
}
}
if (readers == null ||
readers.Count == 0)
{
readers = readers ?? new List<Reader>();
if (!tryHarder)
{
readers.Add(new MultiFormatOneDReader(value));
}
readers.Add(new QRCodeReader());
readers.Add(new DataMatrixReader());
readers.Add(new AztecReader());
readers.Add(new PDF417Reader());
readers.Add(new MaxiCodeReader());
if (tryHarder)
{
readers.Add(new MultiFormatOneDReader(value));
}
}
}
}
public void reset()
{
if (readers != null)
{
foreach (var reader in readers)
{
reader.reset();
}
}
}
private Result decodeInternal(BinaryBitmap image)
{
if (readers != null)
{
var rpCallback = hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
? (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]
: null;
for (var index = 0; index < readers.Count; index++)
{
var reader = readers[index];
reader.reset();
var result = reader.decode(image, hints);
if (result != null)
{
// found a barcode, pushing the successful reader up front
// I assume that the same type of barcode is read multiple times
// so the reordering of the readers list should speed up the next reading
// a little bit
readers.RemoveAt(index);
readers.Insert(0, reader);
return result;
}
if (rpCallback != null)
rpCallback(null);
}
}
return null;
}
}
}
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Creating;
public sealed class CreateResourceWithToManyRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public CreateResourceWithToManyRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemsController>();
testContext.UseController<UserAccountsController>();
}
[Fact]
public async Task Can_create_OneToMany_relationship()
{
// Arrange
List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.UserAccounts.AddRange(existingUserAccounts);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingUserAccounts[0].StringId
},
new
{
type = "userAccounts",
id = existingUserAccounts[1].StringId
}
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty();
responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty();
responseDocument.Included.Should().BeNull();
int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(newWorkItemId);
workItemInDatabase.Subscribers.ShouldHaveCount(2);
workItemInDatabase.Subscribers.Should().ContainSingle(subscriber => subscriber.Id == existingUserAccounts[0].Id);
workItemInDatabase.Subscribers.Should().ContainSingle(subscriber => subscriber.Id == existingUserAccounts[1].Id);
});
}
[Fact]
public async Task Can_create_OneToMany_relationship_with_include()
{
// Arrange
List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.UserAccounts.AddRange(existingUserAccounts);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingUserAccounts[0].StringId
},
new
{
type = "userAccounts",
id = existingUserAccounts[1].StringId
}
}
}
}
}
};
const string route = "/workItems?include=subscribers";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty();
responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty();
responseDocument.Included.ShouldHaveCount(2);
responseDocument.Included.Should().OnlyContain(resource => resource.Type == "userAccounts");
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingUserAccounts[0].StringId);
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingUserAccounts[1].StringId);
responseDocument.Included.Should().OnlyContain(resource => resource.Attributes.ShouldContainKey("firstName") != null);
responseDocument.Included.Should().OnlyContain(resource => resource.Attributes.ShouldContainKey("lastName") != null);
responseDocument.Included.Should().OnlyContain(resource => resource.Relationships.ShouldNotBeNull().Count > 0);
int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(newWorkItemId);
workItemInDatabase.Subscribers.ShouldHaveCount(2);
workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingUserAccounts[0].Id);
workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingUserAccounts[1].Id);
});
}
[Fact]
public async Task Can_create_OneToMany_relationship_with_include_and_secondary_fieldset()
{
// Arrange
List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.UserAccounts.AddRange(existingUserAccounts);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingUserAccounts[0].StringId
},
new
{
type = "userAccounts",
id = existingUserAccounts[1].StringId
}
}
}
}
}
};
const string route = "/workItems?include=subscribers&fields[userAccounts]=firstName";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty();
responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty();
responseDocument.Included.ShouldHaveCount(2);
responseDocument.Included.Should().OnlyContain(resource => resource.Type == "userAccounts");
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingUserAccounts[0].StringId);
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingUserAccounts[1].StringId);
responseDocument.Included.Should().OnlyContain(resource => resource.Attributes.ShouldNotBeNull().Count == 1);
responseDocument.Included.Should().OnlyContain(resource => resource.Attributes.ShouldContainKey("firstName") != null);
responseDocument.Included.Should().OnlyContain(resource => resource.Relationships == null);
int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(newWorkItemId);
workItemInDatabase.Subscribers.ShouldHaveCount(2);
workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingUserAccounts[0].Id);
workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingUserAccounts[1].Id);
});
}
[Fact]
public async Task Can_create_ManyToMany_relationship_with_include_and_fieldsets()
{
// Arrange
List<WorkTag> existingTags = _fakers.WorkTag.Generate(3);
WorkItem workItemToCreate = _fakers.WorkItem.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.WorkTags.AddRange(existingTags);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
attributes = new
{
description = workItemToCreate.Description,
priority = workItemToCreate.Priority
},
relationships = new
{
tags = new
{
data = new[]
{
new
{
type = "workTags",
id = existingTags[0].StringId
},
new
{
type = "workTags",
id = existingTags[1].StringId
},
new
{
type = "workTags",
id = existingTags[2].StringId
}
}
}
}
}
};
const string route = "/workItems?fields[workItems]=priority,tags&include=tags&fields[workTags]=text";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Attributes.ShouldHaveCount(1);
responseDocument.Data.SingleValue.Attributes.ShouldContainKey("priority").With(value => value.Should().Be(workItemToCreate.Priority));
responseDocument.Data.SingleValue.Relationships.ShouldHaveCount(1);
responseDocument.Data.SingleValue.Relationships.ShouldContainKey("tags").With(value =>
{
value.ShouldNotBeNull();
value.Data.ManyValue.ShouldHaveCount(3);
value.Data.ManyValue[0].Id.Should().Be(existingTags[0].StringId);
value.Data.ManyValue[1].Id.Should().Be(existingTags[1].StringId);
value.Data.ManyValue[2].Id.Should().Be(existingTags[2].StringId);
});
responseDocument.Included.ShouldHaveCount(3);
responseDocument.Included.Should().OnlyContain(resource => resource.Type == "workTags");
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingTags[0].StringId);
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingTags[1].StringId);
responseDocument.Included.Should().ContainSingle(resource => resource.Id == existingTags[2].StringId);
responseDocument.Included.Should().OnlyContain(resource => resource.Attributes.ShouldNotBeNull().Count == 1);
responseDocument.Included.Should().OnlyContain(resource => resource.Attributes.ShouldContainKey("text") != null);
responseDocument.Included.Should().OnlyContain(resource => resource.Relationships == null);
int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Tags).FirstWithIdAsync(newWorkItemId);
workItemInDatabase.Tags.ShouldHaveCount(3);
workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[0].Id);
workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[1].Id);
workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[2].Id);
});
}
[Fact]
public async Task Cannot_create_for_missing_relationship_type()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
id = Unknown.StringId.For<UserAccount, long>()
}
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/subscribers/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_unknown_relationship_type()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<UserAccount, long>()
}
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/subscribers/data[0]/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_missing_relationship_ID()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts"
}
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/subscribers/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_unknown_relationship_IDs()
{
// Arrange
string workItemId1 = Unknown.StringId.For<WorkItem, int>();
string workItemId2 = Unknown.StringId.AltFor<WorkItem, int>();
UserAccount newUserAccount = _fakers.UserAccount.Generate();
var requestBody = new
{
data = new
{
type = "userAccounts",
attributes = new
{
firstName = newUserAccount.FirstName,
lastName = newUserAccount.LastName
},
relationships = new
{
assignedItems = new
{
data = new[]
{
new
{
type = "workItems",
id = workItemId1
},
new
{
type = "workItems",
id = workItemId2
}
}
}
}
}
};
const string route = "/userAccounts";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.ShouldHaveCount(2);
ErrorObject error1 = responseDocument.Errors[0];
error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
error1.Title.Should().Be("A related resource does not exist.");
error1.Detail.Should().Be($"Related resource of type 'workItems' with ID '{workItemId1}' in relationship 'assignedItems' does not exist.");
error1.Meta.Should().NotContainKey("requestBody");
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
error2.Title.Should().Be("A related resource does not exist.");
error2.Detail.Should().Be($"Related resource of type 'workItems' with ID '{workItemId2}' in relationship 'assignedItems' does not exist.");
error2.Meta.Should().NotContainKey("requestBody");
}
[Fact]
public async Task Cannot_create_on_relationship_type_mismatch()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "rgbColors",
id = "0A0B0C"
}
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Conflict);
error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found.");
error.Detail.Should().Be("Type 'rgbColors' is incompatible with type 'userAccounts' of relationship 'subscribers'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/subscribers/data[0]/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Can_create_with_duplicates()
{
// Arrange
UserAccount existingUserAccount = _fakers.UserAccount.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.UserAccounts.Add(existingUserAccount);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
data = new[]
{
new
{
type = "userAccounts",
id = existingUserAccount.StringId
},
new
{
type = "userAccounts",
id = existingUserAccount.StringId
}
}
}
}
}
};
const string route = "/workItems?include=subscribers";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Attributes.ShouldNotBeEmpty();
responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty();
responseDocument.Included.ShouldHaveCount(1);
responseDocument.Included[0].Type.Should().Be("userAccounts");
responseDocument.Included[0].Id.Should().Be(existingUserAccount.StringId);
int newWorkItemId = int.Parse(responseDocument.Data.SingleValue.Id.ShouldNotBeNull());
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Subscribers).FirstWithIdAsync(newWorkItemId);
workItemInDatabase.Subscribers.ShouldHaveCount(1);
workItemInDatabase.Subscribers.Single().Id.Should().Be(existingUserAccount.Id);
});
}
[Fact]
public async Task Cannot_create_with_missing_data_in_OneToMany_relationship()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
subscribers = new
{
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/subscribers");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_with_null_data_in_ManyToMany_relationship()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
tags = new
{
data = (object?)null
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of 'null'.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/tags/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_with_object_data_in_ManyToMany_relationship()
{
// Arrange
var requestBody = new
{
data = new
{
type = "workItems",
relationships = new
{
tags = new
{
data = new
{
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of an object.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/relationships/tags/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_resource_with_local_ID()
{
// Arrange
const string workItemLocalId = "wo-1";
var requestBody = new
{
data = new
{
type = "workItems",
lid = workItemLocalId,
relationships = new
{
children = new
{
data = new[]
{
new
{
type = "workItems",
lid = workItemLocalId
}
}
}
}
}
};
const string route = "/workItems";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'lid' element is not supported at this endpoint.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/data/lid");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
}
| |
/*
* Copyright (c) 2006-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.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
public partial class AgentManager
{
#region Enums
/// <summary>
/// Used to specify movement actions for your agent
/// </summary>
[Flags]
public enum ControlFlags
{
/// <summary>Empty flag</summary>
NONE = 0,
/// <summary>Move Forward (SL Keybinding: W/Up Arrow)</summary>
AGENT_CONTROL_AT_POS = 0x1 << CONTROL_AT_POS_INDEX,
/// <summary>Move Backward (SL Keybinding: S/Down Arrow)</summary>
AGENT_CONTROL_AT_NEG = 0x1 << CONTROL_AT_NEG_INDEX,
/// <summary>Move Left (SL Keybinding: Shift-(A/Left Arrow))</summary>
AGENT_CONTROL_LEFT_POS = 0x1 << CONTROL_LEFT_POS_INDEX,
/// <summary>Move Right (SL Keybinding: Shift-(D/Right Arrow))</summary>
AGENT_CONTROL_LEFT_NEG = 0x1 << CONTROL_LEFT_NEG_INDEX,
/// <summary>Not Flying: Jump/Flying: Move Up (SL Keybinding: E)</summary>
AGENT_CONTROL_UP_POS = 0x1 << CONTROL_UP_POS_INDEX,
/// <summary>Not Flying: Croutch/Flying: Move Down (SL Keybinding: C)</summary>
AGENT_CONTROL_UP_NEG = 0x1 << CONTROL_UP_NEG_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_PITCH_POS = 0x1 << CONTROL_PITCH_POS_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_PITCH_NEG = 0x1 << CONTROL_PITCH_NEG_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_YAW_POS = 0x1 << CONTROL_YAW_POS_INDEX,
/// <summary>Unused</summary>
AGENT_CONTROL_YAW_NEG = 0x1 << CONTROL_YAW_NEG_INDEX,
/// <summary>ORed with AGENT_CONTROL_AT_* if the keyboard is being used</summary>
AGENT_CONTROL_FAST_AT = 0x1 << CONTROL_FAST_AT_INDEX,
/// <summary>ORed with AGENT_CONTROL_LEFT_* if the keyboard is being used</summary>
AGENT_CONTROL_FAST_LEFT = 0x1 << CONTROL_FAST_LEFT_INDEX,
/// <summary>ORed with AGENT_CONTROL_UP_* if the keyboard is being used</summary>
AGENT_CONTROL_FAST_UP = 0x1 << CONTROL_FAST_UP_INDEX,
/// <summary>Fly</summary>
AGENT_CONTROL_FLY = 0x1 << CONTROL_FLY_INDEX,
/// <summary></summary>
AGENT_CONTROL_STOP = 0x1 << CONTROL_STOP_INDEX,
/// <summary>Finish our current animation</summary>
AGENT_CONTROL_FINISH_ANIM = 0x1 << CONTROL_FINISH_ANIM_INDEX,
/// <summary>Stand up from the ground or a prim seat</summary>
AGENT_CONTROL_STAND_UP = 0x1 << CONTROL_STAND_UP_INDEX,
/// <summary>Sit on the ground at our current location</summary>
AGENT_CONTROL_SIT_ON_GROUND = 0x1 << CONTROL_SIT_ON_GROUND_INDEX,
/// <summary>Whether mouselook is currently enabled</summary>
AGENT_CONTROL_MOUSELOOK = 0x1 << CONTROL_MOUSELOOK_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_AT_POS = 0x1 << CONTROL_NUDGE_AT_POS_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_AT_NEG = 0x1 << CONTROL_NUDGE_AT_NEG_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_LEFT_POS = 0x1 << CONTROL_NUDGE_LEFT_POS_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_LEFT_NEG = 0x1 << CONTROL_NUDGE_LEFT_NEG_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_UP_POS = 0x1 << CONTROL_NUDGE_UP_POS_INDEX,
/// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary>
AGENT_CONTROL_NUDGE_UP_NEG = 0x1 << CONTROL_NUDGE_UP_NEG_INDEX,
/// <summary></summary>
AGENT_CONTROL_TURN_LEFT = 0x1 << CONTROL_TURN_LEFT_INDEX,
/// <summary></summary>
AGENT_CONTROL_TURN_RIGHT = 0x1 << CONTROL_TURN_RIGHT_INDEX,
/// <summary>Set when the avatar is idled or set to away. Note that the away animation is
/// activated separately from setting this flag</summary>
AGENT_CONTROL_AWAY = 0x1 << CONTROL_AWAY_INDEX,
/// <summary></summary>
AGENT_CONTROL_LBUTTON_DOWN = 0x1 << CONTROL_LBUTTON_DOWN_INDEX,
/// <summary></summary>
AGENT_CONTROL_LBUTTON_UP = 0x1 << CONTROL_LBUTTON_UP_INDEX,
/// <summary></summary>
AGENT_CONTROL_ML_LBUTTON_DOWN = 0x1 << CONTROL_ML_LBUTTON_DOWN_INDEX,
/// <summary></summary>
AGENT_CONTROL_ML_LBUTTON_UP = 0x1 << CONTROL_ML_LBUTTON_UP_INDEX
}
#endregion Enums
#region AgentUpdate Constants
private const int CONTROL_AT_POS_INDEX = 0;
private const int CONTROL_AT_NEG_INDEX = 1;
private const int CONTROL_LEFT_POS_INDEX = 2;
private const int CONTROL_LEFT_NEG_INDEX = 3;
private const int CONTROL_UP_POS_INDEX = 4;
private const int CONTROL_UP_NEG_INDEX = 5;
private const int CONTROL_PITCH_POS_INDEX = 6;
private const int CONTROL_PITCH_NEG_INDEX = 7;
private const int CONTROL_YAW_POS_INDEX = 8;
private const int CONTROL_YAW_NEG_INDEX = 9;
private const int CONTROL_FAST_AT_INDEX = 10;
private const int CONTROL_FAST_LEFT_INDEX = 11;
private const int CONTROL_FAST_UP_INDEX = 12;
private const int CONTROL_FLY_INDEX = 13;
private const int CONTROL_STOP_INDEX = 14;
private const int CONTROL_FINISH_ANIM_INDEX = 15;
private const int CONTROL_STAND_UP_INDEX = 16;
private const int CONTROL_SIT_ON_GROUND_INDEX = 17;
private const int CONTROL_MOUSELOOK_INDEX = 18;
private const int CONTROL_NUDGE_AT_POS_INDEX = 19;
private const int CONTROL_NUDGE_AT_NEG_INDEX = 20;
private const int CONTROL_NUDGE_LEFT_POS_INDEX = 21;
private const int CONTROL_NUDGE_LEFT_NEG_INDEX = 22;
private const int CONTROL_NUDGE_UP_POS_INDEX = 23;
private const int CONTROL_NUDGE_UP_NEG_INDEX = 24;
private const int CONTROL_TURN_LEFT_INDEX = 25;
private const int CONTROL_TURN_RIGHT_INDEX = 26;
private const int CONTROL_AWAY_INDEX = 27;
private const int CONTROL_LBUTTON_DOWN_INDEX = 28;
private const int CONTROL_LBUTTON_UP_INDEX = 29;
private const int CONTROL_ML_LBUTTON_DOWN_INDEX = 30;
private const int CONTROL_ML_LBUTTON_UP_INDEX = 31;
private const int TOTAL_CONTROLS = 32;
#endregion AgentUpdate Constants
/// <summary>
/// Agent movement and camera control
///
/// Agent movement is controlled by setting specific <seealso cref="T:AgentManager.ControlFlags"/>
/// After the control flags are set, An AgentUpdate is required to update the simulator of the specified flags
/// This is most easily accomplished by setting one or more of the AgentMovement properties
///
/// Movement of an avatar is always based on a compass direction, for example AtPos will move the
/// agent from West to East or forward on the X Axis, AtNeg will of course move agent from
/// East to West or backward on the X Axis, LeftPos will be South to North or forward on the Y Axis
/// The Z axis is Up, finer grained control of movements can be done using the Nudge properties
/// </summary>
public partial class AgentMovement
{
#region Properties
/// <summary>Move agent positive along the X axis</summary>
public bool AtPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS, value); }
}
/// <summary>Move agent negative along the X axis</summary>
public bool AtNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG, value); }
}
/// <summary>Move agent positive along the Y axis</summary>
public bool LeftPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS, value); }
}
/// <summary>Move agent negative along the Y axis</summary>
public bool LeftNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG, value); }
}
/// <summary>Move agent positive along the Z axis</summary>
public bool UpPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_POS, value); }
}
/// <summary>Move agent negative along the Z axis</summary>
public bool UpNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG, value); }
}
/// <summary></summary>
public bool PitchPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_POS, value); }
}
/// <summary></summary>
public bool PitchNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_NEG, value); }
}
/// <summary></summary>
public bool YawPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS, value); }
}
/// <summary></summary>
public bool YawNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG, value); }
}
/// <summary></summary>
public bool FastAt
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_AT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_AT, value); }
}
/// <summary></summary>
public bool FastLeft
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_LEFT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_LEFT, value); }
}
/// <summary></summary>
public bool FastUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_UP, value); }
}
/// <summary>Causes simulator to make agent fly</summary>
public bool Fly
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FLY); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FLY, value); }
}
/// <summary>Stop movement</summary>
public bool Stop
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STOP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STOP, value); }
}
/// <summary>Finish animation</summary>
public bool FinishAnim
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FINISH_ANIM); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FINISH_ANIM, value); }
}
/// <summary>Stand up from a sit</summary>
public bool StandUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP, value); }
}
/// <summary>Tells simulator to sit agent on ground</summary>
public bool SitOnGround
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND, value); }
}
/// <summary>Place agent into mouselook mode</summary>
public bool Mouselook
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK, value); }
}
/// <summary>Nudge agent positive along the X axis</summary>
public bool NudgeAtPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS, value); }
}
/// <summary>Nudge agent negative along the X axis</summary>
public bool NudgeAtNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG, value); }
}
/// <summary>Nudge agent positive along the Y axis</summary>
public bool NudgeLeftPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS, value); }
}
/// <summary>Nudge agent negative along the Y axis</summary>
public bool NudgeLeftNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG, value); }
}
/// <summary>Nudge agent positive along the Z axis</summary>
public bool NudgeUpPos
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS, value); }
}
/// <summary>Nudge agent negative along the Z axis</summary>
public bool NudgeUpNeg
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG, value); }
}
/// <summary></summary>
public bool TurnLeft
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT, value); }
}
/// <summary></summary>
public bool TurnRight
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT, value); }
}
/// <summary>Tell simulator to mark agent as away</summary>
public bool Away
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AWAY); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AWAY, value); }
}
/// <summary></summary>
public bool LButtonDown
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN, value); }
}
/// <summary></summary>
public bool LButtonUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP, value); }
}
/// <summary></summary>
public bool MLButtonDown
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN, value); }
}
/// <summary></summary>
public bool MLButtonUp
{
get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP); }
set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP, value); }
}
/// <summary>
/// Returns "always run" value, or changes it by sending a SetAlwaysRunPacket
/// </summary>
public bool AlwaysRun
{
get
{
return alwaysRun;
}
set
{
alwaysRun = value;
SetAlwaysRunPacket run = new SetAlwaysRunPacket();
run.AgentData.AgentID = Client.Self.AgentID;
run.AgentData.SessionID = Client.Self.SessionID;
run.AgentData.AlwaysRun = alwaysRun;
Client.Network.SendPacket(run);
}
}
/// <summary>The current value of the agent control flags</summary>
public uint AgentControls
{
get { return agentControls; }
}
/// <summary>Gets or sets the interval in milliseconds at which
/// AgentUpdate packets are sent to the current simulator. Setting
/// this to a non-zero value will also enable the packet sending if
/// it was previously off, and setting it to zero will disable</summary>
public int UpdateInterval
{
get
{
return updateInterval;
}
set
{
if (value > 0)
{
if (updateTimer != null)
{
updateTimer.Change(value, value);
}
updateInterval = value;
}
else
{
if (updateTimer != null)
{
updateTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
updateInterval = 0;
}
}
}
/// <summary>Gets or sets whether AgentUpdate packets are sent to
/// the current simulator</summary>
public bool UpdateEnabled
{
get { return (updateInterval != 0); }
}
/// <summary>Reset movement controls every time we send an update</summary>
public bool AutoResetControls
{
get { return autoResetControls; }
set { autoResetControls = value; }
}
#endregion Properties
/// <summary>Agent camera controls</summary>
public AgentCamera Camera;
/// <summary>Currently only used for hiding your group title</summary>
public AgentFlags Flags = AgentFlags.None;
/// <summary>Action state of the avatar, which can currently be
/// typing and editing</summary>
public AgentState State = AgentState.None;
/// <summary></summary>
public Quaternion BodyRotation = Quaternion.Identity;
/// <summary></summary>
public Quaternion HeadRotation = Quaternion.Identity;
#region Change tracking
/// <summary></summary>
private Quaternion LastBodyRotation;
/// <summary></summary>
private Quaternion LastHeadRotation;
/// <summary></summary>
private Vector3 LastCameraCenter;
/// <summary></summary>
private Vector3 LastCameraXAxis;
/// <summary></summary>
private Vector3 LastCameraYAxis;
/// <summary></summary>
private Vector3 LastCameraZAxis;
/// <summary></summary>
private float LastFar;
#endregion Change tracking
private bool alwaysRun;
private GridClient Client;
private uint agentControls;
private int duplicateCount;
private AgentState lastState;
/// <summary>Timer for sending AgentUpdate packets</summary>
private Timer updateTimer;
private int updateInterval;
private bool autoResetControls;
/// <summary>Default constructor</summary>
public AgentMovement(GridClient client)
{
Client = client;
Camera = new AgentCamera();
Client.Network.LoginProgress += Network_OnConnected;
Client.Network.Disconnected += Network_OnDisconnected;
updateInterval = Settings.DEFAULT_AGENT_UPDATE_INTERVAL;
}
private void CleanupTimer()
{
if (updateTimer != null)
{
updateTimer.Dispose();
updateTimer = null;
}
}
private void Network_OnDisconnected(object sender, DisconnectedEventArgs e)
{
CleanupTimer();
}
private void Network_OnConnected(object sender, LoginProgressEventArgs e)
{
if (e.Status == LoginStatus.Success)
{
CleanupTimer();
updateTimer = new Timer(new TimerCallback(UpdateTimer_Elapsed), null, updateInterval, updateInterval);
}
}
/// <summary>
/// Send an AgentUpdate with the camera set at the current agent
/// position and pointing towards the heading specified
/// </summary>
/// <param name="heading">Camera rotation in radians</param>
/// <param name="reliable">Whether to send the AgentUpdate reliable
/// or not</param>
public void UpdateFromHeading(double heading, bool reliable)
{
Camera.Position = Client.Self.SimPosition;
Camera.LookDirection(heading);
BodyRotation.Z = (float)Math.Sin(heading / 2.0d);
BodyRotation.W = (float)Math.Cos(heading / 2.0d);
HeadRotation = BodyRotation;
SendUpdate(reliable);
}
/// <summary>
/// Rotates the avatar body and camera toward a target position.
/// This will also anchor the camera position on the avatar
/// </summary>
/// <param name="target">Region coordinates to turn toward</param>
public bool TurnToward(Vector3 target)
{
return TurnToward(target, true);
}
/// <summary>
/// Rotates the avatar body and camera toward a target position.
/// This will also anchor the camera position on the avatar
/// </summary>
/// <param name="target">Region coordinates to turn toward</param>
/// <param name="sendUpdate">whether to send update or not</param>
public bool TurnToward(Vector3 target, bool sendUpdate)
{
if (Client.Settings.SEND_AGENT_UPDATES)
{
Quaternion parentRot = Quaternion.Identity;
if (Client.Self.SittingOn > 0)
{
if (!Client.Network.CurrentSim.ObjectsPrimitives.ContainsKey(Client.Self.SittingOn))
{
Logger.Log("Attempted TurnToward but parent prim is not in dictionary", Helpers.LogLevel.Warning, Client);
return false;
}
else parentRot = Client.Network.CurrentSim.ObjectsPrimitives[Client.Self.SittingOn].Rotation;
}
Quaternion between = Vector3.RotationBetween(Vector3.UnitX, Vector3.Normalize(target - Client.Self.SimPosition));
Quaternion rot = between * (Quaternion.Identity / parentRot);
BodyRotation = rot;
HeadRotation = rot;
Camera.LookAt(Client.Self.SimPosition, target);
if (sendUpdate) SendUpdate();
return true;
}
else
{
Logger.Log("Attempted TurnToward but agent updates are disabled", Helpers.LogLevel.Warning, Client);
return false;
}
}
/// <summary>
/// Send new AgentUpdate packet to update our current camera
/// position and rotation
/// </summary>
public void SendUpdate()
{
SendUpdate(false, Client.Network.CurrentSim);
}
/// <summary>
/// Send new AgentUpdate packet to update our current camera
/// position and rotation
/// </summary>
/// <param name="reliable">Whether to require server acknowledgement
/// of this packet</param>
public void SendUpdate(bool reliable)
{
SendUpdate(reliable, Client.Network.CurrentSim);
}
/// <summary>
/// Send new AgentUpdate packet to update our current camera
/// position and rotation
/// </summary>
/// <param name="reliable">Whether to require server acknowledgement
/// of this packet</param>
/// <param name="simulator">Simulator to send the update to</param>
public void SendUpdate(bool reliable, Simulator simulator)
{
// Since version 1.40.4 of the Linden simulator, sending this update
// causes corruption of the agent position in the simulator
if (simulator != null && (!simulator.AgentMovementComplete))
return;
Vector3 origin = Camera.Position;
Vector3 xAxis = Camera.LeftAxis;
Vector3 yAxis = Camera.AtAxis;
Vector3 zAxis = Camera.UpAxis;
// Attempted to sort these in a rough order of how often they might change
if (agentControls == 0 &&
yAxis == LastCameraYAxis &&
origin == LastCameraCenter &&
State == lastState &&
HeadRotation == LastHeadRotation &&
BodyRotation == LastBodyRotation &&
xAxis == LastCameraXAxis &&
Camera.Far == LastFar &&
zAxis == LastCameraZAxis)
{
++duplicateCount;
}
else
{
duplicateCount = 0;
}
if (Client.Settings.DISABLE_AGENT_UPDATE_DUPLICATE_CHECK || duplicateCount < 10)
{
// Store the current state to do duplicate checking
LastHeadRotation = HeadRotation;
LastBodyRotation = BodyRotation;
LastCameraYAxis = yAxis;
LastCameraCenter = origin;
LastCameraXAxis = xAxis;
LastCameraZAxis = zAxis;
LastFar = Camera.Far;
lastState = State;
// Build the AgentUpdate packet and send it
AgentUpdatePacket update = new AgentUpdatePacket();
update.Header.Reliable = reliable;
update.AgentData.AgentID = Client.Self.AgentID;
update.AgentData.SessionID = Client.Self.SessionID;
update.AgentData.HeadRotation = HeadRotation;
update.AgentData.BodyRotation = BodyRotation;
update.AgentData.CameraAtAxis = yAxis;
update.AgentData.CameraCenter = origin;
update.AgentData.CameraLeftAxis = xAxis;
update.AgentData.CameraUpAxis = zAxis;
update.AgentData.Far = Camera.Far;
update.AgentData.State = (byte)State;
update.AgentData.ControlFlags = agentControls;
update.AgentData.Flags = (byte)Flags;
Client.Network.SendPacket(update, simulator);
if (autoResetControls) {
ResetControlFlags();
}
}
}
/// <summary>
/// Builds an AgentUpdate packet entirely from parameters. This
/// will not touch the state of Self.Movement or
/// Self.Movement.Camera in any way
/// </summary>
/// <param name="controlFlags"></param>
/// <param name="position"></param>
/// <param name="forwardAxis"></param>
/// <param name="leftAxis"></param>
/// <param name="upAxis"></param>
/// <param name="bodyRotation"></param>
/// <param name="headRotation"></param>
/// <param name="farClip"></param>
/// <param name="reliable"></param>
/// <param name="flags"></param>
/// <param name="state"></param>
public void SendManualUpdate(AgentManager.ControlFlags controlFlags, Vector3 position, Vector3 forwardAxis,
Vector3 leftAxis, Vector3 upAxis, Quaternion bodyRotation, Quaternion headRotation, float farClip,
AgentFlags flags, AgentState state, bool reliable)
{
// Since version 1.40.4 of the Linden simulator, sending this update
// causes corruption of the agent position in the simulator
if (Client.Network.CurrentSim != null && (!Client.Network.CurrentSim.HandshakeComplete))
return;
AgentUpdatePacket update = new AgentUpdatePacket();
update.AgentData.AgentID = Client.Self.AgentID;
update.AgentData.SessionID = Client.Self.SessionID;
update.AgentData.BodyRotation = bodyRotation;
update.AgentData.HeadRotation = headRotation;
update.AgentData.CameraCenter = position;
update.AgentData.CameraAtAxis = forwardAxis;
update.AgentData.CameraLeftAxis = leftAxis;
update.AgentData.CameraUpAxis = upAxis;
update.AgentData.Far = farClip;
update.AgentData.ControlFlags = (uint)controlFlags;
update.AgentData.Flags = (byte)flags;
update.AgentData.State = (byte)state;
update.Header.Reliable = reliable;
Client.Network.SendPacket(update);
}
private bool GetControlFlag(ControlFlags flag)
{
return (agentControls & (uint)flag) != 0;
}
private void SetControlFlag(ControlFlags flag, bool value)
{
if (value) agentControls |= (uint)flag;
else agentControls &= ~((uint)flag);
}
public void ResetControlFlags()
{
// Reset all of the flags except for persistent settings like
// away, fly, mouselook, and crouching
agentControls &=
(uint)(ControlFlags.AGENT_CONTROL_AWAY |
ControlFlags.AGENT_CONTROL_FLY |
ControlFlags.AGENT_CONTROL_MOUSELOOK |
ControlFlags.AGENT_CONTROL_UP_NEG);
}
private void UpdateTimer_Elapsed(object obj)
{
if (Client.Network.Connected && Client.Settings.SEND_AGENT_UPDATES)
{
//Send an AgentUpdate packet
SendUpdate(false, Client.Network.CurrentSim);
}
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using HETSAPI.Models;
using HETSAPI.ViewModels;
using HETSAPI.Mappings;
using Microsoft.AspNetCore.Http;
namespace HETSAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class RentalRequestService : ServiceBase, IRentalRequestService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public RentalRequestService(IHttpContextAccessor httpContextAccessor, DbAppContext context) : base(httpContextAccessor, context)
{
_context = context;
}
private void AdjustRecord(RentalRequest item)
{
if (item != null)
{
// Adjust the record to allow it to be updated / inserted
if (item.LocalArea != null)
{
item.LocalArea = _context.LocalAreas.FirstOrDefault(a => a.Id == item.LocalArea.Id);
}
if (item.Project != null)
{
item.Project = _context.Projects.FirstOrDefault(a => a.Id == item.Project.Id);
}
if (item.DistrictEquipmentType != null)
{
item.DistrictEquipmentType = _context.DistrictEquipmentTypes
.Include(x => x.EquipmentType)
.First(a => a.Id == item.DistrictEquipmentType.Id);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">Project created</response>
public virtual IActionResult RentalrequestsBulkPostAsync(RentalRequest[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (RentalRequest item in items)
{
AdjustRecord(item);
bool exists = _context.RentalRequests.Any(a => a.Id == item.Id);
if (exists)
{
_context.RentalRequests.Update(item);
}
else
{
_context.RentalRequests.Add(item);
}
}
// Save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
public virtual IActionResult RentalrequestsGetAsync()
{
var result = _context.RentalRequests
.Include(x => x.RentalRequestAttachments)
.Include(x => x.DistrictEquipmentType)
.Include(x => x.FirstOnRotationList)
.Include(x => x.LocalArea.ServiceArea.District.Region)
.Include(x => x.Notes)
.Include(x => x.Project)
.Include(x => x.RentalRequestRotationList)
.ToList();
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular RentalRequest</remarks>
/// <param name="id">id of RentalRequest to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">RentalRequest not found</response>
public virtual IActionResult RentalrequestsIdAttachmentsGetAsync(int id)
{
bool exists = _context.RentalRequests.Any(a => a.Id == id);
if (exists)
{
RentalRequest rentalRequest = _context.RentalRequests
.Include(x => x.Attachments)
.First(a => a.Id == id);
var result = MappingExtensions.GetAttachmentListAsViewModel(rentalRequest.Attachments);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Project to delete</param>
/// <response code="200">OK</response>
/// <response code="404">Project not found</response>
public virtual IActionResult RentalrequestsIdDeletePostAsync(int id)
{
var item = _context.RentalRequests
.Include(x => x.RentalRequestRotationList)
.FirstOrDefault(a => a.Id == id);
if (item != null)
{
// Remove the rotation list if it exists.
if (item.RentalRequestRotationList != null)
{
foreach (var rentalRequestRotationList in item.RentalRequestRotationList)
{
_context.RentalRequestRotationLists.Remove(rentalRequestRotationList);
}
}
_context.RentalRequests.Remove(item);
// Save the changes
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular RentalRequest</remarks>
/// <param name="id">id of RentalRequest to fetch History for</param>
/// <response code="200">OK</response>
public virtual IActionResult RentalrequestsIdHistoryGetAsync(int id, int? offset, int? limit)
{
bool exists = _context.RentalRequests.Any(a => a.Id == id);
if (exists)
{
RentalRequest rentalRequest = _context.RentalRequests
.Include(x => x.History)
.First(a => a.Id == id);
List<History> data = rentalRequest.History.OrderByDescending(y => y.LastUpdateTimestamp).ToList();
if (offset == null)
{
offset = 0;
}
if (limit == null)
{
limit = data.Count() - offset;
}
List<HistoryViewModel> result = new List<HistoryViewModel>();
for (int i = (int)offset; i < data.Count() && i < offset + limit; i++)
{
result.Add(data[i].ToViewModel(id));
}
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Add a History record to the RentalRequest</remarks>
/// <param name="id">id of RentalRequest to add History for</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="201">History created</response>
public virtual IActionResult RentalrequestsIdHistoryPostAsync(int id, History item)
{
HistoryViewModel result = new HistoryViewModel();
bool exists = _context.RentalRequests.Any(a => a.Id == id);
if (exists)
{
RentalRequest rentalRequest = _context.RentalRequests
.Include(x => x.History)
.First(a => a.Id == id);
if (rentalRequest.History == null)
{
rentalRequest.History = new List<History>();
}
// force add
item.Id = 0;
rentalRequest.History.Add(item);
_context.RentalRequests.Update(rentalRequest);
_context.SaveChanges();
}
result.HistoryText = item.HistoryText;
result.Id = item.Id;
result.LastUpdateTimestamp = item.LastUpdateTimestamp;
result.LastUpdateUserid = item.LastUpdateUserid;
result.AffectedEntityId = id;
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Project to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Project not found</response>
public virtual IActionResult RentalrequestsIdGetAsync(int id)
{
var exists = _context.RentalRequests.Any(a => a.Id == id);
if (exists)
{
var result = _context.RentalRequests
.Include(x => x.RentalRequestAttachments)
.Include(x => x.DistrictEquipmentType)
.Include(x => x.FirstOnRotationList)
.Include(x => x.LocalArea.ServiceArea.District.Region)
.Include(x => x.Notes)
.Include(x => x.Project.PrimaryContact)
.Include(x => x.RentalRequestRotationList).ThenInclude(y => y.Equipment)
.First(a => a.Id == id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="id">id of Project to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">Project not found</response>
public virtual IActionResult RentalrequestsIdPutAsync(int id, RentalRequest item)
{
AdjustRecord(item);
var exists = _context.RentalRequests.Any(a => a.Id == id);
if (exists && id == item.Id)
{
_context.RentalRequests.Update(item);
// Save the changes
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
private void BuildRentalRequestRotationList(RentalRequest item)
{
// validate input parameters
if (item != null && item.LocalArea != null && item.DistrictEquipmentType != null && item.DistrictEquipmentType.EquipmentType != null)
{
int currentSortOrder = 1;
item.RentalRequestRotationList = new List<RentalRequestRotationList>();
// first get the localAreaRotationList.askNextBlock1 for the given local area.
LocalAreaRotationList localAreaRotationList = _context.LocalAreaRotationLists
.Include(x => x.LocalArea)
.Include(x => x.AskNextBlock1)
.Include(x => x.AskNextBlock2)
.Include(x => x.AskNextBlockOpen)
.FirstOrDefault(x => x.LocalArea.Id == item.LocalArea.Id);
int numberOfBlocks = item.DistrictEquipmentType.EquipmentType.NumberOfBlocks;
for (int currentBlock = 1; currentBlock <= numberOfBlocks; currentBlock++)
{
int currentBlockSortOrder = 0;
// start by getting the current set of equipment for the given equipment type.
List<Equipment> blockEquipment = _context.Equipments
.Where(x => x.DistrictEquipmentType == item.DistrictEquipmentType && x.BlockNumber == currentBlock && x.LocalArea.Id == item.LocalArea.Id)
.OrderByDescending(x => x.Seniority)
.ToList();
int listSize = blockEquipment.Count;
// find the starting position.
int currentPosition = 0;
Equipment seeking = null;
if (localAreaRotationList != null)
{
switch (currentBlock)
{
case 1:
seeking = localAreaRotationList.AskNextBlock1;
break;
case 2:
seeking = localAreaRotationList.AskNextBlock2;
break;
case 3:
seeking = localAreaRotationList.AskNextBlockOpen;
break;
}
}
if (localAreaRotationList != null && seeking != null)
{
for (int i = 0; i < listSize; i++)
{
if (blockEquipment[i] != null && blockEquipment[i].Id == seeking.Id)
{
currentPosition = i;
}
}
}
// next pass sets the rotation list sort order.
for (int i = 0; i < listSize; i++)
{
RentalRequestRotationList rentalRequestRotationList = new RentalRequestRotationList();
rentalRequestRotationList.Equipment = blockEquipment[currentPosition];
rentalRequestRotationList.CreateTimestamp = DateTime.UtcNow;
rentalRequestRotationList.RotationListSortOrder = currentSortOrder;
item.RentalRequestRotationList.Add(rentalRequestRotationList);
currentPosition++;
currentBlockSortOrder++;
currentSortOrder++;
if (currentPosition >= listSize)
{
currentPosition = 0;
}
}
}
}
}
/// <summary>
/// Adjust the RentalRequestRotationList record
/// </summary>
/// <param name="item"></param>
private void AdjustRRRLRecord(RentalRequestRotationList item)
{
if (item != null)
{
if (item.Equipment != null)
{
item.Equipment = _context.Equipments.FirstOrDefault(a => a.Id == item.Equipment.Id);
}
if (item.RentalAgreement != null)
{
item.RentalAgreement = _context.RentalAgreements.FirstOrDefault(a => a.Id == item.RentalAgreement.Id);
}
}
}
/// <summary>
///
/// </summary>
/// <remarks>Updates a rental request rotation list entry. Side effect is the LocalAreaRotationList is also updated</remarks>
/// <param name="id">id of RentalRequest to update</param>
/// <param name="rentalRequestRotationListId">id of RentalRequestRotationList to update</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">RentalRequestRotationList not found</response>
public virtual IActionResult RentalrequestsIdRentalrequestrotationlistRentalRequestRotationListIdPutAsync(int id, int rentalRequestRotationListId, RentalRequestRotationList item)
{
// update the rental request rotation list item.
AdjustRRRLRecord(item);
var exists = _context.RentalRequestRotationLists.Any(a => a.Id == rentalRequestRotationListId);
if (exists && rentalRequestRotationListId == item.Id)
{
_context.RentalRequestRotationLists.Update(item);
// Save the changes
_context.SaveChanges();
_context.Entry(item).State = EntityState.Detached;
// now update the corresponding entry in the LocalAreaRotationList.
_context.UpdateLocalAreaRotationList(item.Id);
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">Project created</response>
public virtual IActionResult RentalrequestsPostAsync(RentalRequest item)
{
if (item != null)
{
AdjustRecord(item);
var exists = _context.RentalRequests.Any(a => a.Id == item.Id);
if (exists)
{
_context.RentalRequests.Update(item);
}
else
{
// record not found
BuildRentalRequestRotationList(item);
_context.RentalRequests.Add(item);
}
// Save the changes
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
return new StatusCodeResult(400);
}
}
/// <summary>
/// Searches Projects
/// </summary>
/// <remarks>Used for the project search page.</remarks>
/// <param name="localareasCSV">Local areas (comma seperated list of id numbers)</param>
/// <param name="project">name or partial name for a Project</param>
/// <param name="status">Status</param>
/// <param name="startDate">Inspection start date</param>
/// <param name="endDate">Inspection end date</param>
/// <response code="200">OK</response>
public virtual IActionResult RentalrequestsSearchGetAsync(string localareasCSV, string project, string status, DateTime? startDate, DateTime? endDate)
{
int?[] localareas = ParseIntArray(localareasCSV);
var data = _context.RentalRequests
.Include(x => x.LocalArea.ServiceArea.District.Region)
.Include(x => x.DistrictEquipmentType.EquipmentType)
.Include(x => x.Project.PrimaryContact)
.Select(x => x);
// Default search results must be limited to user
int? districtId = _context.GetDistrictIdByUserId(GetCurrentUserId()).Single();
data = data.Where(x => x.LocalArea.ServiceArea.DistrictId.Equals(districtId));
if (localareas != null && localareas.Length > 0)
{
data = data.Where(x => localareas.Contains(x.LocalArea.Id));
}
if (project != null)
{
data = data.Where(x => x.Project.Name.ToLowerInvariant().Contains(project.ToLowerInvariant()));
}
if (startDate != null)
{
data = data.Where(x => x.ExpectedStartDate >= startDate);
}
if (endDate != null)
{
data = data.Where(x => x.ExpectedStartDate <= endDate);
}
if (status != null)
{
// TODO: Change to enumerated type
data = data.Where(x => x.Status.ToLower() == status.ToLower());
}
var result = new List<RentalRequestSearchResultViewModel>();
foreach (var item in data)
{
if (item != null)
{
RentalRequestSearchResultViewModel newItem = item.ToViewModel();
result.Add(newItem);
}
}
// no calculated fields in a RentalRequest search yet.
return new ObjectResult(result);
}
}
}
| |
/*****************************************************************
* MPAPI - Message Passing API
* A framework for writing parallel and distributed applications
*
* Author : Frank Thomsen
* Web : http://sector0.dk
* Contact : mpapi@sector0.dk
* License : New BSD licence
*
* Copyright (c) 2008, Frank Thomsen
*
* Feel free to contact me with bugs and ideas.
*****************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MPAPI
{
public abstract class Worker : IWorker
{
private const int MessageCountWarningLimit = 10000; //the worker will give a warning if the number of waiting messages exceed this limit.
#region Static
private static Dictionary<int, Worker> _threadIdToWorkerMap = new Dictionary<int, Worker>();
private static void RegisterWorker(Worker worker)
{
lock (_threadIdToWorkerMap)
{
_threadIdToWorkerMap.Add(Thread.CurrentThread.ManagedThreadId, worker);
}
}
private static void UnregisterWorker()
{
lock (_threadIdToWorkerMap)
{
_threadIdToWorkerMap.Remove(Thread.CurrentThread.ManagedThreadId);
}
}
public static IWorker Current
{
get
{
lock (_threadIdToWorkerMap)
{
if (_threadIdToWorkerMap.ContainsKey(Thread.CurrentThread.ManagedThreadId))
return _threadIdToWorkerMap[Thread.CurrentThread.ManagedThreadId];
return null;
}
}
}
#endregion
private Node _node;
private ushort _id;
private LinkedList<Message> _messageQueue = new LinkedList<Message>();
private ManualResetEvent _messageQueueWaitHandle = new ManualResetEvent(false);
private WorkerAddress _monitoringWorker = null;
private List<int> _messageFilters = new List<int>();
#region Properties
public IWorkerNode Node
{
get { return _node; }
}
public ushort Id
{
get { return _id; }
set { _id = value; }
}
#endregion
public abstract void Main();
internal void SetNode(Node node) { _node = node; }
internal void SetMonitoringWorker(WorkerAddress monitoringWorker)
{
_monitoringWorker = monitoringWorker;
}
/// <summary>
/// This method is called by the framework
/// </summary>
internal void _Main()
{
RegisterWorker(this);
try
{
Main();
if (_monitoringWorker != null)
{
Message msg = new Message(MessageLevel.System, _monitoringWorker, new WorkerAddress(_node.GetId(), _id), SystemMessages.WorkerTerminated, null);
_node.QueueMessage(msg);
}
OnWorkerTerminated();
}
catch (Exception e)
{
WorkerAddress workerAddress = new WorkerAddress(_node.GetId(), _id);
Log.Error("Worker {0} crashed with exception {1}", workerAddress, e.Message);
if (_monitoringWorker != null)
{
Message msg = new Message(MessageLevel.System, _monitoringWorker, workerAddress, SystemMessages.WorkerTerminatedAbnormally, e);
_node.QueueMessage(msg);
}
OnWorkerTerminatedAbnormally(e);
}
_node.WorkerTerminated(_id);
UnregisterWorker();
}
/// <summary>
/// This method is called right before a worker terminates normally.
/// </summary>
public virtual void OnWorkerTerminated()
{
}
/// <summary>
/// This method is called right before a worker terminates
/// abnormally due to an exception.
/// </summary>
/// <param name="e"></param>
public virtual void OnWorkerTerminatedAbnormally(Exception e)
{
}
/// <summary>
/// This method is called whenever a remote node registers on the registration server.
/// </summary>
/// <param name="nodeId"></param>
public virtual void OnRemoteNodeRegistered(ushort nodeId)
{
}
/// <summary>
/// This method is called whenever a remote node unregisters from the registration server.
/// </summary>
/// <param name="nodeId"></param>
public virtual void OnRemoteNodeUnregistered(ushort nodeId)
{
}
internal void PutMessage(MessageLevel messageLevel, ushort receiverNodeId, ushort receiverWorkerId, ushort senderNodeId, ushort senderWorkerId, int messageType, object content)
{
lock (_messageFilters)
{
if (_messageFilters.Count > 0 && !_messageFilters.Contains(messageType))
return;
}
lock (_messageQueue)
{
_messageQueue.AddLast(new Message(messageLevel, new WorkerAddress(receiverNodeId, receiverWorkerId), new WorkerAddress(senderNodeId, senderWorkerId), messageType, content));
//if (_messageQueue.Count >= MessageCountWarningLimit)
// Log.Warning("Mail box contains {0} unread messages. WorkerId:{1}", _messageQueue.Count, _id);
_messageQueueWaitHandle.Set();
}
}
#region Message passing primitives and other control primitives
/// <summary>
/// Sets the message types that this worker is interested in.
/// </summary>
/// <param name="filters"></param>
public void SetMessageFilter(params int[] filters)
{
lock (_messageFilters)
{
_messageFilters.Clear();
_messageFilters.AddRange(filters);
}
}
/// <summary>
/// Makes the thread running this worker sleep for a period of time.
/// </summary>
/// <param name="ms">The number of milliseconds to sleep.</param>
public void Sleep(int ms)
{
Thread.Sleep(ms);
}
/// <summary>
/// Enables this worker to receive system messages when the monitoree terminates, either
/// normally or abnormally.
/// </summary>
/// <param name="monitoree"></param>
public void Monitor(WorkerAddress monitoree)
{
_node._Monitor(new WorkerAddress(_node.GetId(), _id), monitoree);
}
/// <summary>
/// Spawns a new worker locally.
/// </summary>
/// <typeparam name="TWorkerType">The type of worker to spawn. Must inherit from Worker.</typeparam>
/// <returns>The address of the new worker if successfull, otherwise null.</returns>
public WorkerAddress Spawn<TWorkerType>() where TWorkerType : Worker
{
ushort workerId;
WorkerAddress workerAddress = null;
if (_node.Spawn(typeof(TWorkerType), out workerId))
workerAddress = new WorkerAddress(_node.GetId(), workerId);
return workerAddress;
}
/// <summary>
/// Spawns a new worker at the specified node.
/// </summary>
/// <typeparam name="TWorkerType">The type of worker to spawn. Must inherit from Worker.</typeparam>
/// <param name="nodeId">Id of the node to spawn the worker at.</param>
/// <returns>The address of the new worker if successfull, otherwise null.</returns>
public WorkerAddress Spawn<TWorkerType>(ushort nodeId) where TWorkerType : Worker
{
ushort workerId;
WorkerAddress workerAddress = null;
if (_node.Spawn(typeof(TWorkerType), nodeId, out workerId))
workerAddress = new WorkerAddress(nodeId, workerId);
return workerAddress;
}
/// <summary>
/// Spawns a new worker at the specified node.
/// </summary>
/// <param name="workerTypeName">Fully qualified name of worker type. Must inherit from Worker.</param>
/// <param name="nodeId">Id of the node to spawn the worker at.</param>
/// <returns>The address of the new worker if successfull, otherwise null.</returns>
public WorkerAddress Spawn(string workerTypeName, ushort nodeId)
{
ushort workerId;
WorkerAddress workerAddress = null;
if (_node.Spawn(workerTypeName, nodeId, out workerId))
workerAddress = new WorkerAddress(nodeId, workerId);
return workerAddress;
}
/// <summary>
/// Sends a message.
/// </summary>
/// <param name="receiverAddress">Address of the receicer.</param>
/// <param name="messageType">Type of message - user specific.</param>
/// <param name="content">The contents of the message.</param>
public void Send(WorkerAddress receiverAddress, int messageType, object content)
{
if (SystemMessages.IsSystemMessageType(messageType))
{
Log.Error("Message types smaller than 0 are reserved for system messages. Message type : {0}", messageType);
return;
}
Message msg = new Message(MessageLevel.User, receiverAddress, new WorkerAddress(_node.GetId(), _id), messageType, content);
_node.QueueMessage(msg);
}
/// <summary>
/// Broadcasts a message to all workers.
/// </summary>
/// <param name="messageType">Type of message - user specific.</param>
/// <param name="content">The contents of the message.</param>
public void Broadcast(int messageType, object content)
{
Message msg = new Message(MessageLevel.User, new WorkerAddress(ushort.MaxValue, ushort.MaxValue), new WorkerAddress(_node.GetId(), _id), messageType, content);
_node.QueueMessage(msg);
}
/// <summary>
/// Fetches a message from the message queue.
/// This method blocks until there are any messages.
/// </summary>
/// <returns>The first message in the queue.</returns>
public Message Receive()
{
Message msg = null;
LinkedListNode<Message> msgNode;
do
{
_messageQueueWaitHandle.WaitOne();
lock (_messageQueue)
{
msgNode = _messageQueue.First;
if (msgNode != null)
{
msg = msgNode.Value;
_messageQueue.RemoveFirst();
}
if (msg == null) //nothing yet
_messageQueueWaitHandle.Reset();
}
}
while (msg == null);
return msg;
}
/// <summary>
/// Fetches a message from the message queue from the specified sender.
/// This method blocks until there are any messages fullfilling the criteria.
/// </summary>
/// <param name="senderAddress">The address of the sender.</param>
/// <returns>The first message in the queue from the specified sender.</returns>
public Message Receive(WorkerAddress senderAddress)
{
Message msg = null;
LinkedListNode<Message> msgNode;
do
{
_messageQueueWaitHandle.WaitOne();
lock (_messageQueue)
{
msgNode = _messageQueue.First;
//traverse all messages to see if there are any that matches the search criteria
while (msgNode != null && msg == null)
{
if (msgNode.Value.SenderAddress == senderAddress)
{
msg = msgNode.Value;
_messageQueue.Remove(msgNode);
}
else
msgNode = msgNode.Next;
}
if (msg == null) //nothing yet
_messageQueueWaitHandle.Reset();
}
}
while (msg == null);
return msg;
}
/// <summary>
/// Fetches a message from the message queue with the specified message type.
/// This method blocks until there are any messages fullfilling the criteria.
/// </summary>
/// <param name="messageType">The message type.</param>
/// <returns>The first message in the queue with the specified message type.</returns>
public Message Receive(int messageType)
{
Message msg = null;
LinkedListNode<Message> msgNode;
do
{
_messageQueueWaitHandle.WaitOne();
lock (_messageQueue)
{
msgNode = _messageQueue.First;
//traverse all messages to see if there are any that matches the search criteria
while (msgNode != null && msg == null)
{
if (msgNode.Value.MessageType == messageType)
{
msg = msgNode.Value;
_messageQueue.Remove(msgNode);
}
else
msgNode = msgNode.Next;
}
if (msg == null) //nothing yet
_messageQueueWaitHandle.Reset();
}
}
while (msg == null);
return msg;
}
/// <summary>
/// Fetches a message from the message queue with the specified sender address and message type.
/// This method blocks until there are any messages fullfilling the criteria.
/// </summary>
/// <param name="senderAddress">The sender address.</param>
/// <param name="messageType">The message type.</param>
/// <returns>The first message in the queue with the specified sender address and message type</returns>
public Message Receive(WorkerAddress senderAddress, int messageType)
{
Message msg = null;
LinkedListNode<Message> msgNode;
do
{
_messageQueueWaitHandle.WaitOne();
lock (_messageQueue)
{
msgNode = _messageQueue.First;
//traverse all messages to see if there are any that matches the search criteria
while (msgNode != null && msg == null)
{
if (msgNode.Value.SenderAddress == senderAddress && msgNode.Value.MessageType == messageType)
{
msg = msgNode.Value;
_messageQueue.Remove(msgNode);
}
else
msgNode = msgNode.Next;
}
if (msg == null) //nothing yet
_messageQueueWaitHandle.Reset();
}
}
while (msg == null);
return msg;
}
/// <summary>
/// Checks if there are any messages in the message queue.
/// </summary>
/// <returns></returns>
public bool HasMessages()
{
lock (_messageQueue)
{
return _messageQueue.Count > 0;
}
}
/// <summary>
/// Checks if there are any messages from the specified sender in the message queue.
/// </summary>
/// <param name="senderAddress"></param>
/// <returns></returns>
public bool HasMessages(WorkerAddress senderAddress)
{
lock (_messageQueue)
{
foreach (Message msg in _messageQueue)
if (msg.SenderAddress == senderAddress)
return true;
}
return false;
}
/// <summary>
/// Checks if there are any messages with the specified message type in the message queue.
/// </summary>
/// <param name="messageType"></param>
/// <returns></returns>
public bool HasMessages(int messageType)
{
lock (_messageQueue)
{
foreach (Message msg in _messageQueue)
if (msg.MessageType == messageType)
return true;
}
return false;
}
/// <summary>
/// Checks if there are any message from the specified sender and with the specified message type in the message queue.
/// </summary>
/// <param name="senderAddress"></param>
/// <param name="messageType"></param>
/// <returns></returns>
public bool HasMessages(WorkerAddress senderAddress, int messageType)
{
lock (_messageQueue)
{
foreach (Message msg in _messageQueue)
if (msg.SenderAddress == senderAddress && msg.MessageType == messageType)
return true;
}
return false;
}
#endregion
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetAzureTargetsSpectraS3Request : Ds3Request
{
private string _accountName;
public string AccountName
{
get { return _accountName; }
set { WithAccountName(value); }
}
private TargetReadPreferenceType? _defaultReadPreference;
public TargetReadPreferenceType? DefaultReadPreference
{
get { return _defaultReadPreference; }
set { WithDefaultReadPreference(value); }
}
private bool? _https;
public bool? Https
{
get { return _https; }
set { WithHttps(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private bool? _permitGoingOutOfSync;
public bool? PermitGoingOutOfSync
{
get { return _permitGoingOutOfSync; }
set { WithPermitGoingOutOfSync(value); }
}
private Quiesced? _quiesced;
public Quiesced? Quiesced
{
get { return _quiesced; }
set { WithQuiesced(value); }
}
private TargetState? _state;
public TargetState? State
{
get { return _state; }
set { WithState(value); }
}
public GetAzureTargetsSpectraS3Request WithAccountName(string accountName)
{
this._accountName = accountName;
if (accountName != null)
{
this.QueryParams.Add("account_name", accountName);
}
else
{
this.QueryParams.Remove("account_name");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithDefaultReadPreference(TargetReadPreferenceType? defaultReadPreference)
{
this._defaultReadPreference = defaultReadPreference;
if (defaultReadPreference != null)
{
this.QueryParams.Add("default_read_preference", defaultReadPreference.ToString());
}
else
{
this.QueryParams.Remove("default_read_preference");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithHttps(bool? https)
{
this._https = https;
if (https != null)
{
this.QueryParams.Add("https", https.ToString());
}
else
{
this.QueryParams.Remove("https");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithPermitGoingOutOfSync(bool? permitGoingOutOfSync)
{
this._permitGoingOutOfSync = permitGoingOutOfSync;
if (permitGoingOutOfSync != null)
{
this.QueryParams.Add("permit_going_out_of_sync", permitGoingOutOfSync.ToString());
}
else
{
this.QueryParams.Remove("permit_going_out_of_sync");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithQuiesced(Quiesced? quiesced)
{
this._quiesced = quiesced;
if (quiesced != null)
{
this.QueryParams.Add("quiesced", quiesced.ToString());
}
else
{
this.QueryParams.Remove("quiesced");
}
return this;
}
public GetAzureTargetsSpectraS3Request WithState(TargetState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetAzureTargetsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/azure_target";
}
}
}
}
| |
// <copyright file="PlayGamesAchievement.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. 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.
// </copyright>
namespace GooglePlayGames
{
using System;
using GooglePlayGames.BasicApi;
using UnityEngine;
using UnityEngine.SocialPlatforms;
internal delegate void ReportProgress(string id, double progress, Action<bool> callback);
/// <summary>
/// Represents a Google Play Games achievement. It can be used to report an achievement
/// to the API, offering identical functionality as <see cref="PlayGamesPlatform.ReportProgress" />.
/// </summary>
internal class PlayGamesAchievement : IAchievement, IAchievementDescription
{
private readonly ReportProgress mProgressCallback;
private string mId = string.Empty;
private double mPercentComplete = 0.0f;
private bool mCompleted = false;
private bool mHidden = false;
private DateTime mLastModifiedTime = new DateTime (1970, 1, 1, 0, 0, 0, 0);
private string mTitle = string.Empty;
private string mRevealedImageUrl = string.Empty;
private string mUnlockedImageUrl = string.Empty;
private WWW mImageFetcher = null;
private Texture2D mImage = null;
private string mDescription = string.Empty;
private ulong mPoints = 0;
internal PlayGamesAchievement()
: this(PlayGamesPlatform.Instance.ReportProgress)
{
}
internal PlayGamesAchievement(ReportProgress progressCallback)
{
mProgressCallback = progressCallback;
}
internal PlayGamesAchievement(Achievement ach) : this()
{
this.mId = ach.Id;
this.mPercentComplete = (double)ach.CurrentSteps / (double) ach.TotalSteps;
this.mCompleted = ach.IsUnlocked;
this.mHidden = !ach.IsRevealed;
this.mLastModifiedTime = ach.LastModifiedTime;
this.mTitle = ach.Name;
this.mDescription = ach.Description;
this.mPoints = ach.Points;
this.mRevealedImageUrl = ach.RevealedImageUrl;
this.mUnlockedImageUrl = ach.UnlockedImageUrl;
}
/// <summary>
/// Reveals, unlocks or increment achievement. Call after setting
/// <see cref="id" /> and <see cref="percentCompleted" />. Equivalent to calling
/// <see cref="PlayGamesPlatform.ReportProgress" />.
/// </summary>
public void ReportProgress(Action<bool> callback)
{
mProgressCallback.Invoke(mId, mPercentComplete, callback);
}
/// <summary>
/// Loads the local user's image from the url. Loading urls
/// is asynchronous so the return from this call is fast,
/// the image is returned once it is loaded. null is returned
/// up to that point.
/// </summary>
private Texture2D LoadImage()
{
if (hidden) {
// return null, we dont have images for hidden achievements.
return null;
}
string url = completed ? mUnlockedImageUrl : mRevealedImageUrl;
// the url can be null if the image is not configured.
if (!string.IsNullOrEmpty(url))
{
if (mImageFetcher == null || mImageFetcher.url != url)
{
mImageFetcher = new WWW(url);
mImage = null;
}
// if we have the texture, just return, this avoids excessive
// memory usage calling www.texture repeatedly.
if (mImage != null)
{
return mImage;
}
if (mImageFetcher.isDone)
{
mImage = mImageFetcher.texture;
return mImage;
}
}
// if there is no url, always return null.
return null;
}
/// <summary>
/// Gets or sets the id of this achievement.
/// </summary>
/// <returns>
/// The identifier.
/// </returns>
public string id
{
get
{
return mId;
}
set
{
mId = value;
}
}
/// <summary>
/// Gets or sets the percent completed.
/// </summary>
/// <returns>
/// The percent completed.
/// </returns>
public double percentCompleted
{
get
{
return mPercentComplete;
}
set
{
mPercentComplete = value;
}
}
public bool completed
{
get
{
return this.mCompleted;
}
}
/// <summary>
/// Not implemented. Always returns false.
/// </summary>
public bool hidden
{
get
{
return this.mHidden;
}
}
public DateTime lastReportedDate
{
get
{
return mLastModifiedTime;
}
}
public String title
{
get
{
return mTitle;
}
}
public Texture2D image
{
get
{
return LoadImage();
}
}
public string achievedDescription
{
get
{
return mDescription;
}
}
public string unachievedDescription
{
get
{
return mDescription;
}
}
public int points
{
get
{
return (int) mPoints;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Linq;
using AutoRest.Swagger.Validation;
using System.Collections.Generic;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Validation.Core;
namespace AutoRest.Swagger.Model
{
/// <summary>
/// Describes a single API operation on a path.
/// </summary>
[Rule(typeof(OperationDescriptionRequired))]
public class Operation : SwaggerBase
{
private string _description;
private string _summary;
public Operation()
{
Consumes = new List<string>();
Produces = new List<string>();
}
/// <summary>
/// A list of tags for API documentation control.
/// </summary>
public IList<string> Tags { get; set; }
/// <summary>
/// A friendly serviceTypeName for the operation. The id MUST be unique among all
/// operations described in the API. Tools and libraries MAY use the
/// operation id to uniquely identify an operation.
/// </summary>
[Rule(typeof(OneUnderscoreInOperationId))]
[Rule(typeof(OperationIdNounInVerb))]
[Rule(typeof(GetOperationNameValidation))]
[Rule(typeof(PutOperationNameValidation))]
[Rule(typeof(PatchOperationNameValidation))]
[Rule(typeof(DeleteOperationNameValidation))]
public string OperationId { get; set; }
public string Summary
{
get { return _summary; }
set { _summary = value.StripControlCharacters(); }
}
[Rule(typeof(AvoidMsdnReferences))]
public string Description
{
get { return _description; }
set { _description = value.StripControlCharacters(); }
}
/// <summary>
/// Additional external documentation for this operation.
/// </summary>
public ExternalDoc ExternalDocs { get; set; }
/// <summary>
/// A list of MIME types the operation can consume.
/// </summary>
[CollectionRule(typeof(NonAppJsonTypeWarning))]
public IList<string> Consumes { get; set; }
/// <summary>
/// A list of MIME types the operation can produce.
/// </summary>
[CollectionRule(typeof(NonAppJsonTypeWarning))]
public IList<string> Produces { get; set; }
/// <summary>
/// A list of parameters that are applicable for this operation.
/// If a parameter is already defined at the Path Item, the
/// new definition will override it, but can never remove it.
/// </summary>
[CollectionRule(typeof(OperationParametersValidation))]
[CollectionRule(typeof(AnonymousParameterTypes))]
public IList<SwaggerParameter> Parameters { get; set; }
/// <summary>
/// The list of possible responses as they are returned from executing this operation.
/// </summary>
[Rule(typeof(ResponseRequired))]
public Dictionary<string, OperationResponse> Responses { get; set; }
/// <summary>
/// The transfer protocol for the operation.
/// </summary>
[CollectionRule(typeof(SupportedSchemesWarning))]
public IList<TransferProtocolScheme> Schemes { get; set; }
public bool Deprecated { get; set; }
/// <summary>
/// A declaration of which security schemes are applied for this operation.
/// The list of values describes alternative security schemes that can be used
/// (that is, there is a logical OR between the security requirements).
/// This definition overrides any declared top-level security. To remove a
/// top-level security declaration, an empty array can be used.
/// </summary>
public IList<Dictionary<string, List<string>>> Security { get; set; }
/// <summary>
/// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes.
/// </summary>
/// <param name="context">The modified document context.</param>
/// <param name="previous">The original document model.</param>
/// <returns>A list of messages from the comparison.</returns>
public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous)
{
var priorOperation = previous as Operation;
var currentRoot = (context.CurrentRoot as ServiceDefinition);
var previousRoot = (context.PreviousRoot as ServiceDefinition);
if (priorOperation == null)
{
throw new ArgumentException("previous");
}
base.Compare(context, previous);
if (!OperationId.Equals(priorOperation.OperationId))
{
context.LogBreakingChange(ComparisonMessages.ModifiedOperationId);
}
CheckParameters(context, priorOperation);
if (Responses != null && priorOperation.Responses != null)
{
foreach (var response in Responses)
{
var oldResponse = priorOperation.FindResponse(response.Key, priorOperation.Responses);
context.PushProperty(response.Key);
if (oldResponse == null)
{
context.LogBreakingChange(ComparisonMessages.AddingResponseCode, response.Key);
}
else
{
response.Value.Compare(context, oldResponse);
}
context.Pop();
}
foreach (var response in priorOperation.Responses)
{
var newResponse = this.FindResponse(response.Key, this.Responses);
if (newResponse == null)
{
context.PushProperty(response.Key);
context.LogBreakingChange(ComparisonMessages.RemovedResponseCode, response.Key);
context.Pop();
}
}
}
return context.Messages;
}
private void CheckParameters(ComparisonContext context, Operation priorOperation)
{
// Check that no parameters were removed or reordered, and compare them if it's not the case.
var currentRoot = (context.CurrentRoot as ServiceDefinition);
var previousRoot = (context.PreviousRoot as ServiceDefinition);
foreach (var oldParam in priorOperation.Parameters
.Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, previousRoot.Parameters)))
{
SwaggerParameter newParam = FindParameter(oldParam.Name, Parameters, currentRoot.Parameters);
context.PushProperty(oldParam.Name);
if (newParam != null)
{
newParam.Compare(context, oldParam);
}
else if (oldParam.IsRequired)
{
context.LogBreakingChange(ComparisonMessages.RemovedRequiredParameter, oldParam.Name);
}
context.Pop();
}
// Check that no required parameters were added.
foreach (var newParam in Parameters
.Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, currentRoot.Parameters))
.Where(p => p != null && p.IsRequired))
{
if (newParam == null) continue;
SwaggerParameter oldParam = FindParameter(newParam.Name, priorOperation.Parameters, previousRoot.Parameters);
if (oldParam == null)
{
context.PushProperty(newParam.Name);
context.LogBreakingChange(ComparisonMessages.AddingRequiredParameter, newParam.Name);
context.Pop();
}
}
}
private SwaggerParameter FindParameter(string name, IEnumerable<SwaggerParameter> operationParameters, IDictionary<string, SwaggerParameter> clientParameters)
{
if (Parameters != null)
{
foreach (var param in operationParameters)
{
if (name.Equals(param.Name))
return param;
var pRef = FindReferencedParameter(param.Reference, clientParameters);
if (pRef != null && name.Equals(pRef.Name))
{
return pRef;
}
}
}
return null;
}
private OperationResponse FindResponse(string name, IDictionary<string, OperationResponse> responses)
{
OperationResponse response = null;
this.Responses.TryGetValue(name, out response);
return response;
}
private static SwaggerParameter FindReferencedParameter(string reference, IDictionary<string, SwaggerParameter> parameters)
{
if (reference != null && reference.StartsWith("#", StringComparison.Ordinal))
{
var parts = reference.Split('/');
if (parts.Length == 3 && parts[1].Equals("parameters"))
{
SwaggerParameter p = null;
if (parameters.TryGetValue(parts[2], out p))
{
return p;
}
}
}
return null;
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to complete, since the modulation parameters are of variable length. UNFINISHED
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(RadioEntityType))]
[XmlInclude(typeof(Vector3Double))]
[XmlInclude(typeof(Vector3Float))]
[XmlInclude(typeof(ModulationType))]
[XmlInclude(typeof(Vector3Float))]
[XmlInclude(typeof(Vector3Float))]
public partial class TransmitterPdu : RadioCommunicationsFamilyPdu, IEquatable<TransmitterPdu>
{
/// <summary>
/// linear accelleration of entity
/// </summary>
private RadioEntityType _radioEntityType = new RadioEntityType();
/// <summary>
/// transmit state
/// </summary>
private byte _transmitState;
/// <summary>
/// input source
/// </summary>
private byte _inputSource;
/// <summary>
/// padding
/// </summary>
private ushort _padding1;
/// <summary>
/// Location of antenna
/// </summary>
private Vector3Double _antennaLocation = new Vector3Double();
/// <summary>
/// relative location of antenna
/// </summary>
private Vector3Float _relativeAntennaLocation = new Vector3Float();
/// <summary>
/// antenna pattern type
/// </summary>
private ushort _antennaPatternType;
/// <summary>
/// atenna pattern length
/// </summary>
private ushort _antennaPatternCount;
/// <summary>
/// frequency
/// </summary>
private ulong _frequency;
/// <summary>
/// transmit frequency Bandwidth
/// </summary>
private float _transmitFrequencyBandwidth;
/// <summary>
/// transmission power
/// </summary>
private float _power;
/// <summary>
/// modulation
/// </summary>
private ModulationType _modulationType = new ModulationType();
/// <summary>
/// crypto system enumeration
/// </summary>
private ushort _cryptoSystem;
/// <summary>
/// crypto system key identifer
/// </summary>
private ushort _cryptoKeyId;
/// <summary>
/// how many modulation parameters we have
/// </summary>
private byte _modulationParameterCount;
/// <summary>
/// padding2
/// </summary>
private ushort _padding2;
/// <summary>
/// padding3
/// </summary>
private byte _padding3;
/// <summary>
/// variable length list of modulation parameters
/// </summary>
private List<Vector3Float> _modulationParametersList = new List<Vector3Float>();
/// <summary>
/// variable length list of antenna pattern records
/// </summary>
private List<Vector3Float> _antennaPatternList = new List<Vector3Float>();
/// <summary>
/// Initializes a new instance of the <see cref="TransmitterPdu"/> class.
/// </summary>
public TransmitterPdu()
{
PduType = (byte)25;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(TransmitterPdu left, TransmitterPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(TransmitterPdu left, TransmitterPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._radioEntityType.GetMarshalledSize(); // this._radioEntityType
marshalSize += 1; // this._transmitState
marshalSize += 1; // this._inputSource
marshalSize += 2; // this._padding1
marshalSize += this._antennaLocation.GetMarshalledSize(); // this._antennaLocation
marshalSize += this._relativeAntennaLocation.GetMarshalledSize(); // this._relativeAntennaLocation
marshalSize += 2; // this._antennaPatternType
marshalSize += 2; // this._antennaPatternCount
marshalSize += 8; // this._frequency
marshalSize += 4; // this._transmitFrequencyBandwidth
marshalSize += 4; // this._power
marshalSize += this._modulationType.GetMarshalledSize(); // this._modulationType
marshalSize += 2; // this._cryptoSystem
marshalSize += 2; // this._cryptoKeyId
marshalSize += 1; // this._modulationParameterCount
marshalSize += 2; // this._padding2
marshalSize += 1; // this._padding3
for (int idx = 0; idx < this._modulationParametersList.Count; idx++)
{
Vector3Float listElement = (Vector3Float)this._modulationParametersList[idx];
marshalSize += listElement.GetMarshalledSize();
}
for (int idx = 0; idx < this._antennaPatternList.Count; idx++)
{
Vector3Float listElement = (Vector3Float)this._antennaPatternList[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the linear accelleration of entity
/// </summary>
[XmlElement(Type = typeof(RadioEntityType), ElementName = "radioEntityType")]
public RadioEntityType RadioEntityType
{
get
{
return this._radioEntityType;
}
set
{
this._radioEntityType = value;
}
}
/// <summary>
/// Gets or sets the transmit state
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "transmitState")]
public byte TransmitState
{
get
{
return this._transmitState;
}
set
{
this._transmitState = value;
}
}
/// <summary>
/// Gets or sets the input source
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "inputSource")]
public byte InputSource
{
get
{
return this._inputSource;
}
set
{
this._inputSource = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "padding1")]
public ushort Padding1
{
get
{
return this._padding1;
}
set
{
this._padding1 = value;
}
}
/// <summary>
/// Gets or sets the Location of antenna
/// </summary>
[XmlElement(Type = typeof(Vector3Double), ElementName = "antennaLocation")]
public Vector3Double AntennaLocation
{
get
{
return this._antennaLocation;
}
set
{
this._antennaLocation = value;
}
}
/// <summary>
/// Gets or sets the relative location of antenna
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "relativeAntennaLocation")]
public Vector3Float RelativeAntennaLocation
{
get
{
return this._relativeAntennaLocation;
}
set
{
this._relativeAntennaLocation = value;
}
}
/// <summary>
/// Gets or sets the antenna pattern type
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "antennaPatternType")]
public ushort AntennaPatternType
{
get
{
return this._antennaPatternType;
}
set
{
this._antennaPatternType = value;
}
}
/// <summary>
/// Gets or sets the atenna pattern length
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getantennaPatternCount method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(ushort), ElementName = "antennaPatternCount")]
public ushort AntennaPatternCount
{
get
{
return this._antennaPatternCount;
}
set
{
this._antennaPatternCount = value;
}
}
/// <summary>
/// Gets or sets the frequency
/// </summary>
[XmlElement(Type = typeof(ulong), ElementName = "frequency")]
public ulong Frequency
{
get
{
return this._frequency;
}
set
{
this._frequency = value;
}
}
/// <summary>
/// Gets or sets the transmit frequency Bandwidth
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "transmitFrequencyBandwidth")]
public float TransmitFrequencyBandwidth
{
get
{
return this._transmitFrequencyBandwidth;
}
set
{
this._transmitFrequencyBandwidth = value;
}
}
/// <summary>
/// Gets or sets the transmission power
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "power")]
public float Power
{
get
{
return this._power;
}
set
{
this._power = value;
}
}
/// <summary>
/// Gets or sets the modulation
/// </summary>
[XmlElement(Type = typeof(ModulationType), ElementName = "modulationType")]
public ModulationType ModulationType
{
get
{
return this._modulationType;
}
set
{
this._modulationType = value;
}
}
/// <summary>
/// Gets or sets the crypto system enumeration
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "cryptoSystem")]
public ushort CryptoSystem
{
get
{
return this._cryptoSystem;
}
set
{
this._cryptoSystem = value;
}
}
/// <summary>
/// Gets or sets the crypto system key identifer
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "cryptoKeyId")]
public ushort CryptoKeyId
{
get
{
return this._cryptoKeyId;
}
set
{
this._cryptoKeyId = value;
}
}
/// <summary>
/// Gets or sets the how many modulation parameters we have
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getmodulationParameterCount method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(byte), ElementName = "modulationParameterCount")]
public byte ModulationParameterCount
{
get
{
return this._modulationParameterCount;
}
set
{
this._modulationParameterCount = value;
}
}
/// <summary>
/// Gets or sets the padding2
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "padding2")]
public ushort Padding2
{
get
{
return this._padding2;
}
set
{
this._padding2 = value;
}
}
/// <summary>
/// Gets or sets the padding3
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "padding3")]
public byte Padding3
{
get
{
return this._padding3;
}
set
{
this._padding3 = value;
}
}
/// <summary>
/// Gets the variable length list of modulation parameters
/// </summary>
[XmlElement(ElementName = "modulationParametersListList", Type = typeof(List<Vector3Float>))]
public List<Vector3Float> ModulationParametersList
{
get
{
return this._modulationParametersList;
}
}
/// <summary>
/// Gets the variable length list of antenna pattern records
/// </summary>
[XmlElement(ElementName = "antennaPatternListList", Type = typeof(List<Vector3Float>))]
public List<Vector3Float> AntennaPatternList
{
get
{
return this._antennaPatternList;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._radioEntityType.Marshal(dos);
dos.WriteUnsignedByte((byte)this._transmitState);
dos.WriteUnsignedByte((byte)this._inputSource);
dos.WriteUnsignedShort((ushort)this._padding1);
this._antennaLocation.Marshal(dos);
this._relativeAntennaLocation.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._antennaPatternType);
dos.WriteUnsignedShort((ushort)this._antennaPatternList.Count);
dos.WriteUnsignedLong((ulong)this._frequency);
dos.WriteFloat((float)this._transmitFrequencyBandwidth);
dos.WriteFloat((float)this._power);
this._modulationType.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._cryptoSystem);
dos.WriteUnsignedShort((ushort)this._cryptoKeyId);
dos.WriteUnsignedByte((byte)this._modulationParametersList.Count);
dos.WriteUnsignedShort((ushort)this._padding2);
dos.WriteUnsignedByte((byte)this._padding3);
for (int idx = 0; idx < this._modulationParametersList.Count; idx++)
{
Vector3Float aVector3Float = (Vector3Float)this._modulationParametersList[idx];
aVector3Float.Marshal(dos);
}
for (int idx = 0; idx < this._antennaPatternList.Count; idx++)
{
Vector3Float aVector3Float = (Vector3Float)this._antennaPatternList[idx];
aVector3Float.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._radioEntityType.Unmarshal(dis);
this._transmitState = dis.ReadUnsignedByte();
this._inputSource = dis.ReadUnsignedByte();
this._padding1 = dis.ReadUnsignedShort();
this._antennaLocation.Unmarshal(dis);
this._relativeAntennaLocation.Unmarshal(dis);
this._antennaPatternType = dis.ReadUnsignedShort();
this._antennaPatternCount = dis.ReadUnsignedShort();
this._frequency = dis.ReadUnsignedLong();
this._transmitFrequencyBandwidth = dis.ReadFloat();
this._power = dis.ReadFloat();
this._modulationType.Unmarshal(dis);
this._cryptoSystem = dis.ReadUnsignedShort();
this._cryptoKeyId = dis.ReadUnsignedShort();
this._modulationParameterCount = dis.ReadUnsignedByte();
this._padding2 = dis.ReadUnsignedShort();
this._padding3 = dis.ReadUnsignedByte();
for (int idx = 0; idx < this.ModulationParameterCount; idx++)
{
Vector3Float anX = new Vector3Float();
anX.Unmarshal(dis);
this._modulationParametersList.Add(anX);
}
for (int idx = 0; idx < this.AntennaPatternCount; idx++)
{
Vector3Float anX = new Vector3Float();
anX.Unmarshal(dis);
this._antennaPatternList.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<TransmitterPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<radioEntityType>");
this._radioEntityType.Reflection(sb);
sb.AppendLine("</radioEntityType>");
sb.AppendLine("<transmitState type=\"byte\">" + this._transmitState.ToString(CultureInfo.InvariantCulture) + "</transmitState>");
sb.AppendLine("<inputSource type=\"byte\">" + this._inputSource.ToString(CultureInfo.InvariantCulture) + "</inputSource>");
sb.AppendLine("<padding1 type=\"ushort\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>");
sb.AppendLine("<antennaLocation>");
this._antennaLocation.Reflection(sb);
sb.AppendLine("</antennaLocation>");
sb.AppendLine("<relativeAntennaLocation>");
this._relativeAntennaLocation.Reflection(sb);
sb.AppendLine("</relativeAntennaLocation>");
sb.AppendLine("<antennaPatternType type=\"ushort\">" + this._antennaPatternType.ToString(CultureInfo.InvariantCulture) + "</antennaPatternType>");
sb.AppendLine("<antennaPatternList type=\"ushort\">" + this._antennaPatternList.Count.ToString(CultureInfo.InvariantCulture) + "</antennaPatternList>");
sb.AppendLine("<frequency type=\"ulong\">" + this._frequency.ToString(CultureInfo.InvariantCulture) + "</frequency>");
sb.AppendLine("<transmitFrequencyBandwidth type=\"float\">" + this._transmitFrequencyBandwidth.ToString(CultureInfo.InvariantCulture) + "</transmitFrequencyBandwidth>");
sb.AppendLine("<power type=\"float\">" + this._power.ToString(CultureInfo.InvariantCulture) + "</power>");
sb.AppendLine("<modulationType>");
this._modulationType.Reflection(sb);
sb.AppendLine("</modulationType>");
sb.AppendLine("<cryptoSystem type=\"ushort\">" + this._cryptoSystem.ToString(CultureInfo.InvariantCulture) + "</cryptoSystem>");
sb.AppendLine("<cryptoKeyId type=\"ushort\">" + this._cryptoKeyId.ToString(CultureInfo.InvariantCulture) + "</cryptoKeyId>");
sb.AppendLine("<modulationParametersList type=\"byte\">" + this._modulationParametersList.Count.ToString(CultureInfo.InvariantCulture) + "</modulationParametersList>");
sb.AppendLine("<padding2 type=\"ushort\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>");
sb.AppendLine("<padding3 type=\"byte\">" + this._padding3.ToString(CultureInfo.InvariantCulture) + "</padding3>");
for (int idx = 0; idx < this._modulationParametersList.Count; idx++)
{
sb.AppendLine("<modulationParametersList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"Vector3Float\">");
Vector3Float aVector3Float = (Vector3Float)this._modulationParametersList[idx];
aVector3Float.Reflection(sb);
sb.AppendLine("</modulationParametersList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
for (int idx = 0; idx < this._antennaPatternList.Count; idx++)
{
sb.AppendLine("<antennaPatternList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"Vector3Float\">");
Vector3Float aVector3Float = (Vector3Float)this._antennaPatternList[idx];
aVector3Float.Reflection(sb);
sb.AppendLine("</antennaPatternList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</TransmitterPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as TransmitterPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(TransmitterPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._radioEntityType.Equals(obj._radioEntityType))
{
ivarsEqual = false;
}
if (this._transmitState != obj._transmitState)
{
ivarsEqual = false;
}
if (this._inputSource != obj._inputSource)
{
ivarsEqual = false;
}
if (this._padding1 != obj._padding1)
{
ivarsEqual = false;
}
if (!this._antennaLocation.Equals(obj._antennaLocation))
{
ivarsEqual = false;
}
if (!this._relativeAntennaLocation.Equals(obj._relativeAntennaLocation))
{
ivarsEqual = false;
}
if (this._antennaPatternType != obj._antennaPatternType)
{
ivarsEqual = false;
}
if (this._antennaPatternCount != obj._antennaPatternCount)
{
ivarsEqual = false;
}
if (this._frequency != obj._frequency)
{
ivarsEqual = false;
}
if (this._transmitFrequencyBandwidth != obj._transmitFrequencyBandwidth)
{
ivarsEqual = false;
}
if (this._power != obj._power)
{
ivarsEqual = false;
}
if (!this._modulationType.Equals(obj._modulationType))
{
ivarsEqual = false;
}
if (this._cryptoSystem != obj._cryptoSystem)
{
ivarsEqual = false;
}
if (this._cryptoKeyId != obj._cryptoKeyId)
{
ivarsEqual = false;
}
if (this._modulationParameterCount != obj._modulationParameterCount)
{
ivarsEqual = false;
}
if (this._padding2 != obj._padding2)
{
ivarsEqual = false;
}
if (this._padding3 != obj._padding3)
{
ivarsEqual = false;
}
if (this._modulationParametersList.Count != obj._modulationParametersList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._modulationParametersList.Count; idx++)
{
if (!this._modulationParametersList[idx].Equals(obj._modulationParametersList[idx]))
{
ivarsEqual = false;
}
}
}
if (this._antennaPatternList.Count != obj._antennaPatternList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._antennaPatternList.Count; idx++)
{
if (!this._antennaPatternList[idx].Equals(obj._antennaPatternList[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._radioEntityType.GetHashCode();
result = GenerateHash(result) ^ this._transmitState.GetHashCode();
result = GenerateHash(result) ^ this._inputSource.GetHashCode();
result = GenerateHash(result) ^ this._padding1.GetHashCode();
result = GenerateHash(result) ^ this._antennaLocation.GetHashCode();
result = GenerateHash(result) ^ this._relativeAntennaLocation.GetHashCode();
result = GenerateHash(result) ^ this._antennaPatternType.GetHashCode();
result = GenerateHash(result) ^ this._antennaPatternCount.GetHashCode();
result = GenerateHash(result) ^ this._frequency.GetHashCode();
result = GenerateHash(result) ^ this._transmitFrequencyBandwidth.GetHashCode();
result = GenerateHash(result) ^ this._power.GetHashCode();
result = GenerateHash(result) ^ this._modulationType.GetHashCode();
result = GenerateHash(result) ^ this._cryptoSystem.GetHashCode();
result = GenerateHash(result) ^ this._cryptoKeyId.GetHashCode();
result = GenerateHash(result) ^ this._modulationParameterCount.GetHashCode();
result = GenerateHash(result) ^ this._padding2.GetHashCode();
result = GenerateHash(result) ^ this._padding3.GetHashCode();
if (this._modulationParametersList.Count > 0)
{
for (int idx = 0; idx < this._modulationParametersList.Count; idx++)
{
result = GenerateHash(result) ^ this._modulationParametersList[idx].GetHashCode();
}
}
if (this._antennaPatternList.Count > 0)
{
for (int idx = 0; idx < this._antennaPatternList.Count; idx++)
{
result = GenerateHash(result) ^ this._antennaPatternList[idx].GetHashCode();
}
}
return result;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System.Dynamic;
#endif
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using System.Security;
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
SerializeValue(jsonWriter, value, GetContractSafe(value), null, null);
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer.ContractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContract collectionValueContract)
{
if (contract.UnderlyingType == typeof (byte[]))
{
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName);
writer.WriteValue(value);
writer.WriteEndObject();
return;
}
}
writer.WriteValue(value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContract collectionValueContract)
{
JsonConverter converter = (member != null) ? member.Converter : null;
if (value == null)
{
writer.WriteNull();
return;
}
if ((converter != null
|| ((converter = valueContract.Converter) != null)
|| ((converter = Serializer.GetMatchingConverter(valueContract.UnderlyingType)) != null)
|| ((converter = valueContract.InternalConverter) != null))
&& converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract) valueContract, member, collectionValueContract);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract) valueContract;
SerializeList(writer, arrayContract.CreateWrapper(value), arrayContract, member, collectionValueContract);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract) valueContract, member, collectionValueContract);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract) valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract) valueContract;
SerializeDictionary(writer, dictionaryContract.CreateWrapper(value), dictionaryContract, member, collectionValueContract);
break;
#if !(NET35 || NET20 || WINDOWS_PHONE)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider) value, (JsonDynamicContract) valueContract);
break;
#endif
#if !SILVERLIGHT && !PocketPC
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable) value, (JsonISerializableContract) valueContract, member, collectionValueContract);
break;
#endif
case JsonContractType.Linq:
((JToken) value).WriteTo(writer, (Serializer.Converters != null) ? Serializer.Converters.ToArray() : null);
break;
}
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract contract)
{
if (value == null)
return false;
if (contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return false;
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null)
isReference = contract.IsReference;
if (isReference == null)
{
if (contract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.ReferenceResolver.IsReferenced(this, value);
}
private void WriteMemberInfoProperty(JsonWriter writer, object memberValue, JsonProperty property, JsonContract contract)
{
string propertyName = property.PropertyName;
object defaultValue = property.DefaultValue;
if (property.NullValueHandling.GetValueOrDefault(Serializer.NullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer.DefaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, defaultValue))
return;
if (ShouldWriteReference(memberValue, property, contract))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, memberValue);
return;
}
if (!CheckForCircularReference(memberValue, property.ReferenceLoopHandling, contract))
return;
if (memberValue == null && property.Required == Required.Always)
throw new JsonSerializationException("Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));
writer.WritePropertyName(propertyName);
SerializeValue(writer, memberValue, contract, property, null);
}
private bool CheckForCircularReference(object value, ReferenceLoopHandling? referenceLoopHandling, JsonContract contract)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
if (_serializeStack.IndexOf(value) != -1)
{
switch (referenceLoopHandling.GetValueOrDefault(Serializer.ReferenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw new JsonSerializationException("Self referencing loop detected for type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
case ReferenceLoopHandling.Ignore:
return false;
case ReferenceLoopHandling.Serialize:
return true;
default:
throw new InvalidOperationException("Unexpected ReferenceLoopHandling value: '{0}'".FormatWith(CultureInfo.InvariantCulture, Serializer.ReferenceLoopHandling));
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
writer.WriteEndObject();
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !PocketPC
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
#if !SILVERLIGHT
&& !(converter is ComponentConverter)
#endif
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
#if !SILVERLIGHT
s = converter.ConvertToInvariantString(value);
#else
s = converter.ConvertToString(value);
#endif
return true;
}
}
#endif
#if SILVERLIGHT || PocketPC
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
_serializeStack.Add(value);
writer.WriteStartObject();
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, value));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
int initialDepth = writer.Top;
foreach (JsonProperty property in contract.Properties)
{
try
{
if (!property.Ignored && property.Readable && ShouldSerialize(property, value) && IsSpecified(property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer.ContractResolver.ResolveContract(property.PropertyType);
object memberValue = property.ValueProvider.GetValue(value);
JsonContract memberContract = (property.PropertyContract.UnderlyingType.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
WriteMemberInfoProperty(writer, memberValue, property, memberContract);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
writer.WritePropertyName(JsonTypeReflector.TypePropertyName);
writer.WriteValue(ReflectionUtils.GetTypeName(type, Serializer.TypeNameAssemblyFormat, Serializer.Binder));
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract)
{
if (ShouldWriteReference(value, null, contract))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(value, null, contract))
return;
_serializeStack.Add(value);
converter.WriteJson(writer, value, GetInternalSerializer());
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(values.UnderlyingCollection, Serializer.Context);
_serializeStack.Add(values.UnderlyingCollection);
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, collectionValueContract);
if (isReference || includeTypeDetails)
{
writer.WriteStartObject();
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingCollection));
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.UnderlyingCollection.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName);
}
if (contract.CollectionItemContract == null)
contract.CollectionItemContract = Serializer.ContractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
JsonContract collectionItemValueContract = (contract.CollectionItemContract.UnderlyingType.IsSealed) ? contract.CollectionItemContract : null;
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = collectionItemValueContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(value, null, contract))
{
SerializeValue(writer, value, valueContract, null, contract.CollectionItemContract);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingCollection, contract, index, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (isReference || includeTypeDetails)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingCollection, Serializer.Context);
}
#if !SILVERLIGHT && !PocketPC
#if !NET20
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")]
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
_serializeStack.Add(value);
writer.WriteStartObject();
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer.Context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null);
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
#endif
#if !(NET35 || NET20 || WINDOWS_PHONE)
/// <summary>
/// Serializes the dynamic.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="value">The value.</param>
/// <param name="contract">The contract.</param>
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract)
{
contract.InvokeOnSerializing(value, Serializer.Context);
_serializeStack.Add(value);
writer.WriteStartObject();
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (DynamicUtils.TryGetMember(value, memberName, out memberValue))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, GetContractSafe(memberValue), null, null);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(value, Serializer.Context);
}
#endif
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContract collectionValueContract)
{
if (HasFlag(((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling, typeNameHandlingFlag))
return true;
if (member != null)
{
if ((member.TypeNameHandling ?? Serializer.TypeNameHandling) == TypeNameHandling.Auto
// instance and property type are different
&& contract.UnderlyingType != member.PropertyType)
{
JsonContract memberTypeContract = Serializer.ContractResolver.ResolveContract(member.PropertyType);
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (contract.UnderlyingType != memberTypeContract.CreatedType)
return true;
}
}
else if (collectionValueContract != null)
{
if (Serializer.TypeNameHandling == TypeNameHandling.Auto && contract.UnderlyingType != collectionValueContract.UnderlyingType)
return true;
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IWrappedDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContract collectionValueContract)
{
contract.InvokeOnSerializing(values.UnderlyingDictionary, Serializer.Context);
_serializeStack.Add(values.UnderlyingDictionary);
writer.WriteStartObject();
bool isReference = contract.IsReference ?? HasFlag(Serializer.PreserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
writer.WritePropertyName(JsonTypeReflector.IdPropertyName);
writer.WriteValue(Serializer.ReferenceResolver.GetReference(this, values.UnderlyingDictionary));
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionValueContract))
{
WriteTypeProperty(writer, values.UnderlyingDictionary.GetType());
}
if (contract.DictionaryValueContract == null)
contract.DictionaryValueContract = Serializer.ContractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
JsonContract dictionaryValueContract = (contract.DictionaryValueContract.UnderlyingType.IsSealed) ? contract.DictionaryValueContract : null;
int initialDepth = writer.Top;
// Mono Unity 3.0 fix
IDictionary d = values;
foreach (DictionaryEntry entry in d)
{
string propertyName = GetPropertyName(entry);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = dictionaryValueContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(value, null, contract))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, value, valueContract, null, contract.DictionaryValueContract);
}
}
catch (Exception ex)
{
if (IsErrorHandled(values.UnderlyingDictionary, contract, propertyName, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
contract.InvokeOnSerialized(values.UnderlyingDictionary, Serializer.Context);
}
private string GetPropertyName(DictionaryEntry entry)
{
string propertyName;
if (entry.Key is IConvertible)
return Convert.ToString(entry.Key, CultureInfo.InvariantCulture);
else if (TryConvertToString(entry.Key, entry.Key.GetType(), out propertyName))
return propertyName;
else
return entry.Key.ToString();
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
return property.ShouldSerialize(target);
}
private bool IsSpecified(JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
return property.GetIsSpecified(target);
}
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 5747 $</version>
// </file>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Indentation;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
namespace ICSharpCode.AvalonEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : Control, IScrollInfo, IWeakEventListener, ITextEditorComponent, IServiceProvider
{
#region Constructor
static TextArea()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextArea),
new FrameworkPropertyMetadata(typeof(TextArea)));
KeyboardNavigation.IsTabStopProperty.OverrideMetadata(
typeof(TextArea), new FrameworkPropertyMetadata(Boxes.True));
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(
typeof(TextArea), new FrameworkPropertyMetadata(KeyboardNavigationMode.None));
FocusableProperty.OverrideMetadata(
typeof(TextArea), new FrameworkPropertyMetadata(Boxes.True));
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
if (textView == null)
throw new ArgumentNullException("textView");
this.textView = textView;
this.Options = textView.Options;
textView.Services.AddService(typeof(TextArea), this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
caret = new Caret(this);
caret.PositionChanged += (sender, e) => RequestSelectionValidation();
leftMargins.CollectionChanged += leftMargins_CollectionChanged;
this.DefaultInputHandler = new TextAreaDefaultInputHandler(this);
this.ActiveInputHandler = this.DefaultInputHandler;
}
#endregion
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; private set; }
ITextAreaInputHandler activeInputHandler;
bool isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler {
get { return activeInputHandler; }
set {
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (activeInputHandler != value) {
isChangingInputHandler = true;
try {
// pop the whole stack
PopStackedInputHandler(stackedInputHandlers.LastOrDefault());
Debug.Assert(stackedInputHandlers.IsEmpty);
if (activeInputHandler != null)
activeInputHandler.Detach();
activeInputHandler = value;
if (value != null)
value.Attach();
} finally {
isChangingInputHandler = false;
}
if (ActiveInputHandlerChanged != null)
ActiveInputHandlerChanged(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
ImmutableStack<TextAreaStackedInputHandler> stackedInputHandlers = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers {
get { return stackedInputHandlers; }
}
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException("inputHandler");
stackedInputHandlers = stackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (stackedInputHandlers.Any(i => i == inputHandler)) {
ITextAreaInputHandler oldHandler;
do {
oldHandler = stackedInputHandlers.Peek();
stackedInputHandlers = stackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly DependencyProperty DocumentProperty
= TextView.DocumentProperty.AddOwner(typeof(TextArea), new FrameworkPropertyMetadata(OnDocumentChanged));
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document {
get { return (TextDocument)GetValue(DocumentProperty); }
set { SetValue(DocumentProperty, value); }
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextArea)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null) {
TextDocumentWeakEventManager.Changing.RemoveListener(oldValue, this);
TextDocumentWeakEventManager.Changed.RemoveListener(oldValue, this);
TextDocumentWeakEventManager.UpdateStarted.RemoveListener(oldValue, this);
TextDocumentWeakEventManager.UpdateFinished.RemoveListener(oldValue, this);
}
textView.Document = newValue;
if (newValue != null) {
TextDocumentWeakEventManager.Changing.AddListener(newValue, this);
TextDocumentWeakEventManager.Changed.AddListener(newValue, this);
TextDocumentWeakEventManager.UpdateStarted.AddListener(newValue, this);
TextDocumentWeakEventManager.UpdateFinished.AddListener(newValue, this);
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
caret.Location = new TextLocation(1, 1);
this.Selection = Selection.Empty;
if (DocumentChanged != null)
DocumentChanged(this, EventArgs.Empty);
CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly DependencyProperty OptionsProperty
= TextView.OptionsProperty.AddOwner(typeof(TextArea), new FrameworkPropertyMetadata(OnOptionsChanged));
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options {
get { return (TextEditorOptions)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
if (OptionChanged != null) {
OptionChanged(this, e);
}
}
static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
((TextArea)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null) {
PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
}
textView.Options = newValue;
if (newValue != null) {
PropertyChangedWeakEventManager.AddListener(newValue, this);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ReceiveWeakEvent
/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(TextDocumentWeakEventManager.Changing)) {
OnDocumentChanging();
return true;
} else if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
OnDocumentChanged((DocumentChangeEventArgs)e);
return true;
} else if (managerType == typeof(TextDocumentWeakEventManager.UpdateStarted)) {
OnUpdateStarted();
return true;
} else if (managerType == typeof(TextDocumentWeakEventManager.UpdateFinished)) {
OnUpdateFinished();
return true;
} else if (managerType == typeof(PropertyChangedWeakEventManager)) {
OnOptionChanged((PropertyChangedEventArgs)e);
return true;
}
return false;
}
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
return ReceiveWeakEvent(managerType, sender, e);
}
#endregion
#region Caret handling on document changes
void OnDocumentChanging()
{
caret.OnDocumentChanging();
}
void OnDocumentChanged(DocumentChangeEventArgs e)
{
caret.OnDocumentChanged(e);
this.Selection = selection.UpdateOnDocumentChange(e);
}
void OnUpdateStarted()
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
void OnUpdateFinished()
{
caret.OnDocumentUpdateFinished();
}
sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
WeakReference textAreaReference;
TextViewPosition caretPosition;
Selection selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
this.textAreaReference = new WeakReference(textArea);
this.caretPosition = textArea.Caret.Position;
this.selection = textArea.Selection;
}
public void Undo()
{
TextArea textArea = (TextArea)textAreaReference.Target;
if (textArea != null) {
textArea.Caret.Position = caretPosition;
textArea.Selection = selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
readonly TextView textView;
IScrollInfo scrollInfo;
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView {
get {
return textView;
}
}
/// <inheritdoc/>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
scrollInfo = textView;
ApplyScrollInfo();
}
#endregion
#region Selection property
Selection selection = Selection.Empty;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection {
get { return selection; }
set {
if (value == null)
throw new ArgumentNullException("value");
if (!object.Equals(selection, value)) {
Debug.WriteLine("Selection change from " + selection + " to " + value);
if (textView != null) {
textView.Redraw(selection.SurroundingSegment, DispatcherPriority.Background);
textView.Redraw(value.SurroundingSegment, DispatcherPriority.Background);
}
selection = value;
if (SelectionChanged != null)
SelectionChanged(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly DependencyProperty SelectionBrushProperty =
DependencyProperty.Register("SelectionBrush", typeof(Brush), typeof(TextArea));
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public Brush SelectionBrush {
get { return (Brush)GetValue(SelectionBrushProperty); }
set { SetValue(SelectionBrushProperty, value); }
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly DependencyProperty SelectionForegroundProperty =
DependencyProperty.Register("SelectionForeground", typeof(Brush), typeof(TextArea));
/// <summary>
/// Gets/Sets the foreground brush used selected text.
/// </summary>
public Brush SelectionForeground {
get { return (Brush)GetValue(SelectionForegroundProperty); }
set { SetValue(SelectionForegroundProperty, value); }
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly DependencyProperty SelectionBorderProperty =
DependencyProperty.Register("SelectionBorder", typeof(Pen), typeof(TextArea));
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public Pen SelectionBorder {
get { return (Pen)GetValue(SelectionBorderProperty); }
set { SetValue(SelectionBorderProperty, value); }
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly DependencyProperty SelectionCornerRadiusProperty =
DependencyProperty.Register("SelectionCornerRadius", typeof(double), typeof(TextArea),
new FrameworkPropertyMetadata(3.0));
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius {
get { return (double)GetValue(SelectionCornerRadiusProperty); }
set { SetValue(SelectionCornerRadiusProperty, value); }
}
#endregion
#region Force caret to stay inside selection
bool ensureSelectionValidRequested;
int allowCaretOutsideSelection;
void RequestSelectionValidation()
{
if (!ensureSelectionValidRequested && allowCaretOutsideSelection == 0) {
ensureSelectionValidRequested = true;
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(EnsureSelectionValid));
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
void EnsureSelectionValid()
{
ensureSelectionValidRequested = false;
if (allowCaretOutsideSelection == 0) {
if (!selection.IsEmpty && !selection.Contains(caret.Offset)) {
Debug.WriteLine("Resetting selection because caret is outside");
this.Selection = Selection.Empty;
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the WPF dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate {
VerifyAccess();
allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
readonly Caret caret;
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret {
get { return caret; }
}
ObservableCollection<UIElement> leftMargins = new ObservableCollection<UIElement>();
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<UIElement> LeftMargins {
get {
return leftMargins;
}
}
void leftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null) {
foreach (ITextViewConnect c in e.OldItems.OfType<ITextViewConnect>()) {
c.RemoveFromTextView(textView);
}
}
if (e.NewItems != null) {
foreach (ITextViewConnect c in e.NewItems.OfType<ITextViewConnect>()) {
c.AddToTextView(textView);
}
}
}
IReadOnlySectionProvider readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider {
get { return readOnlySectionProvider; }
set {
if (value == null)
throw new ArgumentNullException("value");
readOnlySectionProvider = value;
}
}
#endregion
#region IScrollInfo implementation
ScrollViewer scrollOwner;
bool canVerticallyScroll, canHorizontallyScroll;
void ApplyScrollInfo()
{
if (scrollInfo != null) {
scrollInfo.ScrollOwner = scrollOwner;
scrollInfo.CanVerticallyScroll = canVerticallyScroll;
scrollInfo.CanHorizontallyScroll = canHorizontallyScroll;
scrollOwner = null;
}
}
bool IScrollInfo.CanVerticallyScroll {
get { return scrollInfo != null ? scrollInfo.CanVerticallyScroll : false; }
set {
canVerticallyScroll = value;
if (scrollInfo != null)
scrollInfo.CanVerticallyScroll = value;
}
}
bool IScrollInfo.CanHorizontallyScroll {
get { return scrollInfo != null ? scrollInfo.CanHorizontallyScroll : false; }
set {
canHorizontallyScroll = value;
if (scrollInfo != null)
scrollInfo.CanHorizontallyScroll = value;
}
}
double IScrollInfo.ExtentWidth {
get { return scrollInfo != null ? scrollInfo.ExtentWidth : 0; }
}
double IScrollInfo.ExtentHeight {
get { return scrollInfo != null ? scrollInfo.ExtentHeight : 0; }
}
double IScrollInfo.ViewportWidth {
get { return scrollInfo != null ? scrollInfo.ViewportWidth : 0; }
}
double IScrollInfo.ViewportHeight {
get { return scrollInfo != null ? scrollInfo.ViewportHeight : 0; }
}
double IScrollInfo.HorizontalOffset {
get { return scrollInfo != null ? scrollInfo.HorizontalOffset : 0; }
}
double IScrollInfo.VerticalOffset {
get { return scrollInfo != null ? scrollInfo.VerticalOffset : 0; }
}
ScrollViewer IScrollInfo.ScrollOwner {
get { return scrollInfo != null ? scrollInfo.ScrollOwner : null; }
set {
if (scrollInfo != null)
scrollInfo.ScrollOwner = value;
else
scrollOwner = value;
}
}
void IScrollInfo.LineUp()
{
if (scrollInfo != null) scrollInfo.LineUp();
}
void IScrollInfo.LineDown()
{
if (scrollInfo != null) scrollInfo.LineDown();
}
void IScrollInfo.LineLeft()
{
if (scrollInfo != null) scrollInfo.LineLeft();
}
void IScrollInfo.LineRight()
{
if (scrollInfo != null) scrollInfo.LineRight();
}
void IScrollInfo.PageUp()
{
if (scrollInfo != null) scrollInfo.PageUp();
}
void IScrollInfo.PageDown()
{
if (scrollInfo != null) scrollInfo.PageDown();
}
void IScrollInfo.PageLeft()
{
if (scrollInfo != null) scrollInfo.PageLeft();
}
void IScrollInfo.PageRight()
{
if (scrollInfo != null) scrollInfo.PageRight();
}
void IScrollInfo.MouseWheelUp()
{
if (scrollInfo != null) scrollInfo.MouseWheelUp();
}
void IScrollInfo.MouseWheelDown()
{
if (scrollInfo != null) scrollInfo.MouseWheelDown();
}
void IScrollInfo.MouseWheelLeft()
{
if (scrollInfo != null) scrollInfo.MouseWheelLeft();
}
void IScrollInfo.MouseWheelRight()
{
if (scrollInfo != null) scrollInfo.MouseWheelRight();
}
void IScrollInfo.SetHorizontalOffset(double offset)
{
if (scrollInfo != null) scrollInfo.SetHorizontalOffset(offset);
}
void IScrollInfo.SetVerticalOffset(double offset)
{
if (scrollInfo != null) scrollInfo.SetVerticalOffset(offset);
}
Rect IScrollInfo.MakeVisible(System.Windows.Media.Visual visual, Rect rectangle)
{
if (scrollInfo != null)
return scrollInfo.MakeVisible(visual, rectangle);
else
return Rect.Empty;
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <inheritdoc/>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
Focus();
}
/// <inheritdoc/>
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
caret.Show();
}
/// <inheritdoc/>
protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnLostKeyboardFocus(e);
caret.Hide();
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// This is like the <see cref="UIElement.TextInput"/> event,
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event TextCompositionEventHandler TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// This is like the <see cref="UIElement.TextInput"/> event,
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event TextCompositionEventHandler TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextCompositionEventArgs e)
{
if (TextEntering != null) {
TextEntering(this, e);
}
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextCompositionEventArgs e)
{
if (TextEntered != null) {
TextEntered(this, e);
}
}
/// <inheritdoc/>
protected override void OnTextInput(TextCompositionEventArgs e)
{
//Debug.WriteLine("TextInput: Text='" + e.Text + "' SystemText='" + e.SystemText + "' ControlText='" + e.ControlText + "'");
base.OnTextInput(e);
if (!e.Handled && this.Document != null) {
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b") {
// ASCII 0x1b = ESC.
// WPF produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
TextComposition textComposition = new TextComposition(InputManager.Current, this, text);
TextCompositionEventArgs e = new TextCompositionEventArgs(Keyboard.PrimaryDevice, textComposition);
e.RoutedEvent = TextInputEvent;
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextCompositionEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
if (this.Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled) {
if (e.Text == "\n" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
ReplaceSelectionWithText(e.Text);
OnTextEntered(e);
caret.BringCaretToView();
}
}
void ReplaceSelectionWithNewLine()
{
string newLine = TextUtilities.GetNewLineFromDocument(this.Document, this.Caret.Line);
using (this.Document.RunUpdate()) {
ReplaceSelectionWithText(newLine);
if (this.IndentationStrategy != null) {
DocumentLine line = this.Document.GetLineByNumber(this.Caret.Line);
ISegment[] deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) {
// use indentation strategy only if the line is not read-only
this.IndentationStrategy.IndentLine(this.Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (this.Document == null)
throw ThrowUtil.NoDocumentAssigned();
selection.ReplaceSelectionWithText(this, string.Empty);
#if DEBUG
if (!selection.IsEmpty) {
foreach (ISegment s in selection.Segments) {
Debug.Assert(this.ReadOnlySectionProvider.GetDeletableSegments(s).Count() == 0);
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException("newText");
if (this.Document == null)
throw ThrowUtil.NoDocumentAssigned();
selection.ReplaceSelectionWithText(this, newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = this.ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
int lastIndex = segment.Offset;
for (int i = 0; i < array.Length; i++) {
if (array[i].Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = array[i].EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly DependencyProperty IndentationStrategyProperty =
DependencyProperty.Register("IndentationStrategy", typeof(IIndentationStrategy), typeof(TextArea),
new FrameworkPropertyMetadata(new DefaultIndentationStrategy()));
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy {
get { return (IIndentationStrategy)GetValue(IndentationStrategyProperty); }
set { SetValue(IndentationStrategyProperty, value); }
}
#endregion
#region OnKeyDown/OnKeyUp
/// <inheritdoc/>
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
base.OnPreviewKeyDown(e);
foreach (TextAreaStackedInputHandler h in stackedInputHandlers) {
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnPreviewKeyUp(KeyEventArgs e)
{
base.OnPreviewKeyUp(e);
foreach (TextAreaStackedInputHandler h in stackedInputHandlers) {
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursor();
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursor();
}
#endregion
/// <inheritdoc/>
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
// accept clicks even where the text area draws no background
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == SelectionBrushProperty
|| e.Property == SelectionBorderProperty
|| e.Property == SelectionForegroundProperty
|| e.Property == SelectionCornerRadiusProperty)
{
textView.Redraw();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return textView.Services.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
internal void OnTextCopied(TextEventArgs e)
{
if (TextCopied != null)
TextCopied(this, e);
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
[Serializable]
public class TextEventArgs : EventArgs
{
string text;
/// <summary>
/// Gets the text.
/// </summary>
public string Text {
get {
return text;
}
}
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
if (text == null)
throw new ArgumentNullException("text");
this.text = text;
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Microsoft.AspNet.Razor.Editor;
using Microsoft.AspNet.Razor.Generator;
using Microsoft.AspNet.Razor.Parser.SyntaxTree;
using Microsoft.AspNet.Razor.Text;
using Microsoft.AspNet.Razor.Tokenizer;
using Microsoft.AspNet.Razor.Tokenizer.Symbols;
using Microsoft.AspNet.Razor.Utils;
namespace Microsoft.AspNet.Razor.Parser
{
public abstract partial class TokenizerBackedParser<TTokenizer, TSymbol, TSymbolType> : ParserBase
where TTokenizer : Tokenizer<TSymbol, TSymbolType>
where TSymbol : SymbolBase<TSymbolType>
{
// Helpers
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This only occurs in Release builds, where this method is empty by design")]
[Conditional("DEBUG")]
internal void Assert(TSymbolType expectedType)
{
Debug.Assert(!EndOfFile && Equals(CurrentSymbol.Type, expectedType));
}
protected internal void PutBack(TSymbol symbol)
{
if (symbol != null)
{
Tokenizer.PutBack(symbol);
}
}
/// <summary>
/// Put the specified symbols back in the input stream. The provided list MUST be in the ORDER THE SYMBOLS WERE READ. The
/// list WILL be reversed and the Putback(TSymbol) will be called on each item.
/// </summary>
/// <remarks>
/// If a document contains symbols: a, b, c, d, e, f
/// and AcceptWhile or AcceptUntil is used to collect until d
/// the list returned by AcceptWhile/Until will contain: a, b, c IN THAT ORDER
/// that is the correct format for providing to this method. The caller of this method would,
/// in that case, want to put c, b and a back into the stream, so "a, b, c" is the CORRECT order
/// </remarks>
protected internal void PutBack(IEnumerable<TSymbol> symbols)
{
foreach (TSymbol symbol in symbols.Reverse())
{
PutBack(symbol);
}
}
protected internal void PutCurrentBack()
{
if (!EndOfFile && CurrentSymbol != null)
{
PutBack(CurrentSymbol);
}
}
protected internal bool Balance(BalancingModes mode)
{
TSymbolType left = CurrentSymbol.Type;
TSymbolType right = Language.FlipBracket(left);
SourceLocation start = CurrentLocation;
AcceptAndMoveNext();
if (EndOfFile && !mode.HasFlag(BalancingModes.NoErrorOnFailure))
{
Context.OnError(start,
string.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,
Language.GetSample(left),
Language.GetSample(right)));
}
return Balance(mode, left, right, start);
}
protected internal bool Balance(BalancingModes mode, TSymbolType left, TSymbolType right, SourceLocation start)
{
int startPosition = CurrentLocation.AbsoluteIndex;
int nesting = 1;
if (!EndOfFile)
{
IList<TSymbol> syms = new List<TSymbol>();
do
{
if (IsAtEmbeddedTransition(
mode.HasFlag(BalancingModes.AllowCommentsAndTemplates),
mode.HasFlag(BalancingModes.AllowEmbeddedTransitions)))
{
Accept(syms);
syms.Clear();
HandleEmbeddedTransition();
// Reset backtracking since we've already outputted some spans.
startPosition = CurrentLocation.AbsoluteIndex;
}
if (At(left))
{
nesting++;
}
else if (At(right))
{
nesting--;
}
if (nesting > 0)
{
syms.Add(CurrentSymbol);
}
}
while (nesting > 0 && NextToken());
if (nesting > 0)
{
if (!mode.HasFlag(BalancingModes.NoErrorOnFailure))
{
Context.OnError(start,
string.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,
Language.GetSample(left),
Language.GetSample(right)));
}
if (mode.HasFlag(BalancingModes.BacktrackOnFailure))
{
Context.Source.Position = startPosition;
NextToken();
}
else
{
Accept(syms);
}
}
else
{
// Accept all the symbols we saw
Accept(syms);
}
}
return nesting == 0;
}
protected internal bool NextIs(TSymbolType type)
{
return NextIs(sym => sym != null && Equals(type, sym.Type));
}
protected internal bool NextIs(params TSymbolType[] types)
{
return NextIs(sym => sym != null && types.Any(t => Equals(t, sym.Type)));
}
protected internal bool NextIs(Func<TSymbol, bool> condition)
{
TSymbol cur = CurrentSymbol;
NextToken();
bool result = condition(CurrentSymbol);
PutCurrentBack();
PutBack(cur);
EnsureCurrent();
return result;
}
protected internal bool Was(TSymbolType type)
{
return PreviousSymbol != null && Equals(PreviousSymbol.Type, type);
}
protected internal bool At(TSymbolType type)
{
return !EndOfFile && CurrentSymbol != null && Equals(CurrentSymbol.Type, type);
}
protected internal bool AcceptAndMoveNext()
{
Accept(CurrentSymbol);
return NextToken();
}
protected TSymbol AcceptSingleWhiteSpaceCharacter()
{
if (Language.IsWhiteSpace(CurrentSymbol))
{
Tuple<TSymbol, TSymbol> pair = Language.SplitSymbol(CurrentSymbol, 1, Language.GetKnownSymbolType(KnownSymbolType.WhiteSpace));
Accept(pair.Item1);
Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
NextToken();
return pair.Item2;
}
return null;
}
protected internal void Accept(IEnumerable<TSymbol> symbols)
{
foreach (TSymbol symbol in symbols)
{
Accept(symbol);
}
}
protected internal void Accept(TSymbol symbol)
{
if (symbol != null)
{
foreach (RazorError error in symbol.Errors)
{
Context.Errors.Add(error);
}
Span.Accept(symbol);
}
}
protected internal bool AcceptAll(params TSymbolType[] types)
{
foreach (TSymbolType type in types)
{
if (CurrentSymbol == null || !Equals(CurrentSymbol.Type, type))
{
return false;
}
AcceptAndMoveNext();
}
return true;
}
protected internal void AddMarkerSymbolIfNecessary()
{
AddMarkerSymbolIfNecessary(CurrentLocation);
}
protected internal void AddMarkerSymbolIfNecessary(SourceLocation location)
{
if (Span.Symbols.Count == 0 && Context.LastAcceptedCharacters != AcceptedCharacters.Any)
{
Accept(Language.CreateMarkerSymbol(location));
}
}
protected internal void Output(SpanKind kind)
{
Configure(kind, null);
Output();
}
protected internal void Output(SpanKind kind, AcceptedCharacters accepts)
{
Configure(kind, accepts);
Output();
}
protected internal void Output(AcceptedCharacters accepts)
{
Configure(null, accepts);
Output();
}
private void Output()
{
if (Span.Symbols.Count > 0)
{
Context.AddSpan(Span.Build());
Initialize(Span);
}
}
protected IDisposable PushSpanConfig()
{
return PushSpanConfig(newConfig: (Action<SpanBuilder, Action<SpanBuilder>>)null);
}
protected IDisposable PushSpanConfig(Action<SpanBuilder> newConfig)
{
return PushSpanConfig(newConfig == null ? (Action<SpanBuilder, Action<SpanBuilder>>)null : (span, _) => newConfig(span));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "The Action<T> parameters are preferred over custom delegates")]
protected IDisposable PushSpanConfig(Action<SpanBuilder, Action<SpanBuilder>> newConfig)
{
Action<SpanBuilder> old = SpanConfig;
ConfigureSpan(newConfig);
return new DisposableAction(() => SpanConfig = old);
}
protected void ConfigureSpan(Action<SpanBuilder> config)
{
SpanConfig = config;
Initialize(Span);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "The Action<T> parameters are preferred over custom delegates")]
protected void ConfigureSpan(Action<SpanBuilder, Action<SpanBuilder>> config)
{
Action<SpanBuilder> prev = SpanConfig;
if (config == null)
{
SpanConfig = null;
}
else
{
SpanConfig = span => config(span, prev);
}
Initialize(Span);
}
protected internal void Expected(KnownSymbolType type)
{
Expected(Language.GetKnownSymbolType(type));
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "types", Justification = "It is used in debug builds")]
protected internal void Expected(params TSymbolType[] types)
{
Debug.Assert(!EndOfFile && CurrentSymbol != null && types.Contains(CurrentSymbol.Type));
AcceptAndMoveNext();
}
protected internal bool Optional(KnownSymbolType type)
{
return Optional(Language.GetKnownSymbolType(type));
}
protected internal bool Optional(TSymbolType type)
{
if (At(type))
{
AcceptAndMoveNext();
return true;
}
return false;
}
protected internal bool Required(TSymbolType expected, bool errorIfNotFound, Func<string, string> errorBase)
{
bool found = At(expected);
if (!found && errorIfNotFound)
{
string error;
if (Language.IsNewLine(CurrentSymbol))
{
error = RazorResources.ErrorComponent_Newline;
}
else if (Language.IsWhiteSpace(CurrentSymbol))
{
error = RazorResources.ErrorComponent_Whitespace;
}
else if (EndOfFile)
{
error = RazorResources.ErrorComponent_EndOfFile;
}
else
{
error = string.Format(RazorResources.ErrorComponent_Character, CurrentSymbol.Content);
}
Context.OnError(
CurrentLocation,
errorBase(error));
}
return found;
}
protected bool EnsureCurrent()
{
if (CurrentSymbol == null)
{
return NextToken();
}
return true;
}
protected internal void AcceptWhile(TSymbolType type)
{
AcceptWhile(sym => Equals(type, sym.Type));
}
// We want to avoid array allocations and enumeration where possible, so we use the same technique as String.Format
protected internal void AcceptWhile(TSymbolType type1, TSymbolType type2)
{
AcceptWhile(sym => Equals(type1, sym.Type) || Equals(type2, sym.Type));
}
protected internal void AcceptWhile(TSymbolType type1, TSymbolType type2, TSymbolType type3)
{
AcceptWhile(sym => Equals(type1, sym.Type) || Equals(type2, sym.Type) || Equals(type3, sym.Type));
}
protected internal void AcceptWhile(params TSymbolType[] types)
{
AcceptWhile(sym => types.Any(expected => Equals(expected, sym.Type)));
}
protected internal void AcceptUntil(TSymbolType type)
{
AcceptWhile(sym => !Equals(type, sym.Type));
}
// We want to avoid array allocations and enumeration where possible, so we use the same technique as String.Format
protected internal void AcceptUntil(TSymbolType type1, TSymbolType type2)
{
AcceptWhile(sym => !Equals(type1, sym.Type) && !Equals(type2, sym.Type));
}
protected internal void AcceptUntil(TSymbolType type1, TSymbolType type2, TSymbolType type3)
{
AcceptWhile(sym => !Equals(type1, sym.Type) && !Equals(type2, sym.Type) && !Equals(type3, sym.Type));
}
protected internal void AcceptUntil(params TSymbolType[] types)
{
AcceptWhile(sym => types.All(expected => !Equals(expected, sym.Type)));
}
protected internal void AcceptWhile(Func<TSymbol, bool> condition)
{
Accept(ReadWhileLazy(condition));
}
protected internal IEnumerable<TSymbol> ReadWhile(Func<TSymbol, bool> condition)
{
return ReadWhileLazy(condition).ToList();
}
protected TSymbol AcceptWhiteSpaceInLines()
{
TSymbol lastWs = null;
while (Language.IsWhiteSpace(CurrentSymbol) || Language.IsNewLine(CurrentSymbol))
{
// Capture the previous whitespace node
if (lastWs != null)
{
Accept(lastWs);
}
if (Language.IsWhiteSpace(CurrentSymbol))
{
lastWs = CurrentSymbol;
}
else if (Language.IsNewLine(CurrentSymbol))
{
// Accept newline and reset last whitespace tracker
Accept(CurrentSymbol);
lastWs = null;
}
Tokenizer.Next();
}
return lastWs;
}
protected bool AtIdentifier(bool allowKeywords)
{
return CurrentSymbol != null &&
(Language.IsIdentifier(CurrentSymbol) ||
(allowKeywords && Language.IsKeyword(CurrentSymbol)));
}
// Don't open this to sub classes because it's lazy but it looks eager.
// You have to advance the Enumerable to read the next characters.
internal IEnumerable<TSymbol> ReadWhileLazy(Func<TSymbol, bool> condition)
{
while (EnsureCurrent() && condition(CurrentSymbol))
{
yield return CurrentSymbol;
NextToken();
}
}
private void Configure(SpanKind? kind, AcceptedCharacters? accepts)
{
if (kind != null)
{
Span.Kind = kind.Value;
}
if (accepts != null)
{
Span.EditHandler.AcceptedCharacters = accepts.Value;
}
}
protected virtual void OutputSpanBeforeRazorComment()
{
throw new InvalidOperationException(RazorResources.Language_Does_Not_Support_RazorComment);
}
private void CommentSpanConfig(SpanBuilder span)
{
span.CodeGenerator = SpanCodeGenerator.Null;
span.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString);
}
protected void RazorComment()
{
if (!Language.KnowsSymbolType(KnownSymbolType.CommentStart) ||
!Language.KnowsSymbolType(KnownSymbolType.CommentStar) ||
!Language.KnowsSymbolType(KnownSymbolType.CommentBody))
{
throw new InvalidOperationException(RazorResources.Language_Does_Not_Support_RazorComment);
}
OutputSpanBeforeRazorComment();
using (PushSpanConfig(CommentSpanConfig))
{
using (Context.StartBlock(BlockType.Comment))
{
Context.CurrentBlock.CodeGenerator = new RazorCommentCodeGenerator();
SourceLocation start = CurrentLocation;
Expected(KnownSymbolType.CommentStart);
Output(SpanKind.Transition, AcceptedCharacters.None);
Expected(KnownSymbolType.CommentStar);
Output(SpanKind.MetaCode, AcceptedCharacters.None);
Optional(KnownSymbolType.CommentBody);
AddMarkerSymbolIfNecessary();
Output(SpanKind.Comment);
bool errorReported = false;
if (!Optional(KnownSymbolType.CommentStar))
{
errorReported = true;
Context.OnError(start, RazorResources.ParseError_RazorComment_Not_Terminated);
}
else
{
Output(SpanKind.MetaCode, AcceptedCharacters.None);
}
if (!Optional(KnownSymbolType.CommentStart))
{
if (!errorReported)
{
errorReported = true;
Context.OnError(start, RazorResources.ParseError_RazorComment_Not_Terminated);
}
}
else
{
Output(SpanKind.Transition, AcceptedCharacters.None);
}
}
}
Initialize(Span);
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse.StructuredData;
namespace OpenMetaverse.Packets
{
public abstract partial class Packet
{
#region Serialization/Deserialization
public static string ToXmlString(Packet packet)
{
return OSDParser.SerializeLLSDXmlString(GetLLSD(packet));
}
public static OSD GetLLSD(Packet packet)
{
OSDMap body = new OSDMap();
Type type = packet.GetType();
foreach (FieldInfo field in type.GetFields())
{
if (field.IsPublic)
{
Type blockType = field.FieldType;
if (blockType.IsArray)
{
object blockArray = field.GetValue(packet);
Array array = (Array)blockArray;
OSDArray blockList = new OSDArray(array.Length);
IEnumerator ie = array.GetEnumerator();
while (ie.MoveNext())
{
object block = ie.Current;
blockList.Add(BuildLLSDBlock(block));
}
body[field.Name] = blockList;
}
else
{
object block = field.GetValue(packet);
body[field.Name] = BuildLLSDBlock(block);
}
}
}
return body;
}
public static byte[] ToBinary(Packet packet)
{
return OSDParser.SerializeLLSDBinary(GetLLSD(packet));
}
public static Packet FromXmlString(string xml)
{
System.Xml.XmlTextReader reader =
new System.Xml.XmlTextReader(new System.IO.MemoryStream(Utils.StringToBytes(xml)));
return FromLLSD(OSDParser.DeserializeLLSDXml(reader));
}
public static Packet FromLLSD(OSD osd)
{
// FIXME: Need the inverse of the reflection magic above done here
throw new NotImplementedException();
}
#endregion Serialization/Deserialization
/// <summary>
/// Attempts to convert an LLSD structure to a known Packet type
/// </summary>
/// <param name="capsEventName">Event name, this must match an actual
/// packet name for a Packet to be successfully built</param>
/// <param name="body">LLSD to convert to a Packet</param>
/// <returns>A Packet on success, otherwise null</returns>
public static Packet BuildPacket(string capsEventName, OSDMap body)
{
Assembly assembly = Assembly.GetExecutingAssembly();
// Check if we have a subclass of packet with the same name as this event
Type type = assembly.GetType("OpenMetaverse.Packets." + capsEventName + "Packet", false);
if (type == null)
return null;
Packet packet = null;
try
{
// Create an instance of the object
packet = (Packet)Activator.CreateInstance(type);
// Iterate over all of the fields in the packet class, looking for matches in the LLSD
foreach (FieldInfo field in type.GetFields())
{
if (body.ContainsKey(field.Name))
{
Type blockType = field.FieldType;
if (blockType.IsArray)
{
OSDArray array = (OSDArray)body[field.Name];
Type elementType = blockType.GetElementType();
object[] blockArray = (object[])Array.CreateInstance(elementType, array.Count);
for (int i = 0; i < array.Count; i++)
{
OSDMap map = (OSDMap)array[i];
blockArray[i] = ParseLLSDBlock(map, elementType);
}
field.SetValue(packet, blockArray);
}
else
{
OSDMap map = (OSDMap)((OSDArray)body[field.Name])[0];
field.SetValue(packet, ParseLLSDBlock(map, blockType));
}
}
}
}
catch (Exception)
{
//FIXME Logger.Log(e.Message, Helpers.LogLevel.Error, e);
}
return packet;
}
private static object ParseLLSDBlock(OSDMap blockData, Type blockType)
{
object block = Activator.CreateInstance(blockType);
// Iterate over each field and set the value if a match was found in the LLSD
foreach (FieldInfo field in blockType.GetFields())
{
if (blockData.ContainsKey(field.Name))
{
Type fieldType = field.FieldType;
if (fieldType == typeof(ulong))
{
// ulongs come in as a byte array, convert it manually here
byte[] bytes = blockData[field.Name].AsBinary();
ulong value = Utils.BytesToUInt64(bytes);
field.SetValue(block, value);
}
else if (fieldType == typeof(uint))
{
// uints come in as a byte array, convert it manually here
byte[] bytes = blockData[field.Name].AsBinary();
uint value = Utils.BytesToUInt(bytes);
field.SetValue(block, value);
}
else if (fieldType == typeof(ushort))
{
// Just need a bit of manual typecasting love here
field.SetValue(block, (ushort)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(byte))
{
// Just need a bit of manual typecasting love here
field.SetValue(block, (byte)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(sbyte))
{
field.SetValue(block, (sbyte)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(short))
{
field.SetValue(block, (short)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(string))
{
field.SetValue(block, blockData[field.Name].AsString());
}
else if (fieldType == typeof(bool))
{
field.SetValue(block, blockData[field.Name].AsBoolean());
}
else if (fieldType == typeof(float))
{
field.SetValue(block, (float)blockData[field.Name].AsReal());
}
else if (fieldType == typeof(double))
{
field.SetValue(block, blockData[field.Name].AsReal());
}
else if (fieldType == typeof(int))
{
field.SetValue(block, blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(UUID))
{
field.SetValue(block, blockData[field.Name].AsUUID());
}
else if (fieldType == typeof(Vector3))
{
Vector3 vec = ((OSDArray)blockData[field.Name]).AsVector3();
field.SetValue(block, vec);
}
else if (fieldType == typeof(Vector4))
{
Vector4 vec = ((OSDArray)blockData[field.Name]).AsVector4();
field.SetValue(block, vec);
}
else if (fieldType == typeof(Quaternion))
{
Quaternion quat = ((OSDArray)blockData[field.Name]).AsQuaternion();
field.SetValue(block, quat);
}
else if (fieldType == typeof(byte[]) && blockData[field.Name].Type == OSDType.String)
{
field.SetValue(block, Utils.StringToBytes(blockData[field.Name]));
}
}
}
// Additional fields come as properties, Handle those as well.
foreach (PropertyInfo property in blockType.GetProperties())
{
if (blockData.ContainsKey(property.Name))
{
OSDType proptype = blockData[property.Name].Type;
MethodInfo set = property.GetSetMethod();
if (proptype.Equals(OSDType.Binary))
{
set.Invoke(block, new object[] { blockData[property.Name].AsBinary() });
}
else
set.Invoke(block, new object[] { Utils.StringToBytes(blockData[property.Name].AsString()) });
}
}
return block;
}
private static OSD BuildLLSDBlock(object block)
{
OSDMap map = new OSDMap();
Type blockType = block.GetType();
foreach (FieldInfo field in blockType.GetFields())
{
if (field.IsPublic)
map[field.Name] = OSD.FromObject(field.GetValue(block));
}
foreach (PropertyInfo property in blockType.GetProperties())
{
if (property.Name != "Length")
{
map[property.Name] = OSD.FromObject(property.GetValue(block, null));
}
}
return map;
}
}
}
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Android.Content;
using Android.Locations;
using Android.OS;
using Java.Lang;
namespace Xamarin.Geolocation
{
public class Geolocator
{
private static readonly DateTime Epoch = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc );
private readonly LocationManager manager;
private readonly object positionSync = new object();
private readonly string[] providers;
private string headingProvider;
private Position lastPosition;
private GeolocationContinuousListener listener;
public Geolocator( Context context )
{
if(context == null)
{
throw new ArgumentNullException( "context" );
}
manager = (LocationManager)context.GetSystemService( Context.LocationService );
providers =
manager.GetProviders( enabledOnly: false ).Where( s => s != LocationManager.PassiveProvider ).ToArray();
}
public event EventHandler<PositionEventArgs> PositionChanged;
public event EventHandler<PositionErrorEventArgs> PositionError;
public double DesiredAccuracy { get; set; }
public bool IsGeolocationAvailable
{
get { return providers.Length > 0; }
}
public bool IsGeolocationEnabled
{
get { return providers.Any( manager.IsProviderEnabled ); }
}
public bool IsListening
{
get { return listener != null; }
}
public bool SupportsHeading
{
get
{
return false;
// if (this.headingProvider == null || !this.manager.IsProviderEnabled (this.headingProvider))
// {
// Criteria c = new Criteria { BearingRequired = true };
// string providerName = this.manager.GetBestProvider (c, enabledOnly: false);
//
// LocationProvider provider = this.manager.GetProvider (providerName);
//
// if (provider.SupportsBearing())
// {
// this.headingProvider = providerName;
// return true;
// }
// else
// {
// this.headingProvider = null;
// return false;
// }
// }
// else
// return true;
}
}
public Task<Position> GetPositionAsync( CancellationToken cancelToken )
{
return GetPositionAsync( cancelToken, false );
}
public Task<Position> GetPositionAsync( CancellationToken cancelToken, bool includeHeading )
{
return GetPositionAsync( Timeout.Infinite, cancelToken );
}
public Task<Position> GetPositionAsync( int timeout )
{
return GetPositionAsync( timeout, false );
}
public Task<Position> GetPositionAsync( int timeout, bool includeHeading )
{
return GetPositionAsync( timeout, CancellationToken.None );
}
public Task<Position> GetPositionAsync( int timeout, CancellationToken cancelToken )
{
return GetPositionAsync( timeout, cancelToken, false );
}
public Task<Position> GetPositionAsync( int timeout, CancellationToken cancelToken, bool includeHeading )
{
if(timeout <= 0 && timeout != Timeout.Infinite)
{
throw new ArgumentOutOfRangeException( "timeout", "timeout must be greater than or equal to 0" );
}
var tcs = new TaskCompletionSource<Position>();
if(!IsListening)
{
GeolocationSingleListener singleListener = null;
singleListener = new GeolocationSingleListener(
(float)DesiredAccuracy,
timeout,
providers.Where( manager.IsProviderEnabled ),
finishedCallback: () =>
{
for(int i = 0; i < providers.Length; ++i)
{
manager.RemoveUpdates( singleListener );
}
} );
if(cancelToken != CancellationToken.None)
{
cancelToken.Register(
() =>
{
singleListener.Cancel();
for(int i = 0; i < providers.Length; ++i)
{
manager.RemoveUpdates( singleListener );
}
},
true );
}
try
{
Looper looper = Looper.MyLooper() ?? Looper.MainLooper;
int enabled = 0;
for(int i = 0; i < providers.Length; ++i)
{
if(manager.IsProviderEnabled( providers[i] ))
{
enabled++;
}
manager.RequestLocationUpdates( providers[i], 0, 0, singleListener, looper );
}
if(enabled == 0)
{
for(int i = 0; i < providers.Length; ++i)
{
manager.RemoveUpdates( singleListener );
}
tcs.SetException( new GeolocationException( GeolocationError.PositionUnavailable ) );
return tcs.Task;
}
}
catch(SecurityException ex)
{
tcs.SetException( new GeolocationException( GeolocationError.Unauthorized, ex ) );
return tcs.Task;
}
return singleListener.Task;
}
// If we're already listening, just use the current listener
lock(positionSync)
{
if(lastPosition == null)
{
if(cancelToken != CancellationToken.None)
{
cancelToken.Register( () => tcs.TrySetCanceled() );
}
EventHandler<PositionEventArgs> gotPosition = null;
gotPosition = ( s, e ) =>
{
tcs.TrySetResult( e.Position );
PositionChanged -= gotPosition;
};
PositionChanged += gotPosition;
}
else
{
tcs.SetResult( lastPosition );
}
}
return tcs.Task;
}
public void StartListening( int minTime, double minDistance )
{
StartListening( minTime, minDistance, false );
}
public void StartListening( int minTime, double minDistance, bool includeHeading )
{
if(minTime < 0)
{
throw new ArgumentOutOfRangeException( "minTime" );
}
if(minDistance < 0)
{
throw new ArgumentOutOfRangeException( "minDistance" );
}
if(IsListening)
{
throw new InvalidOperationException( "This Geolocator is already listening" );
}
listener = new GeolocationContinuousListener( manager, TimeSpan.FromMilliseconds( minTime ), providers );
listener.PositionChanged += OnListenerPositionChanged;
listener.PositionError += OnListenerPositionError;
Looper looper = Looper.MyLooper() ?? Looper.MainLooper;
for(int i = 0; i < providers.Length; ++i)
{
manager.RequestLocationUpdates( providers[i], minTime, (float)minDistance, listener, looper );
}
}
public void StopListening()
{
if(listener == null)
{
return;
}
listener.PositionChanged -= OnListenerPositionChanged;
listener.PositionError -= OnListenerPositionError;
for(int i = 0; i < providers.Length; ++i)
{
manager.RemoveUpdates( listener );
}
listener = null;
}
private void OnListenerPositionChanged( object sender, PositionEventArgs e )
{
if(!IsListening) // ignore anything that might come in afterwards
{
return;
}
lock(positionSync)
{
lastPosition = e.Position;
var changed = PositionChanged;
if(changed != null)
{
changed( this, e );
}
}
}
private void OnListenerPositionError( object sender, PositionErrorEventArgs e )
{
StopListening();
var error = PositionError;
if(error != null)
{
error( this, e );
}
}
internal static DateTimeOffset GetTimestamp( Location location )
{
return new DateTimeOffset( Epoch.AddMilliseconds( location.Time ) );
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
using System.Linq;
using RelationsInspector.Extensions;
namespace RelationsInspector.Backend.AssetDependency
{
using ObjMap = Dictionary<Object, HashSet<Object>>;
using ObjNodeGraph = Dictionary<ObjectNode, HashSet<ObjectNode>>;
public static class ObjectDependencyUtil
{
public static ObjNodeGraph GetReferenceGraph( string sceneFilePath, HashSet<Object> targets )
{
// get the scene's objects
var sceneObjects = UnityEditorInternal
.InternalEditorUtility
.LoadSerializedFileAndForget( sceneFilePath )
.ToHashSet();
// get the root gameObjects
var rootGOs = sceneObjects
.OfType<GameObject>()
.Where( go => go.transform.parent == null );
// build the Object graph
var objGraph = new ObjMap();
var targetArray = targets.ToArray();
foreach ( var rootGO in rootGOs )
{
var rootGOgraph = ObjectGraphUtil.GetDependencyGraph( rootGO, targetArray );
objGraph = ObjectGraphUtil.MergeGraphs( objGraph, rootGOgraph );
}
// convert it to a SceneObjectNode graph, so we can destroy the objects
var nodeGraph = ObjectGraphToObjectNodeGraph( objGraph, obj => GetSceneObjectNode( obj, targets, sceneObjects, sceneFilePath ) );
// destroy the scene Objects
var sceneObjArray = sceneObjects.ToArray();
for ( int i = 0; i < sceneObjArray.Length; i++ )
Object.DestroyImmediate( sceneObjArray[ i ] );
System.GC.Collect();
return nodeGraph;
}
public static ObjNodeGraph GetActiveSceneReferenceGraph( HashSet<Object> targets )
{
var rootGameObjects = ActiveSceneRootGameObjects();
// build the Object graph
var objGraph = new ObjMap();
var targetArray = targets.ToArray();
foreach ( var rootGO in rootGameObjects )
{
var rootGOgraph = ObjectGraphUtil.GetDependencyGraph( rootGO, targetArray );
objGraph = ObjectGraphUtil.MergeGraphs( objGraph, rootGOgraph );
}
// convert it to a SceneObjectNode graph, so we can destroy the objects
return ObjectGraphToObjectNodeGraph( objGraph, obj => GetActiveSceneObjectNode( obj, targets ) );
}
public static IEnumerable<GameObject> ActiveSceneRootGameObjects()
{
#if UNITY_5_3
return UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
#else
var prop = new HierarchyProperty( HierarchyType.GameObjects );
var expanded = new int[ 0 ];
while ( prop.Next( expanded ) )
{
yield return prop.pptrValue as GameObject;
}
#endif
}
public static string GetActiveSceneName( bool excludePath = true )
{
#if UNITY_5_3
string sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
#else
string sceneName = EditorApplication.currentScene;
#endif
return excludePath ? sceneName.Split( '/' ).Last() : sceneName;
}
// turn object graph into VisualNode graph (mapping obj -> name)
static ObjNodeGraph ObjectGraphToObjectNodeGraph( ObjMap objGraph, System.Func<Object, ObjectNode> getNode )
{
var referencedObjects = objGraph.Values.SelectMany( o => o ).ToHashSet();
// get all graph objects
var allObjs = objGraph.Keys.Concat( referencedObjects ).ToHashSet();
// map them to VisualNodes
var objToNode = allObjs.ToDictionary( obj => obj, obj => getNode( obj ) );
// convert from Object to SceneObjectNode and flip the edge direction
return referencedObjects.ToDictionary(
x => objToNode[ x ],
x => objGraph
.Where( pair => pair.Value.Contains( x ) )
.Select( pair => objToNode[ pair.Key ] )
.ToHashSet()
);
}
static ObjectNode GetActiveSceneObjectNode( Object obj, HashSet<Object> targets )
{
string label = obj.name;
string tooltip = "";
bool isSceneObj = false;
Object[] objects;
string sceneName = GetActiveSceneName();
var asCycleRep = obj as CycleRep;
if ( asCycleRep != null )
{
label = asCycleRep.name;
if ( targets.Intersect( asCycleRep.members ).Any() )
label += "\nScene " + sceneName;
tooltip = !string.IsNullOrEmpty( label ) ? label : string.Join( "\n", asCycleRep.members.Select( m => m.name ).ToArray() );
// we consider rep as a scene Obj if all its members are scene objs
isSceneObj = asCycleRep.members.All( m => IsSceneObject( m ) );
objects = asCycleRep.gameObject != null ? new[] { asCycleRep.gameObject } : asCycleRep.members.ToArray();
}
else
{
// add scene name. if label has content, put the scene name in a new line
if ( targets.Contains( obj ) )
label += ( ( label == "" ) ? "" : "\n" ) + "Scene " + sceneName;
isSceneObj = IsSceneObject( obj );
objects = new[] { obj };
}
return new ObjectNode( label, tooltip, objects, isSceneObj );
}
// return true if obj is part of a scene
static bool IsSceneObject( Object obj )
{
// scene objects have no asset path
return string.IsNullOrEmpty( AssetDatabase.GetAssetPath( obj ) );
}
static ObjectNode GetSceneObjectNode( Object obj, HashSet<Object> targets, HashSet<Object> sceneObjects, string scenePath )
{
string label = obj.name;
string tooltip = "";
bool isSceneObj = false;
Object[] objects;
string sceneName = System.IO.Path.GetFileNameWithoutExtension( scenePath );
var asCycleRep = obj as CycleRep;
if ( asCycleRep != null )
{
label = asCycleRep.name;
if ( targets.Intersect( asCycleRep.members ).Any() )
label += "\nScene " + sceneName;
tooltip = !string.IsNullOrEmpty( label ) ? label : string.Join( "\n", asCycleRep.members.Select( m => m.name ).ToArray() );
// we consider rep as a scene Obj if all its members are scene objs
isSceneObj = !asCycleRep.members.Except( sceneObjects ).Any();
objects = asCycleRep.gameObject != null ? new[] { asCycleRep.gameObject } : asCycleRep.members.ToArray();
}
else
{
// add scene name. if label has content, put the scene name in a new line
if ( targets.Contains( obj ) )
label += ((label == "") ? "" : "\n") + "Scene " + sceneName;
isSceneObj = sceneObjects.Contains( obj );
objects = new[] { obj };
}
if ( isSceneObj )
objects = new Object[] { }; // todo: get scene object
return new ObjectNode( label, tooltip, objects, isSceneObj );
}
// returns true if the object is a prefab
static bool IsPrefab( Object obj )
{
return PrefabUtility.GetPrefabParent( obj ) == null && PrefabUtility.GetPrefabObject( obj ) != null;
}
// merge two graphs
public static void AddGraph<T>( Dictionary<T, HashSet<T>> graph, Dictionary<T, HashSet<T>> addedGraph ) where T : class
{
foreach ( var pair in addedGraph )
{
if ( !graph.ContainsKey( pair.Key ) )
graph[ pair.Key ] = pair.Value;
else
graph[ pair.Key ].UnionWith( pair.Value );
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// TaskOperations operations.
/// </summary>
public partial interface ITaskOperations
{
/// <summary>
/// Adds a task to the specified job.
/// </summary>
/// <param name='jobId'>
/// The ID of the job to which the task is to be added.
/// </param>
/// <param name='task'>
/// The task to be added.
/// </param>
/// <param name='taskAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<TaskAddHeaders>> AddWithHttpMessagesAsync(string jobId, TaskAddParameter task, TaskAddOptions taskAddOptions = default(TaskAddOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <remarks>
/// For multi-instance tasks, information such as affinityId,
/// executionInfo and nodeInfo refer to the primary task. Use the list
/// subtasks API to retrieve information about subtasks.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='taskListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudTask>,TaskListHeaders>> ListWithHttpMessagesAsync(string jobId, TaskListOptions taskListOptions = default(TaskListOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Adds a collection of tasks to the specified job.
/// </summary>
/// <remarks>
/// Note that each task must have a unique ID. The Batch service may
/// not return the results for each task in the same order the tasks
/// were submitted in this request. If the server times out or the
/// connection is closed during the request, the request may have been
/// partially or fully processed, or not at all. In such cases, the
/// user should re-issue the request. Note that it is up to the user to
/// correctly handle failures when re-issuing a request. For example,
/// you should use the same task IDs during a retry so that if the
/// prior operation succeeded, the retry will not create extra tasks
/// unexpectedly. If the response contains any tasks which failed to
/// add, a client can retry the request. In a retry, it is most
/// efficient to resubmit only tasks that failed to add, and to omit
/// tasks that were successfully added on the first attempt.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to which the task collection is to be added.
/// </param>
/// <param name='value'>
/// The collection of tasks to add. The total serialized size of this
/// collection must be less than 4MB. If it is greater than 4MB (for
/// example if each task has 100's of resource files or environment
/// variables), the request will fail with code 'RequestBodyTooLarge'
/// and should be retried again with fewer tasks.
/// </param>
/// <param name='taskAddCollectionOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<TaskAddCollectionResult,TaskAddCollectionHeaders>> AddCollectionWithHttpMessagesAsync(string jobId, IList<TaskAddParameter> value, TaskAddCollectionOptions taskAddCollectionOptions = default(TaskAddCollectionOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a task from the specified job.
/// </summary>
/// <remarks>
/// When a task is deleted, all of the files in its directory on the
/// compute node where it ran are also deleted (regardless of the
/// retention time). For multi-instance tasks, the delete task
/// operation applies synchronously to the primary task; subtasks and
/// their files are then deleted asynchronously in the background.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job from which to delete the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to delete.
/// </param>
/// <param name='taskDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<TaskDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, string taskId, TaskDeleteOptions taskDeleteOptions = default(TaskDeleteOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified task.
/// </summary>
/// <remarks>
/// For multi-instance tasks, information such as affinityId,
/// executionInfo and nodeInfo refer to the primary task. Use the list
/// subtasks API to retrieve information about subtasks.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to get information about.
/// </param>
/// <param name='taskGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CloudTask,TaskGetHeaders>> GetWithHttpMessagesAsync(string jobId, string taskId, TaskGetOptions taskGetOptions = default(TaskGetOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the properties of the specified task.
/// </summary>
/// <param name='jobId'>
/// The ID of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to update.
/// </param>
/// <param name='constraints'>
/// Constraints that apply to this task. If omitted, the task is given
/// the default constraints. For multi-instance tasks, updating the
/// retention time applies only to the primary task and not subtasks.
/// </param>
/// <param name='taskUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<TaskUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, string taskId, TaskConstraints constraints = default(TaskConstraints), TaskUpdateOptions taskUpdateOptions = default(TaskUpdateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the subtasks that are associated with the specified
/// multi-instance task.
/// </summary>
/// <remarks>
/// If the task is not a multi-instance task then this returns an empty
/// collection.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='taskId'>
/// The ID of the task.
/// </param>
/// <param name='taskListSubtasksOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CloudTaskListSubtasksResult,TaskListSubtasksHeaders>> ListSubtasksWithHttpMessagesAsync(string jobId, string taskId, TaskListSubtasksOptions taskListSubtasksOptions = default(TaskListSubtasksOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Terminates the specified task.
/// </summary>
/// <remarks>
/// When the task has been terminated, it moves to the completed state.
/// For multi-instance tasks, the terminate task operation applies
/// synchronously to the primary task; subtasks are then terminated
/// asynchronously in the background.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to terminate.
/// </param>
/// <param name='taskTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<TaskTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string taskId, TaskTerminateOptions taskTerminateOptions = default(TaskTerminateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reactivates a task, allowing it to run again even if its retry
/// count has been exhausted.
/// </summary>
/// <remarks>
/// Reactivation makes a task eligible to be retried again up to its
/// maximum retry count. The task's state is changed to active. As the
/// task is no longer in the completed state, any previous exit code or
/// failure information is no longer available after reactivation. Each
/// time a task is reactivated, its retry count is reset to 0.
/// Reactivation will fail for tasks that are not completed or that
/// previously completed successfully (with an exit code of 0).
/// Additionally, it will fail if the job has completed (or is
/// terminating or deleting).
/// </remarks>
/// <param name='jobId'>
/// The ID of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to reactivate.
/// </param>
/// <param name='taskReactivateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationHeaderResponse<TaskReactivateHeaders>> ReactivateWithHttpMessagesAsync(string jobId, string taskId, TaskReactivateOptions taskReactivateOptions = default(TaskReactivateOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <remarks>
/// For multi-instance tasks, information such as affinityId,
/// executionInfo and nodeInfo refer to the primary task. Use the list
/// subtasks API to retrieve information about subtasks.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='taskListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CloudTask>,TaskListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, TaskListNextOptions taskListNextOptions = default(TaskListNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Data/Player/PlayerPublicProfile.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Data.Player {
/// <summary>Holder for reflection information generated from POGOProtos/Data/Player/PlayerPublicProfile.proto</summary>
public static partial class PlayerPublicProfileReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Data/Player/PlayerPublicProfile.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PlayerPublicProfileReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjBQT0dPUHJvdG9zL0RhdGEvUGxheWVyL1BsYXllclB1YmxpY1Byb2ZpbGUu",
"cHJvdG8SFlBPR09Qcm90b3MuRGF0YS5QbGF5ZXIaKVBPR09Qcm90b3MvRGF0",
"YS9QbGF5ZXIvUGxheWVyQXZhdGFyLnByb3RvImgKE1BsYXllclB1YmxpY1By",
"b2ZpbGUSDAoEbmFtZRgBIAEoCRINCgVsZXZlbBgCIAEoBRI0CgZhdmF0YXIY",
"AyABKAsyJC5QT0dPUHJvdG9zLkRhdGEuUGxheWVyLlBsYXllckF2YXRhcmIG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Data.Player.PlayerAvatarReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.Player.PlayerPublicProfile), global::POGOProtos.Data.Player.PlayerPublicProfile.Parser, new[]{ "Name", "Level", "Avatar" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class PlayerPublicProfile : pb::IMessage<PlayerPublicProfile> {
private static readonly pb::MessageParser<PlayerPublicProfile> _parser = new pb::MessageParser<PlayerPublicProfile>(() => new PlayerPublicProfile());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PlayerPublicProfile> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Data.Player.PlayerPublicProfileReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerPublicProfile() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerPublicProfile(PlayerPublicProfile other) : this() {
name_ = other.name_;
level_ = other.level_;
Avatar = other.avatar_ != null ? other.Avatar.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerPublicProfile Clone() {
return new PlayerPublicProfile(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "level" field.</summary>
public const int LevelFieldNumber = 2;
private int level_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Level {
get { return level_; }
set {
level_ = value;
}
}
/// <summary>Field number for the "avatar" field.</summary>
public const int AvatarFieldNumber = 3;
private global::POGOProtos.Data.Player.PlayerAvatar avatar_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Data.Player.PlayerAvatar Avatar {
get { return avatar_; }
set {
avatar_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PlayerPublicProfile);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PlayerPublicProfile other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Level != other.Level) return false;
if (!object.Equals(Avatar, other.Avatar)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Level != 0) hash ^= Level.GetHashCode();
if (avatar_ != null) hash ^= Avatar.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Level != 0) {
output.WriteRawTag(16);
output.WriteInt32(Level);
}
if (avatar_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Avatar);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Level != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Level);
}
if (avatar_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Avatar);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PlayerPublicProfile other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Level != 0) {
Level = other.Level;
}
if (other.avatar_ != null) {
if (avatar_ == null) {
avatar_ = new global::POGOProtos.Data.Player.PlayerAvatar();
}
Avatar.MergeFrom(other.Avatar);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
Level = input.ReadInt32();
break;
}
case 26: {
if (avatar_ == null) {
avatar_ = new global::POGOProtos.Data.Player.PlayerAvatar();
}
input.ReadMessage(avatar_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Data;
using System.Data.SqlClient;
using Oranikle.Report.Engine;
namespace Oranikle.Report.Engine
{
///<summary>
/// Main Report definition; this is the top of the tree that contains the complete
/// definition of a instance of a report.
///</summary>
public class Report
{
// private definitions
ReportDefn _Report;
DataSources _DataSources;
DataSets _DataSets;
int _RuntimeName=0; // used for the generation of unique runtime names
IDictionary _LURuntimeName; // Runtime names
ICollection _UserParameters; // User parameters
public ReportLog rl; // report log
RCache _Cache;
// Some report runtime variables
private string _Folder; // folder name
private string _ReportName; // report name
private string _CSS; // after rendering ASPHTML; this is separate
private string _JavaScript; // after rendering ASPHTML; this is separate
private object _CodeInstance; // Instance of the class generated for the Code element
private Page _CurrentPage; // needed for page header/footer references
private string _UserID; // UserID of client executing the report
private string _ClientLanguage; // Language code of the client executing the report.
private DataSourcesDefn _ParentConnections; // When running subreport with merge transactions this is parent report connections
public int PageNumber=1; // current page number
public int TotalPages=1; // total number of pages in report
public DateTime ExecutionTime; // start time of report execution
/// <summary>
/// Construct a runtime Report object using the compiled report definition.
/// </summary>
/// <param name="r"></param>
public Report(ReportDefn r)
{
_Report = r;
_Cache = new RCache();
rl = new ReportLog(r.rl);
_ReportName = r.Name;
_UserParameters = null;
_LURuntimeName = new ListDictionary(); // shouldn't be very many of these
if (r.Code != null)
_CodeInstance = r.Code.Load(this);
if (r.Classes != null)
r.Classes.Load(this);
}
// Event for Subreport data retrieval
/// <summary>
/// Event invoked just prior to obtaining data for the subreport. Setting DataSet
/// and DataConnection information during this event affects only this instance
/// of the Subreport.
/// </summary>
public event EventHandler<SubreportDataRetrievalEventArgs> SubreportDataRetrieval;
protected virtual void OnSubreportDataRetrieval(SubreportDataRetrievalEventArgs e)
{
if (SubreportDataRetrieval != null)
SubreportDataRetrieval(this, e);
}
public void SubreportDataRetrievalTriggerEvent()
{
if (SubreportDataRetrieval != null)
{
OnSubreportDataRetrieval(new SubreportDataRetrievalEventArgs(this, this.ReportDefinition.Subreport));
}
}
public bool IsSubreportDataRetrievalDefined
{
get { return SubreportDataRetrieval != null; }
}
public Page CurrentPage
{
get {return _CurrentPage;}
set {_CurrentPage = value;}
}
public Rows GetPageExpressionRows(string exprname)
{
if (_CurrentPage == null)
return null;
return _CurrentPage.GetPageExpressionRows(exprname);
}
/// <summary>
/// Read all the DataSets in the report
/// </summary>
/// <param name="parms"></param>
public bool RunGetData(IDictionary parms)
{
ExecutionTime = DateTime.Now;
bool bRows = _Report.RunGetData(this, parms);
return bRows;
}
/// <summary>
/// Renders the report using the requested presentation type.
/// </summary>
/// <param name="sg">IStreamGen for generating result stream</param>
/// <param name="type">Presentation type: HTML, XML, PDF, or ASP compatible HTML</param>
public void RunRender(IStreamGen sg, OutputPresentationType type)
{
RunRender(sg, type, "");
}
/// <summary>
/// Renders the report using the requested presentation type.
/// </summary>
/// <param name="sg">IStreamGen for generating result stream</param>
/// <param name="type">Presentation type: HTML, XML, PDF, MHT, or ASP compatible HTML</param>
/// <param name="prefix">For HTML puts prefix allowing unique name generation</param>
public void RunRender(IStreamGen sg, OutputPresentationType type, string prefix)
{
if (sg == null)
throw new ArgumentException("IStreamGen argument cannot be null.", "sg");
RenderHtml rh=null;
PageNumber = 1; // reset page numbers
TotalPages = 1;
IPresent ip;
MemoryStreamGen msg = null;
switch (type)
{
case OutputPresentationType.PDF:
ip = new RenderPdf(this, sg);
_Report.Run(ip);
break;
case OutputPresentationType.TIF:
ip = new RenderTif(this, sg);
_Report.Run(ip);
break;
case OutputPresentationType.TIFBW:
RenderTif rtif = new RenderTif(this, sg);
rtif.RenderColor = false;
ip = rtif;
_Report.Run(ip);
break;
case OutputPresentationType.XML:
if (_Report.DataTransform != null && _Report.DataTransform.Length > 0)
{
msg = new MemoryStreamGen();
ip = new RenderXml(this, msg);
_Report.Run(ip);
RunRenderXmlTransform(sg, msg);
}
else
{
ip = new RenderXml(this, sg);
_Report.Run(ip);
}
break;
case OutputPresentationType.MHTML:
this.RunRenderMht(sg);
break;
case OutputPresentationType.CSV:
ip = new RenderCsv(this, sg);
_Report.Run(ip);
break;
case OutputPresentationType.DMP:
ip = new RenderDMP(this, sg);
_Report.Run(ip);
break;
case OutputPresentationType.RTF:
ip = new RenderRtf(this, sg);
_Report.Run(ip);
break;
case OutputPresentationType.Excel:
ip = new RenderExcel(this, sg);
_Report.Run(ip);
break;
case OutputPresentationType.ASPHTML:
case OutputPresentationType.HTML:
default:
ip = rh = new RenderHtml(this, sg);
rh.Asp = (type == OutputPresentationType.ASPHTML);
rh.Prefix = prefix;
_Report.Run(ip);
// Retain the CSS and JavaScript
if (rh != null)
{
_CSS = rh.CSS;
_JavaScript = rh.JavaScript;
}
break;
}
sg.CloseMainStream();
_Cache = new RCache();
return;
}
private void RunRenderMht(IStreamGen sg)
{
OneFileStreamGen temp = null;
FileStream fs=null;
try
{
string tempHtmlReportFileName = Path.ChangeExtension(Path.GetTempFileName(), "htm");
temp = new OneFileStreamGen(tempHtmlReportFileName, true);
RunRender(temp, OutputPresentationType.HTML);
temp.CloseMainStream();
// Create the mht file (into a temporary file position)
MhtBuilder mhtConverter = new MhtBuilder();
string fileName = Path.ChangeExtension(Path.GetTempFileName(), "mht");
mhtConverter.SavePageArchive(fileName, "file://" + tempHtmlReportFileName);
// clean up the temporary files
foreach (string tempFileName in temp.FileList)
{
try
{
File.Delete(tempFileName);
}
catch{}
}
// Copy the mht file to the requested stream
Stream os = sg.GetStream();
fs = File.OpenRead(fileName);
byte[] ba = new byte[4096];
int rb=0;
while ((rb = fs.Read(ba, 0, ba.Length)) > 0)
{
os.Write(ba, 0, rb);
}
}
catch (Exception ex)
{
rl.LogError(8, "Error converting HTML to MHTML " + ex.Message +
Environment.NewLine + ex.StackTrace);
}
finally
{
if (temp != null)
temp.CloseMainStream();
if (fs != null)
fs.Close();
_Cache = new RCache();
}
}
/// <summary>
/// RunRenderPdf will render a Pdf given the page structure
/// </summary>
/// <param name="sg"></param>
/// <param name="pgs"></param>
public void RunRenderPdf(IStreamGen sg, Pages pgs)
{
PageNumber = 1; // reset page numbers
TotalPages = 1;
IPresent ip = new RenderPdf(this, sg);
try
{
ip.Start();
ip.RunPages(pgs);
ip.End();
}
finally
{
pgs.CleanUp(); // always want to make sure we cleanup to reduce resource usage
_Cache = new RCache();
}
return;
}
/// <summary>
/// RunRenderTif will render a TIF given the page structure
/// </summary>
/// <param name="sg"></param>
/// <param name="pgs"></param>
public void RunRenderTif(IStreamGen sg, Pages pgs, bool bColor)
{
PageNumber = 1; // reset page numbers
TotalPages = 1;
RenderTif ip = new RenderTif(this, sg);
ip.RenderColor = bColor;
try
{
ip.Start();
ip.RunPages(pgs);
ip.End();
}
finally
{
pgs.CleanUp(); // always want to make sure we cleanup to reduce resource usage
_Cache = new RCache();
}
return;
}
private void RunRenderXmlTransform(IStreamGen sg, MemoryStreamGen msg)
{
try
{
string file;
if (_Report.DataTransform[0] != Path.DirectorySeparatorChar)
file = this.Folder + Path.DirectorySeparatorChar + _Report.DataTransform;
else
file = this.Folder + _Report.DataTransform;
XmlUtil.XslTrans(file, msg.GetText(), sg.GetStream());
}
catch (Exception ex)
{
rl.LogError(8, "Error processing DataTransform " + ex.Message + "\r\n" + ex.StackTrace);
}
finally
{
msg.Dispose();
}
return;
}
/// <summary>
/// Build the Pages for this report.
/// </summary>
/// <returns></returns>
public Pages BuildPages()
{
PageNumber = 1; // reset page numbers
TotalPages = 1;
Pages pgs = new Pages(this);
pgs.PageHeight = _Report.PageHeight.Points;
pgs.PageWidth = _Report.PageWidth.Points;
try
{
Page p = new Page(1); // kick it off with a new page
pgs.AddPage(p);
// Create all the pages
_Report.Body.RunPage(pgs);
if (pgs.LastPage.IsEmpty() && pgs.PageCount > 1) // get rid of extraneous pages which
pgs.RemoveLastPage(); // can be caused by region page break at end
// Now create the headers and footers for all the pages (as needed)
if (_Report.PageHeader != null)
_Report.PageHeader.RunPage(pgs);
if (_Report.PageFooter != null)
_Report.PageFooter.RunPage(pgs);
// clear out any runtime clutter
foreach (Page pg in pgs)
pg.ResetPageExpressions();
pgs.SortPageItems(); // Handle ZIndex ordering of pages
}
catch (Exception e)
{
rl.LogError(8, "Exception running report\r\n" + e.Message + "\r\n" + e.StackTrace);
}
finally
{
pgs.CleanUp(); // always want to make sure we clean this up since
_Cache = new RCache();
}
return pgs;
}
public NeedPassword GetDataSourceReferencePassword
{
get {return _Report.GetDataSourceReferencePassword;}
set {_Report.GetDataSourceReferencePassword = value;}
}
public ReportDefn ReportDefinition
{
get {return this._Report;}
}
public void SetReportDefinition(ReportDefn r)
{
_Report = r;
_UserParameters = null; // force recalculation of user parameters
}
public string Description
{
get { return _Report.Description; }
}
public string Author
{
get { return _Report.Author; }
}
public string CSS
{
get { return _CSS; }
}
public string JavaScript
{
get { return _JavaScript; }
}
public object CodeInstance
{
get {return this._CodeInstance;}
}
public string CreateRuntimeName(object ro)
{
_RuntimeName++; // increment the name generator
string name = "o" + _RuntimeName.ToString();
_LURuntimeName.Add(name, ro);
return name;
}
public DataSources DataSources
{
get
{
if (_Report.DataSourcesDefn == null)
return null;
if (_DataSources == null)
_DataSources = new DataSources(this, _Report.DataSourcesDefn);
return _DataSources;
}
}
public DataSets DataSets
{
get
{
if (_Report.DataSetsDefn == null)
return null;
if (_DataSets == null)
_DataSets = new DataSets(this, _Report.DataSetsDefn);
return _DataSets;
}
}
/// <summary>
/// User provided parameters to the report. IEnumerable is a list of UserReportParameter.
/// </summary>
public ICollection UserReportParameters
{
get
{
if (_UserParameters != null) // only create this once
return _UserParameters; // since it can be expensive to build
if (ReportDefinition.ReportParameters == null || ReportDefinition.ReportParameters.Count <= 0)
{
List<UserReportParameter> parms = new List<UserReportParameter>(1);
_UserParameters = parms;
}
else
{
List<UserReportParameter> parms = new List<UserReportParameter>(ReportDefinition.ReportParameters.Count);
foreach (ReportParameter p in ReportDefinition.ReportParameters)
{
UserReportParameter urp = new UserReportParameter(this, p);
parms.Add(urp);
}
parms.TrimExcess();
_UserParameters = parms;
}
return _UserParameters;
}
}
/// <summary>
/// Get/Set the folder containing the report.
/// </summary>
public string Folder
{
get { return _Folder==null? _Report.ParseFolder: _Folder; }
set { _Folder = value; }
}
/// <summary>
/// Get/Set the report name. Usually this is the file name of the report sans extension.
/// </summary>
public string Name
{
get { return _ReportName; }
set { _ReportName = value; }
}
/// <summary>
/// Returns the height of the page in points.
/// </summary>
public float PageHeightPoints
{
get { return _Report.PageHeight.Points; }
}
/// <summary>
/// Returns the width of the page in points.
/// </summary>
public float PageWidthPoints
{
get { return _Report.PageWidthPoints; }
}
/// <summary>
/// Returns the left margin size in points.
/// </summary>
public float LeftMarginPoints
{
get { return _Report.LeftMargin.Points; }
}
/// <summary>
/// Returns the right margin size in points.
/// </summary>
public float RightMarginPoints
{
get { return _Report.RightMargin.Points; }
}
/// <summary>
/// Returns the top margin size in points.
/// </summary>
public float TopMarginPoints
{
get { return _Report.TopMargin.Points; }
}
/// <summary>
/// Returns the bottom margin size in points.
/// </summary>
public float BottomMarginPoints
{
get { return _Report.BottomMargin.Points; }
}
/// <summary>
/// Returns the maximum severity of any error. 4 or less indicating report continues running.
/// </summary>
public int ErrorMaxSeverity
{
get
{
if (this.rl == null)
return 0;
else
return rl.MaxSeverity;
}
}
/// <summary>
/// List of errors encountered so far.
/// </summary>
public IList ErrorItems
{
get
{
if (this.rl == null)
return null;
else
return rl.ErrorItems;
}
}
/// <summary>
/// Clear all errors generated up to now.
/// </summary>
public void ErrorReset()
{
if (this.rl == null)
return;
rl.Reset();
return;
}
/// <summary>
/// Get/Set the UserID, that is the running user.
/// </summary>
public string UserID
{
get { return _UserID == null? Environment.UserName: _UserID; }
set { _UserID = value; }
}
/// <summary>
/// Get/Set the three letter ISO language of the client of the report.
/// </summary>
public string ClientLanguage
{
get
{
if (_Report.Language != null)
return _Report.Language.EvaluateString(this, null);
if (_ClientLanguage != null)
return _ClientLanguage;
return CultureInfo.CurrentCulture.ThreeLetterISOLanguageName;
}
set { _ClientLanguage = value; }
}
public DataSourcesDefn ParentConnections
{
get {return _ParentConnections; }
set {_ParentConnections = value; }
}
public RCache Cache
{
get {return _Cache;}
}
}
public class RCache
{
Hashtable _RunCache;
public RCache()
{
_RunCache = new Hashtable();
}
public void Add(ReportLink rl, string name, object o)
{
_RunCache.Add(GetKey(rl,name), o);
}
public void AddReplace(ReportLink rl, string name, object o)
{
string key = GetKey(rl,name);
_RunCache.Remove(key);
_RunCache.Add(key, o);
}
public object Get(ReportLink rl, string name)
{
return _RunCache[GetKey(rl,name)];
}
public void Remove(ReportLink rl, string name)
{
_RunCache.Remove(GetKey(rl,name));
}
public void Add(ReportDefn rd, string name, object o)
{
_RunCache.Add(GetKey(rd,name), o);
}
public void AddReplace(ReportDefn rd, string name, object o)
{
string key = GetKey(rd,name);
_RunCache.Remove(key);
_RunCache.Add(key, o);
}
public object Get(ReportDefn rd, string name)
{
return _RunCache[GetKey(rd,name)];
}
public void Remove(ReportDefn rd, string name)
{
_RunCache.Remove(GetKey(rd,name));
}
public void Add(string key, object o)
{
_RunCache.Add(key, o);
}
public void AddReplace(string key, object o)
{
_RunCache.Remove(key);
_RunCache.Add(key, o);
}
public object Get(string key)
{
return _RunCache[key];
}
public void Remove(string key)
{
_RunCache.Remove(key);
}
public object Get(int i, string name)
{
return _RunCache[GetKey(i,name)];
}
public void Remove(int i, string name)
{
_RunCache.Remove(GetKey(i,name));
}
string GetKey(ReportLink rl, string name)
{
return GetKey(rl.ObjectNumber, name);
}
string GetKey(ReportDefn rd, string name)
{
if (rd.Subreport == null) // top level report use 0
return GetKey(0, name);
else // Use the subreports object number
return GetKey(rd.Subreport.ObjectNumber, name);
}
string GetKey(int onum, string name)
{
return name + onum.ToString();
}
}
// holder objects for value types
public class ODateTime
{
public DateTime dt;
public ODateTime(DateTime adt)
{
dt = adt;
}
}
public class ODecimal
{
public decimal d;
public ODecimal(decimal ad)
{
d = ad;
}
}
public class ODouble
{
public double d;
public ODouble(double ad)
{
d = ad;
}
}
public class OFloat
{
public float f;
public OFloat(float af)
{
f = af;
}
}
public class OInt
{
public int i;
public OInt(int ai)
{
i = ai;
}
}
public class SubreportDataRetrievalEventArgs : EventArgs
{
public readonly Report Report;
private Subreport SubReport;
private DataSets _DataSets;
public DataSets DataSets
{
get { return _DataSets; }
}
public SubReportParameters Parameters
{
get { return SubReport.Parameters; }
}
public SubreportDataRetrievalEventArgs(Report r, Subreport sr)
{
Report = r;
SubReport = sr;
_DataSets = new DataSets(Report, SubReport.ReportDefn.DataSetsDefn);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
//using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class Comparer<T> : IComparer, IComparer<T>
{
// To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small
// as possible and define most of the creation logic in a non-generic class.
public static Comparer<T> Default { get; } = (Comparer<T>)ComparerHelpers.CreateDefaultComparer(typeof(T));
public static Comparer<T> Create(Comparison<T> comparison)
{
if (comparison == null)
throw new ArgumentNullException(nameof(comparison));
return new ComparisonComparer<T>(comparison);
}
public abstract int Compare(T x, T y);
int IComparer.Compare(object x, object y)
{
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
if (x is T && y is T) return Compare((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
}
// Note: although there is a lot of shared code in the following
// comparers, we do not incorporate it into a base class for perf
// reasons. Adding another base class (even one with no fields)
// means another generic instantiation, which can be costly esp.
// for value types.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
public override int Compare(T x, T y)
{
if (x != null)
{
if (y != null) return x.CompareTo(y);
return 1;
}
if (y != null) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T>
{
public override int Compare(T? x, T? y)
{
if (x.HasValue)
{
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
}
if (y.HasValue) return -1;
return 0;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class ObjectComparer<T> : Comparer<T>
{
public override int Compare(T x, T y)
{
return System.Collections.Comparer.Default.Compare(x, y);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
internal sealed class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public override int Compare(T x, T y)
{
return _comparison(x, y);
}
}
// Enum comparers (specialized to avoid boxing)
// NOTE: Each of these needs to implement ISerializable
// and have a SerializationInfo/StreamingContext ctor,
// since we want to serialize as ObjectComparer for
// back-compat reasons (see below).
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public Int32EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
// Used by the serialization engine.
private Int32EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
int ix = JitHelpers.UnsafeEnumCast(x);
int iy = JitHelpers.UnsafeEnumCast(y);
return ix.CompareTo(iy);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Previously Comparer<T> was not specialized for enums,
// and instead fell back to ObjectComparer which uses boxing.
// Set the type as ObjectComparer here so code that serializes
// Comparer for enums will not break.
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class UInt32EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public UInt32EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
// Used by the serialization engine.
private UInt32EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
uint ix = (uint)JitHelpers.UnsafeEnumCast(x);
uint iy = (uint)JitHelpers.UnsafeEnumCast(y);
return ix.CompareTo(iy);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class Int64EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public Int64EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
public override int Compare(T x, T y)
{
long lx = JitHelpers.UnsafeEnumCastLong(x);
long ly = JitHelpers.UnsafeEnumCastLong(y);
return lx.CompareTo(ly);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
internal sealed class UInt64EnumComparer<T> : Comparer<T>, ISerializable where T : struct
{
public UInt64EnumComparer()
{
Debug.Assert(typeof(T).IsEnum);
}
// Used by the serialization engine.
private UInt64EnumComparer(SerializationInfo info, StreamingContext context) { }
public override int Compare(T x, T y)
{
ulong lx = (ulong)JitHelpers.UnsafeEnumCastLong(x);
ulong ly = (ulong)JitHelpers.UnsafeEnumCastLong(y);
return lx.CompareTo(ly);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
}
}
}
| |
/*
* UCS4Encoding.cs - Implementation of the
* "System.Xml.Private.UCS4Encoding" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Xml.Private
{
using System;
using System.Text;
internal class UCS4Encoding : Encoding
{
// Byte ordering for UCS-4 streams.
public enum ByteOrder
{
Order_1234,
Order_4321,
Order_3412,
Order_2143
}; // enum ByteOrder
// Internal state.
private ByteOrder byteOrder;
// Constructors.
public UCS4Encoding(ByteOrder order)
{
byteOrder = order;
}
// Get the number of bytes needed to encode a character buffer.
public override int GetByteCount(char[] chars, int index, int count)
{
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(index < 0 || index > chars.Length)
{
throw new ArgumentOutOfRangeException
("index", S._("ArgRange_Array"));
}
if(count < 0 || count > (chars.Length - index))
{
throw new ArgumentOutOfRangeException
("count", S._("ArgRange_Array"));
}
int bytes = 0;
char ch;
while(count > 0)
{
ch = chars[index++];
--count;
if(ch >= '\uD800' && ch <= '\uDBFF')
{
// Possibly the start of a surrogate pair.
if(count > 0)
{
ch = chars[index];
if(ch >= '\uDC00' && ch <= '\uDFFF')
{
++index;
--count;
}
}
}
bytes += 4;
}
return bytes;
}
// Get the bytes that result from encoding a character buffer.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", S._("ArgRange_Array"));
}
if(charCount < 0 || charCount > (chars.Length - charIndex))
{
throw new ArgumentOutOfRangeException
("charCount", S._("ArgRange_Array"));
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", S._("ArgRange_Array"));
}
int posn = byteIndex;
int left = bytes.Length - byteIndex;
uint pair;
char ch;
switch(byteOrder)
{
case ByteOrder.Order_1234:
{
while(charCount-- > 0)
{
if(left < 4)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
ch = chars[charIndex++];
if(ch >= '\uD800' && ch <= '\uDBFF' &&
charCount > 0 &&
chars[charIndex] >= '\uDC00' &&
chars[charIndex] <= '\uDFFF')
{
pair = ((uint)(ch - '\uD800')) << 10;
ch = chars[charIndex++];
--charCount;
pair += ((uint)(ch - '\uDC00')) + (uint)0x10000;
bytes[posn++] = (byte)(pair >> 24);
bytes[posn++] = (byte)(pair >> 16);
bytes[posn++] = (byte)(pair >> 8);
bytes[posn++] = (byte)pair;
}
else
{
bytes[posn++] = (byte)0;
bytes[posn++] = (byte)0;
bytes[posn++] = (byte)(ch >> 8);
bytes[posn++] = (byte)ch;
}
left -= 4;
}
}
break;
case ByteOrder.Order_4321:
{
while(charCount-- > 0)
{
if(left < 4)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
ch = chars[charIndex++];
if(ch >= '\uD800' && ch <= '\uDBFF' &&
charCount > 0 &&
chars[charIndex] >= '\uDC00' &&
chars[charIndex] <= '\uDFFF')
{
pair = ((uint)(ch - '\uD800')) << 10;
ch = chars[charIndex++];
--charCount;
pair += ((uint)(ch - '\uDC00')) + (uint)0x10000;
bytes[posn++] = (byte)pair;
bytes[posn++] = (byte)(pair >> 8);
bytes[posn++] = (byte)(pair >> 16);
bytes[posn++] = (byte)(pair >> 24);
}
else
{
bytes[posn++] = (byte)ch;
bytes[posn++] = (byte)(ch >> 8);
bytes[posn++] = (byte)0;
bytes[posn++] = (byte)0;
}
left -= 4;
}
}
break;
case ByteOrder.Order_3412:
{
while(charCount-- > 0)
{
if(left < 4)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
ch = chars[charIndex++];
if(ch >= '\uD800' && ch <= '\uDBFF' &&
charCount > 0 &&
chars[charIndex] >= '\uDC00' &&
chars[charIndex] <= '\uDFFF')
{
pair = ((uint)(ch - '\uD800')) << 10;
ch = chars[charIndex++];
--charCount;
pair += ((uint)(ch - '\uDC00')) + (uint)0x10000;
bytes[posn++] = (byte)(pair >> 8);
bytes[posn++] = (byte)pair;
bytes[posn++] = (byte)(pair >> 24);
bytes[posn++] = (byte)(pair >> 16);
}
else
{
bytes[posn++] = (byte)(ch >> 8);
bytes[posn++] = (byte)ch;
bytes[posn++] = (byte)0;
bytes[posn++] = (byte)0;
}
left -= 4;
}
}
break;
case ByteOrder.Order_2143:
{
while(charCount-- > 0)
{
if(left < 4)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
ch = chars[charIndex++];
if(ch >= '\uD800' && ch <= '\uDBFF' &&
charCount > 0 &&
chars[charIndex] >= '\uDC00' &&
chars[charIndex] <= '\uDFFF')
{
pair = ((uint)(ch - '\uD800')) << 10;
ch = chars[charIndex++];
--charCount;
pair += ((uint)(ch - '\uDC00')) + (uint)0x10000;
bytes[posn++] = (byte)(pair >> 16);
bytes[posn++] = (byte)(pair >> 24);
bytes[posn++] = (byte)pair;
bytes[posn++] = (byte)(pair >> 8);
}
else
{
bytes[posn++] = (byte)0;
bytes[posn++] = (byte)0;
bytes[posn++] = (byte)ch;
bytes[posn++] = (byte)(ch >> 8);
}
left -= 4;
}
}
break;
}
return posn - byteIndex;
}
// Read a 4-byte character from an array.
private static uint ReadChar(ByteOrder byteOrder, byte[] array, int index)
{
switch(byteOrder)
{
case ByteOrder.Order_1234:
{
return (((uint)(array[index])) << 24) |
(((uint)(array[index + 1])) << 16) |
(((uint)(array[index + 2])) << 8) |
((uint)(array[index + 3]));
}
// Not reached.
case ByteOrder.Order_4321:
{
return (((uint)(array[index + 3])) << 24) |
(((uint)(array[index + 2])) << 16) |
(((uint)(array[index + 1])) << 8) |
((uint)(array[index]));
}
// Not reached.
case ByteOrder.Order_3412:
{
return (((uint)(array[index + 2])) << 24) |
(((uint)(array[index + 3])) << 16) |
(((uint)(array[index])) << 8) |
((uint)(array[index + 1]));
}
// Not reached.
case ByteOrder.Order_2143:
{
return (((uint)(array[index + 1])) << 24) |
(((uint)(array[index])) << 16) |
(((uint)(array[index + 3])) << 8) |
((uint)(array[index + 2]));
}
// Not reached.
}
return 0;
}
// Internal version of "GetCharCount".
private static int InternalGetCharCount
(ByteOrder byteOrder, byte[] leftOver, int leftOverLen,
byte[] bytes, int index, int count)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(index < 0 || index > bytes.Length)
{
throw new ArgumentOutOfRangeException
("index", S._("ArgRange_Array"));
}
if(count < 0 || count > (bytes.Length - index))
{
throw new ArgumentOutOfRangeException
("count", S._("ArgRange_Array"));
}
// Handle the left-over buffer.
int chars = 0;
uint value;
if(leftOverLen > 0)
{
if((leftOverLen + count) < 4)
{
return 0;
}
Array.Copy(bytes, index, leftOver, leftOverLen,
4 - leftOverLen);
value = ReadChar(byteOrder, leftOver, 0);
if(value != (uint)0x0000FEFF)
{
if(value > (uint)0x0000FFFF)
{
chars += 2;
}
else
{
++chars;
}
}
index += 4 - leftOverLen;
count -= 4 - leftOverLen;
}
// Handle the main buffer contents.
while(count >= 4)
{
value = ReadChar(byteOrder, bytes, index);
if(value != (uint)0x0000FEFF)
{
if(value > (uint)0x0000FFFF)
{
chars += 2;
}
else
{
++chars;
}
}
index += 4;
count -= 4;
}
return chars;
}
// Get the number of characters needed to decode a byte buffer.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return InternalGetCharCount(byteOrder, null, 0,
bytes, index, count);
}
// Internal version of "GetChars".
private static int InternalGetChars(ByteOrder byteOrder,
byte[] leftOver, ref int leftOverLen,
byte[] bytes, int byteIndex,
int byteCount,
char[] chars, int charIndex)
{
// Validate the parameters.
if(bytes == null)
{
throw new ArgumentNullException("bytes");
}
if(chars == null)
{
throw new ArgumentNullException("chars");
}
if(byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException
("byteIndex", S._("ArgRange_Array"));
}
if(byteCount < 0 || byteCount > (bytes.Length - byteIndex))
{
throw new ArgumentOutOfRangeException
("byteCount", S._("ArgRange_Array"));
}
if(charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException
("charIndex", S._("ArgRange_Array"));
}
// Handle the left-over buffer.
uint value;
int start = charIndex;
int charCount = chars.Length - charIndex;
if(leftOverLen > 0)
{
if((leftOverLen + byteCount) < 4)
{
Array.Copy(bytes, byteIndex, leftOver,
leftOverLen, byteCount);
leftOverLen += byteCount;
return 0;
}
Array.Copy(bytes, byteIndex, leftOver, leftOverLen,
4 - leftOverLen);
value = ReadChar(byteOrder, leftOver, 0);
if(value != (uint)0x0000FEFF)
{
if(value > (uint)0x0000FFFF)
{
if(charCount < 2)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
value -= (uint)0x10000;
chars[charIndex++] =
(char)((value >> 10) + (uint)0xD800);
chars[charIndex++] =
(char)((value & (uint)0x03FF) + (uint)0xDC00);
charCount -= 2;
}
else
{
if(charCount < 1)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
chars[charIndex++] = (char)value;
--charCount;
}
}
byteIndex += 4 - leftOverLen;
byteCount -= 4 - leftOverLen;
leftOverLen = 0;
}
// Handle the main buffer contents.
while(byteCount >= 4)
{
value = ReadChar(byteOrder, bytes, byteIndex);
if(value != (uint)0x0000FEFF)
{
if(value > (uint)0x0000FFFF)
{
if(charCount < 2)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
value -= (uint)0x10000;
chars[charIndex++] =
(char)((value >> 10) + (uint)0xD800);
chars[charIndex++] =
(char)((value & (uint)0x03FF) + (uint)0xDC00);
charCount -= 2;
}
else
{
if(charCount < 1)
{
throw new ArgumentException
(S._("Arg_InsufficientSpace"));
}
chars[charIndex++] = (char)value;
--charCount;
}
}
byteIndex += 4;
byteCount -= 4;
}
if(byteCount > 0)
{
Array.Copy(bytes, byteIndex, leftOver, 0, byteCount);
leftOverLen = byteCount;
}
return charIndex - start;
}
// Get the characters that result from decoding a byte buffer.
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
int leftOverLen = 0;
return InternalGetChars(byteOrder, null, ref leftOverLen,
bytes, byteIndex, byteCount,
chars, charIndex);
}
// Get the maximum number of bytes needed to encode a
// specified number of characters.
public override int GetMaxByteCount(int charCount)
{
if(charCount < 0)
{
throw new ArgumentOutOfRangeException
("charCount", S._("ArgRange_NonNegative"));
}
return charCount * 4;
}
// Get the maximum number of characters needed to decode a
// specified number of bytes.
public override int GetMaxCharCount(int byteCount)
{
if(byteCount < 0)
{
throw new ArgumentOutOfRangeException
("byteCount", S._("ArgRange_NonNegative"));
}
// We may need to account for surrogate pairs,
// so use / 2 rather than / 4.
return byteCount / 2;
}
// Get a UCS4-specific decoder that is attached to this instance.
public override Decoder GetDecoder()
{
return new UCS4Decoder(byteOrder);
}
// Get the UCS4 preamble.
public override byte[] GetPreamble()
{
byte[] preamble = new byte[4];
switch(byteOrder)
{
case ByteOrder.Order_1234:
{
preamble[0] = (byte)0x00;
preamble[1] = (byte)0x00;
preamble[2] = (byte)0xFE;
preamble[3] = (byte)0xFF;
}
break;
case ByteOrder.Order_4321:
{
preamble[0] = (byte)0xFF;
preamble[1] = (byte)0xFE;
preamble[2] = (byte)0x00;
preamble[3] = (byte)0x00;
}
break;
case ByteOrder.Order_3412:
{
preamble[0] = (byte)0xFE;
preamble[1] = (byte)0xFF;
preamble[2] = (byte)0x00;
preamble[3] = (byte)0x00;
}
break;
case ByteOrder.Order_2143:
{
preamble[0] = (byte)0x00;
preamble[1] = (byte)0x00;
preamble[2] = (byte)0xFF;
preamble[3] = (byte)0xFE;
}
break;
}
return preamble;
}
// Determine if this object is equal to another.
public override bool Equals(Object value)
{
UCS4Encoding enc = (value as UCS4Encoding);
if(enc != null)
{
return (byteOrder == enc.byteOrder);
}
else
{
return false;
}
}
// Get the hash code for this object.
public override int GetHashCode()
{
return base.GetHashCode();
}
#if !ECMA_COMPAT
// Get the human-readable name for this encoding.
public override String EncodingName
{
get
{
switch(byteOrder)
{
case ByteOrder.Order_1234:
return "ucs-4 (Bigendian)";
case ByteOrder.Order_4321:
return "ucs-4";
case ByteOrder.Order_3412:
return "ucs-4 (order 3412)";
case ByteOrder.Order_2143:
return "ucs-4 (order 2143)";
}
return null;
}
}
#endif // !ECMA_COMPAT
// UCS4 decoder implementation.
private sealed class UCS4Decoder : Decoder
{
// Internal state.
private ByteOrder byteOrder;
private byte[] buffer;
private int bufferUsed;
// Constructor.
public UCS4Decoder(ByteOrder order)
{
byteOrder = order;
buffer = new byte [4];
bufferUsed = 0;
}
// Override inherited methods.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return InternalGetCharCount(byteOrder, buffer, bufferUsed,
bytes, index, count);
}
public override int GetChars(byte[] bytes, int byteIndex,
int byteCount, char[] chars,
int charIndex)
{
return InternalGetChars(byteOrder, buffer,
ref bufferUsed,
bytes, byteIndex, byteCount,
chars, charIndex);
}
} // class UCS4Decoder
}; // class UCS4Encoding
}; // namespace System.Xml.Private
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Cmdletization.Cim
{
/// <summary>
/// Tracks (per-session) terminating errors in a given cmdlet invocation.
/// </summary>
internal sealed class TerminatingErrorTracker
{
#region Getting tracker for a given cmdlet invocation
private static readonly ConditionalWeakTable<InvocationInfo, TerminatingErrorTracker> s_invocationToTracker =
new();
private static int GetNumberOfSessions(InvocationInfo invocationInfo)
{
// if user explicitly specifies CimSession, then the cmdlet runs against exactly those sessions
object cimSessionArgument;
if (invocationInfo.BoundParameters.TryGetValue("CimSession", out cimSessionArgument))
{
IList cimSessionArgumentAsList = (IList)cimSessionArgument;
return cimSessionArgumentAsList.Count;
}
// else - either CimSession=localhost OR CimSession is based on CimInstance->CimSession affinity
// CimInstance->CimSession affinity in instance cmdlets can come from:
// 1. InputObject (either passed through pipeline or explicitly bound to the parameter)
// 2. AssociatedObject (either passed through pipeline or explicitly bound to the parameter [we don't know the name of the parameter though])
// CimInstance->CimSession affinity in static cmdlets can come from:
// 1. Any method argument that is either a CimInstance or CimInstance[]
// Additionally in both instance and static cmdlets, if the pipeline object is a CimInstance, then it can affect the session acted against
if (invocationInfo.ExpectingInput)
{
// can get unlimited number of CimInstances through pipeline
// - this translates into potentially unlimited number of CimSession we will work with
return int.MaxValue;
}
int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1;
foreach (object cmdletArgument in invocationInfo.BoundParameters.Values)
{
CimInstance[] array = cmdletArgument as CimInstance[];
if (array != null)
{
int numberOfSessionsAssociatedWithArgument = array
.Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance)
.Distinct()
.Count();
maxNumberOfSessionsIndicatedByCimInstanceArguments = Math.Max(
maxNumberOfSessionsIndicatedByCimInstanceArguments,
numberOfSessionsAssociatedWithArgument);
}
}
return maxNumberOfSessionsIndicatedByCimInstanceArguments;
}
internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo, bool isStaticCmdlet)
{
var tracker = s_invocationToTracker.GetValue(
invocationInfo,
_ => new TerminatingErrorTracker(GetNumberOfSessions(invocationInfo)));
return tracker;
}
internal static TerminatingErrorTracker GetTracker(InvocationInfo invocationInfo)
{
TerminatingErrorTracker tracker;
bool foundTracker = s_invocationToTracker.TryGetValue(invocationInfo, out tracker);
Dbg.Assert(foundTracker, "The other overload of GetTracker should always be called first");
return tracker;
}
#endregion Getting tracker for a given cmdlet invocation
#region Tracking terminating errors within a single cmdlet invocation
private readonly int _numberOfSessions;
private int _numberOfReportedSessionTerminatingErrors;
private TerminatingErrorTracker(int numberOfSessions)
{
_numberOfSessions = numberOfSessions;
}
#region Tracking session's "connectivity" status
private readonly ConcurrentDictionary<CimSession, bool> _sessionToIsConnected = new();
internal void MarkSessionAsConnected(CimSession connectedSession)
{
_sessionToIsConnected.TryAdd(connectedSession, true);
}
internal bool DidSessionAlreadyPassedConnectivityTest(CimSession session)
{
bool alreadyPassedConnectivityTest = false;
if (_sessionToIsConnected.TryGetValue(session, out alreadyPassedConnectivityTest))
{
return alreadyPassedConnectivityTest;
}
return false;
}
internal Exception GetExceptionIfBrokenSession(
CimSession potentiallyBrokenSession,
bool skipTestConnection,
out bool sessionWasAlreadyTerminated)
{
if (IsSessionTerminated(potentiallyBrokenSession))
{
sessionWasAlreadyTerminated = true;
return null;
}
Exception sessionException = null;
if (!skipTestConnection &&
!this.DidSessionAlreadyPassedConnectivityTest(potentiallyBrokenSession))
{
try
{
CimInstance throwAwayCimInstance;
CimException cimException;
potentiallyBrokenSession.TestConnection(out throwAwayCimInstance, out cimException);
sessionException = cimException;
if (sessionException == null)
{
this.MarkSessionAsConnected(potentiallyBrokenSession);
}
}
catch (InvalidOperationException invalidOperationException)
{
sessionException = invalidOperationException;
}
}
if (sessionException != null)
{
MarkSessionAsTerminated(potentiallyBrokenSession, out sessionWasAlreadyTerminated);
return sessionException;
}
else
{
sessionWasAlreadyTerminated = false;
return null;
}
}
#endregion
#region Tracking session's "terminated" status
private readonly ConcurrentDictionary<CimSession, bool> _sessionToIsTerminated = new();
internal void MarkSessionAsTerminated(CimSession terminatedSession, out bool sessionWasAlreadyTerminated)
{
bool closureSafeSessionWasAlreadyTerminated = false;
_sessionToIsTerminated.AddOrUpdate(
key: terminatedSession,
addValue: true,
updateValueFactory:
(CimSession key, bool isTerminatedValueInDictionary) =>
{
closureSafeSessionWasAlreadyTerminated = isTerminatedValueInDictionary;
return true;
});
sessionWasAlreadyTerminated = closureSafeSessionWasAlreadyTerminated;
}
internal bool IsSessionTerminated(CimSession session)
{
bool isTerminated = _sessionToIsTerminated.GetOrAdd(session, false);
return isTerminated;
}
#endregion
#region Reporting errors in a way that takes session's "terminated" status into account
internal CmdletMethodInvoker<bool> GetErrorReportingDelegate(ErrorRecord errorRecord)
{
ManualResetEventSlim manualResetEventSlim = new();
object lockObject = new();
Func<Cmdlet, bool> action = (Cmdlet cmdlet) =>
{
_numberOfReportedSessionTerminatingErrors++;
if (_numberOfReportedSessionTerminatingErrors >= _numberOfSessions)
{
cmdlet.ThrowTerminatingError(errorRecord);
}
else
{
cmdlet.WriteError(errorRecord);
}
return false; // not really needed here, but required by CmdletMethodInvoker
};
return new CmdletMethodInvoker<bool>
{
Action = action,
Finished = manualResetEventSlim, // not really needed here, but required by CmdletMethodInvoker
SyncObject = lockObject, // not really needed here, but required by CmdletMethodInvoker
};
}
#endregion
#endregion Tracking terminating errors within a single cmdlet invocation
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using ShopifySharp.Filters;
using ShopifySharp.Infrastructure;
using ShopifySharp.Lists;
using Xunit;
namespace ShopifySharp.Tests
{
[Trait("Category", "ShopifyException")]
public class ShopifyException_Tests
{
private HttpRequestMessage PrepareRequest(HttpMethod method, string path, HttpContent content = null)
{
var ub = new UriBuilder(Utils.MyShopifyUrl)
{
Path = $"admin/{path}",
Scheme = "https",
Port = 443
};
var msg = new HttpRequestMessage(method, ub.ToString())
{
Content = content
};
msg.Headers.Add("X-Shopify-Access-Token", Utils.AccessToken);
return msg;
}
[Fact]
public void Throws_On_OAuth_Code_Used()
{
var rawBody = "{\"error\":\"invalid_request\",\"error_description\":\"The authorization code was not found or was already used\"}";
var res = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.NotAcceptable,
ReasonPhrase = "Not Acceptable",
Content = new StringContent(rawBody)
};
res.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ShopifyException ex = null;
try
{
ShopifyService.CheckResponseExceptions(res, rawBody);
}
catch (ShopifyException e)
{
ex = e;
}
Assert.NotNull(ex);
Assert.NotNull(ex.RawBody);
Assert.Single(ex.Errors);
Assert.Equal("(406 Not Acceptable) invalid_request: The authorization code was not found or was already used", ex.Message);
Assert.Equal("invalid_request: The authorization code was not found or was already used", ex.Errors.First());
}
[Fact]
public async Task Throws_On_Error_String()
{
HttpResponseMessage response;
string rawBody;
ShopifyException ex = null;
using (var client = new HttpClient())
{
while (ex == null)
{
// This request will return a response which looks like { errors: "some error message"}
using (var msg = PrepareRequest(HttpMethod.Get, "api_permissions/current.json"))
{
var req = client.SendAsync(msg);
response = await req;
rawBody = await response.Content.ReadAsStringAsync();
}
try
{
ShopifyService.CheckResponseExceptions(response, rawBody);
}
catch (ShopifyRateLimitException)
{
// Ignore this exception and retry the request.
// RateLimitExceptions may happen when all Exception tests are running and
// execution policies are retrying.
}
catch (ShopifyException e)
{
ex = e;
}
}
}
Assert.NotNull(ex);
Assert.Single(ex.Errors);
Assert.StartsWith("(403 Forbidden) Scope undefined for API access: api_permissions. Valid scopes: ", ex.Message);
Assert.StartsWith("Scope undefined for API access: api_permissions. Valid scopes: ", ex.Errors.First());
}
[Fact]
public async Task Throws_On_Error_Object()
{
HttpResponseMessage response;
string rawBody;
ShopifyException ex = null;
using (var client = new HttpClient())
{
while (ex == null)
{
// This request will return a response which looks like { errors: { "order" : "some error message" } }
using (var msg = PrepareRequest(HttpMethod.Post, "orders.json", new JsonContent(new { })))
{
var req = client.SendAsync(msg);
response = await req;
rawBody = await response.Content.ReadAsStringAsync();
}
try
{
ShopifyService.CheckResponseExceptions(response, rawBody);
}
catch (ShopifyRateLimitException)
{
// Ignore this exception and retry the request.
// RateLimitExceptions may happen when all Exception tests are running and
// execution policies are retrying.
}
catch (ShopifyException e)
{
ex = e;
}
}
}
Assert.NotNull(ex);
Assert.NotEmpty(ex.Errors);
Assert.Equal("(400 Bad Request) order: Required parameter missing or invalid", ex.Message);
var error = ex.Errors.First();
Assert.Equal("order: Required parameter missing or invalid", error);
}
[Fact]
public async Task Throws_On_Error_Arrays()
{
//Creating an order with tax lines on both line items and the order will return an error
var order = new Order()
{
CreatedAt = DateTime.UtcNow,
LineItems = new List<LineItem>()
{
new LineItem()
{
Title = "Click Keyboard",
Price = 99.99m,
Grams = 600,
Quantity = 1,
TaxLines = new List<TaxLine>()
{
new TaxLine()
{
Price = 1.0m,
Rate = 0.01m,
Title = "Keyboard tax"
}
}
}
},
TaxLines = new List<TaxLine>()
{
new TaxLine()
{
Price = 6.0m,
Rate = 0.06m,
Title = "State tax"
}
}
};
HttpResponseMessage response;
string rawBody;
ShopifyException ex = null;
using (var client = new HttpClient())
{
while (ex == null)
{
// This request will return a response which looks like { errors: { "order" : [ "some error message" ] } }
using (var msg = PrepareRequest(HttpMethod.Post, "orders.json", new JsonContent(new {order })))
{
var req = client.SendAsync(msg);
response = await req;
rawBody = await response.Content.ReadAsStringAsync();
}
try
{
ShopifyService.CheckResponseExceptions(response, rawBody);
}
catch (ShopifyRateLimitException)
{
// Ignore this exception and retry the request.
// RateLimitExceptions may happen when all Exception tests are running and
// execution policies are retrying.
}
catch (ShopifyException e)
{
ex = e;
}
}
}
Assert.NotNull(ex);
Assert.NotEmpty(ex.Errors);
Assert.NotNull(ex.RequestId);
Assert.Equal("(422 Unprocessable Entity) order: Tax lines must be associated with either order or line item but not both", ex.Message);
var error = ex.Errors.First();
Assert.Equal("order: Tax lines must be associated with either order or line item but not both", error);
}
[Fact]
public async Task Does_Not_Reach_Rate_Limit_With_Retry_Policy()
{
bool thrown = false;
int requestCount = 60;
IEnumerable<ListResult<Order>> list = null;
var service = new OrderService(Utils.MyShopifyUrl, Utils.AccessToken);
service.SetExecutionPolicy(new RetryExecutionPolicy());
try
{
var tasks = Enumerable.Range(0, requestCount).Select(_ => service.ListAsync(new OrderListFilter()
{
Limit = 1
}));
list = await Task.WhenAll(tasks);
}
catch (ShopifyRateLimitException)
{
thrown = true;
}
Assert.False(thrown);
Assert.NotNull(list);
Assert.Equal(requestCount, list.Count());
}
[Fact]
public async Task Does_Not_Reach_Rate_Limit_With_Smart_Retry_Policy()
{
bool thrown = false;
int requestCount = 60;
IEnumerable<ListResult<Order>> list = null;
var service = new OrderService(Utils.MyShopifyUrl, Utils.AccessToken);
service.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
try
{
var tasks = Enumerable.Range(0, requestCount).Select(_ => service.ListAsync(new OrderListFilter()
{
Limit = 1
}));
list = await Task.WhenAll(tasks);
}
catch (ShopifyRateLimitException)
{
thrown = true;
}
Assert.False(thrown);
Assert.NotNull(list);
Assert.Equal(requestCount, list.Count());
}
[Fact]
public async Task Catches_Rate_Limit()
{
int requestCount = 60;
var service = new OrderService(Utils.MyShopifyUrl, Utils.AccessToken);
ShopifyRateLimitException ex = null;
try
{
var tasks = Enumerable.Range(0, requestCount).Select(_ => service.ListAsync(new OrderListFilter()
{
Limit = 1
}));
await Task.WhenAll(tasks);
}
catch (ShopifyRateLimitException e)
{
ex = e;
}
Assert.NotNull(ex);
Assert.Equal(429, (int)ex.HttpStatusCode);
Assert.NotNull(ex.RawBody);
Assert.NotNull(ex.RequestId);
Assert.Single(ex.Errors);
Assert.Equal("(429 Too Many Requests) Exceeded 2 calls per second for api client. Reduce request rates to resume uninterrupted service.", ex.Message);
Assert.Equal("Exceeded 2 calls per second for api client. Reduce request rates to resume uninterrupted service.", ex.Errors.First());
}
[Fact]
public async Task Catches_Rate_Limit_With_Base_Exception()
{
int requestCount = 60;
var service = new OrderService(Utils.MyShopifyUrl, Utils.AccessToken);
ShopifyException ex = null;
try
{
var tasks = Enumerable.Range(0, requestCount).Select(_ => service.ListAsync(new OrderListFilter()
{
Limit = 1
}));
await Task.WhenAll(tasks);
}
catch (ShopifyException e)
{
ex = e;
}
Assert.NotNull(ex);
Assert.IsType<ShopifyRateLimitException>(ex);
Assert.Equal(429, (int)ex.HttpStatusCode);
Assert.NotNull(ex.RawBody);
Assert.NotNull(ex.RequestId);
Assert.Single(ex.Errors);
Assert.Equal("(429 Too Many Requests) Exceeded 2 calls per second for api client. Reduce request rates to resume uninterrupted service.", ex.Message);
Assert.Equal("Exceeded 2 calls per second for api client. Reduce request rates to resume uninterrupted service.", ex.Errors.First());
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
using NLog.Filters;
using NLog.Targets;
/// <summary>
/// Represents a logging rule. An equivalent of <logger /> configuration element.
/// </summary>
[NLogConfigurationItem]
public class LoggingRule
{
private readonly bool[] logLevels = new bool[LogLevel.MaxLevel.Ordinal + 1];
private string loggerNamePattern;
private MatchMode loggerNameMatchMode;
private string loggerNameMatchArgument;
/// <summary>
/// Initializes a new instance of the <see cref="LoggingRule" /> class.
/// </summary>
public LoggingRule()
{
this.Filters = new List<Filter>();
this.ChildRules = new List<LoggingRule>();
this.Targets = new List<Target>();
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingRule" /> class.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target)
{
this.Filters = new List<Filter>();
this.ChildRules = new List<LoggingRule>();
this.Targets = new List<Target>();
this.LoggerNamePattern = loggerNamePattern;
this.Targets.Add(target);
for (int i = minLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
this.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingRule" /> class.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
/// <remarks>By default no logging levels are defined. You should call <see cref="EnableLoggingForLevel"/> and <see cref="DisableLoggingForLevel"/> to set them.</remarks>
public LoggingRule(string loggerNamePattern, Target target)
{
this.Filters = new List<Filter>();
this.ChildRules = new List<LoggingRule>();
this.Targets = new List<Target>();
this.LoggerNamePattern = loggerNamePattern;
this.Targets.Add(target);
}
internal enum MatchMode
{
All,
None,
Equals,
StartsWith,
EndsWith,
Contains,
}
/// <summary>
/// Gets a collection of targets that should be written to when this rule matches.
/// </summary>
public IList<Target> Targets { get; private set; }
/// <summary>
/// Gets a collection of child rules to be evaluated when this rule matches.
/// </summary>
public IList<LoggingRule> ChildRules { get; private set; }
/// <summary>
/// Gets a collection of filters to be checked before writing to targets.
/// </summary>
public IList<Filter> Filters { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to quit processing any further rule when this one matches.
/// </summary>
public bool Final { get; set; }
/// <summary>
/// Gets or sets logger name pattern.
/// </summary>
/// <remarks>
/// Logger name pattern. It may include the '*' wildcard at the beginning, at the end or at both ends but not anywhere else.
/// </remarks>
public string LoggerNamePattern
{
get
{
return this.loggerNamePattern;
}
set
{
this.loggerNamePattern = value;
int firstPos = this.loggerNamePattern.IndexOf('*');
int lastPos = this.loggerNamePattern.LastIndexOf('*');
if (firstPos < 0)
{
this.loggerNameMatchMode = MatchMode.Equals;
this.loggerNameMatchArgument = value;
return;
}
if (firstPos == lastPos)
{
string before = this.LoggerNamePattern.Substring(0, firstPos);
string after = this.LoggerNamePattern.Substring(firstPos + 1);
if (before.Length > 0)
{
this.loggerNameMatchMode = MatchMode.StartsWith;
this.loggerNameMatchArgument = before;
return;
}
if (after.Length > 0)
{
this.loggerNameMatchMode = MatchMode.EndsWith;
this.loggerNameMatchArgument = after;
return;
}
return;
}
// *text*
if (firstPos == 0 && lastPos == this.LoggerNamePattern.Length - 1)
{
string text = this.LoggerNamePattern.Substring(1, this.LoggerNamePattern.Length - 2);
this.loggerNameMatchMode = MatchMode.Contains;
this.loggerNameMatchArgument = text;
return;
}
this.loggerNameMatchMode = MatchMode.None;
this.loggerNameMatchArgument = string.Empty;
}
}
/// <summary>
/// Gets the collection of log levels enabled by this rule.
/// </summary>
public ReadOnlyCollection<LogLevel> Levels
{
get
{
var levels = new List<LogLevel>();
for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (this.logLevels[i])
{
levels.Add(LogLevel.FromOrdinal(i));
}
}
return levels.AsReadOnly();
}
}
/// <summary>
/// Enables logging for a particular level.
/// </summary>
/// <param name="level">Level to be enabled.</param>
public void EnableLoggingForLevel(LogLevel level)
{
this.logLevels[level.Ordinal] = true;
}
/// <summary>
/// Disables logging for a particular level.
/// </summary>
/// <param name="level">Level to be disabled.</param>
public void DisableLoggingForLevel(LogLevel level)
{
this.logLevels[level.Ordinal] = false;
}
/// <summary>
/// Returns a string representation of <see cref="LoggingRule"/>. Used for debugging.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat(CultureInfo.InvariantCulture, "logNamePattern: ({0}:{1})", this.loggerNameMatchArgument, this.loggerNameMatchMode);
sb.Append(" levels: [ ");
for (int i = 0; i < this.logLevels.Length; ++i)
{
if (this.logLevels[0])
{
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString());
}
}
sb.Append("] appendTo: [ ");
foreach (Target app in this.Targets)
{
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", app.Name);
}
sb.Append("]");
return sb.ToString();
}
/// <summary>
/// Checks whether te particular log level is enabled for this rule.
/// </summary>
/// <param name="level">Level to be checked.</param>
/// <returns>A value of <see langword="true"/> when the log level is enabled, <see langword="false" /> otherwise.</returns>
public bool IsLoggingEnabledForLevel(LogLevel level)
{
return this.logLevels[level.Ordinal];
}
/// <summary>
/// Checks whether given name matches the logger name pattern.
/// </summary>
/// <param name="loggerName">String to be matched.</param>
/// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns>
public bool NameMatches(string loggerName)
{
switch (this.loggerNameMatchMode)
{
case MatchMode.All:
return true;
default:
case MatchMode.None:
return false;
case MatchMode.Equals:
return loggerName.Equals(this.loggerNameMatchArgument, StringComparison.Ordinal);
case MatchMode.StartsWith:
return loggerName.StartsWith(this.loggerNameMatchArgument, StringComparison.Ordinal);
case MatchMode.EndsWith:
return loggerName.EndsWith(this.loggerNameMatchArgument, StringComparison.Ordinal);
case MatchMode.Contains:
return loggerName.IndexOf(this.loggerNameMatchArgument, StringComparison.Ordinal) >= 0;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml.XPath;
using System.Xml.Xsl.IlGen;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Runtime.Versioning;
namespace System.Xml.Xsl
{
internal delegate void ExecuteDelegate(XmlQueryRuntime runtime);
/// <summary>
/// This internal class is the entry point for creating Msil assemblies from QilExpression.
/// </summary>
/// <remarks>
/// Generate will return an AssemblyBuilder with the following setup:
/// Assembly Name = "MS.Internal.Xml.CompiledQuery"
/// Module Dll Name = "MS.Internal.Xml.CompiledQuery.dll"
/// public class MS.Internal.Xml.CompiledQuery.Test {
/// public static void Execute(XmlQueryRuntime runtime);
/// public static void Root(XmlQueryRuntime runtime);
/// private static ... UserMethod1(XmlQueryRuntime runtime, ...);
/// ...
/// private static ... UserMethodN(XmlQueryRuntime runtime, ...);
/// }
///
/// XmlILGenerator incorporates a number of different technologies in order to generate efficient code that avoids caching
/// large result sets in memory:
///
/// 1. Code Iterators - Query results are computed using a set of composable, interlocking iterators that alone perform a
/// simple task, but together execute complex queries. The iterators are actually little blocks of code
/// that are connected to each other using a series of jumps. Because each iterator is not instantiated
/// as a separate object, the number of objects and number of function calls is kept to a minimum during
/// execution. Also, large result sets are often computed incrementally, with each iterator performing one step in a
/// pipeline of sequence items.
///
/// 2. Analyzers - During code generation, QilToMsil traverses the semantic tree representation of the query (QIL) several times.
/// As visits to each node in the tree start and end, various Analyzers are invoked. These Analyzers incrementally
/// collect and store information that is later used to generate faster and smaller code.
/// </remarks>
internal class XmlILGenerator
{
private QilExpression _qil;
private GenerateHelper _helper;
private XmlILOptimizerVisitor _optVisitor;
private XmlILVisitor _xmlIlVisitor;
private XmlILModule _module;
/// <summary>
/// Always output debug information in debug mode.
/// </summary>
public XmlILGenerator()
{
}
/// <summary>
/// Given the logical query plan (QilExpression) generate a physical query plan (MSIL) that can be executed.
/// </summary>
// SxS Note: The way the trace file names are created (hardcoded) is NOT SxS safe. However the files are
// created only for internal tracing purposes. In addition XmlILTrace class is not compiled into retail
// builds. As a result it is fine to suppress the FxCop SxS warning.
public XmlILCommand Generate(QilExpression query, TypeBuilder typeBldr)
{
_qil = query;
bool useLRE = (
!_qil.IsDebug &&
(typeBldr == null)
#if DEBUG
&& !XmlILTrace.IsEnabled // Dump assembly to disk; can't do this when using LRE
#endif
);
bool emitSymbols = _qil.IsDebug;
// In debug code, ensure that input QIL is correct
QilValidationVisitor.Validate(_qil);
#if DEBUG
// Trace Qil before optimization
XmlILTrace.WriteQil(this._qil, "qilbefore.xml");
// Trace optimizations
XmlILTrace.TraceOptimizations(this._qil, "qilopt.xml");
#endif
// Optimize and annotate the Qil graph
_optVisitor = new XmlILOptimizerVisitor(_qil, !_qil.IsDebug);
_qil = _optVisitor.Optimize();
// In debug code, ensure that output QIL is correct
QilValidationVisitor.Validate(_qil);
#if DEBUG
// Trace Qil after optimization
XmlILTrace.WriteQil(this._qil, "qilafter.xml");
#endif
// Create module in which methods will be generated
if (typeBldr != null)
{
_module = new XmlILModule(typeBldr);
}
else
{
_module = new XmlILModule(useLRE, emitSymbols);
}
// Create a code generation helper for the module; enable optimizations if IsDebug is false
_helper = new GenerateHelper(_module, _qil.IsDebug);
// Create helper methods
CreateHelperFunctions();
// Create metadata for the Execute function, which is the entry point to the query
// public static void Execute(XmlQueryRuntime);
MethodInfo methExec = _module.DefineMethod("Execute", typeof(void), new Type[] { }, new string[] { }, XmlILMethodAttributes.NonUser);
// Create metadata for the root expression
// public void Root()
Debug.Assert(_qil.Root != null);
XmlILMethodAttributes methAttrs = (_qil.Root.SourceLine == null) ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
MethodInfo methRoot = _module.DefineMethod("Root", typeof(void), new Type[] { }, new string[] { }, methAttrs);
// Declare all early bound function objects
foreach (EarlyBoundInfo info in _qil.EarlyBoundTypes)
{
_helper.StaticData.DeclareEarlyBound(info.NamespaceUri, info.EarlyBoundType);
}
// Create metadata for each QilExpression function that has at least one caller
CreateFunctionMetadata(_qil.FunctionList);
// Create metadata for each QilExpression global variable and parameter
CreateGlobalValueMetadata(_qil.GlobalVariableList);
CreateGlobalValueMetadata(_qil.GlobalParameterList);
// Generate Execute method
GenerateExecuteFunction(methExec, methRoot);
// Visit the QilExpression graph
_xmlIlVisitor = new XmlILVisitor();
_xmlIlVisitor.Visit(_qil, _helper, methRoot);
// Collect all static information required by the runtime
XmlQueryStaticData staticData = new XmlQueryStaticData(
_qil.DefaultWriterSettings,
_qil.WhitespaceRules,
_helper.StaticData
);
// Create static constructor that initializes XmlQueryStaticData instance at runtime
if (typeBldr != null)
{
CreateTypeInitializer(staticData);
// Finish up creation of the type
_module.BakeMethods();
return null;
}
else
{
// Finish up creation of the type
_module.BakeMethods();
// Create delegate over "Execute" method
ExecuteDelegate delExec = (ExecuteDelegate)_module.CreateDelegate("Execute", typeof(ExecuteDelegate));
return new XmlILCommand(delExec, staticData);
}
}
/// <summary>
/// Create MethodBuilder metadata for the specified QilExpression function. Annotate ndFunc with the
/// MethodBuilder. Also, each QilExpression argument type should be converted to a corresponding Clr type.
/// Each argument QilExpression node should be annotated with the resulting ParameterBuilder.
/// </summary>
private void CreateFunctionMetadata(IList<QilNode> funcList)
{
MethodInfo methInfo;
Type[] paramTypes;
string[] paramNames;
Type typReturn;
XmlILMethodAttributes methAttrs;
foreach (QilFunction ndFunc in funcList)
{
paramTypes = new Type[ndFunc.Arguments.Count];
paramNames = new string[ndFunc.Arguments.Count];
// Loop through all other parameters and save their types in the array
for (int arg = 0; arg < ndFunc.Arguments.Count; arg++)
{
QilParameter ndParam = (QilParameter)ndFunc.Arguments[arg];
Debug.Assert(ndParam.NodeType == QilNodeType.Parameter);
// Get the type of each argument as a Clr type
paramTypes[arg] = XmlILTypeHelper.GetStorageType(ndParam.XmlType);
// Get the name of each argument
if (ndParam.DebugName != null)
paramNames[arg] = ndParam.DebugName;
}
// Get the type of the return value
if (XmlILConstructInfo.Read(ndFunc).PushToWriterLast)
{
// Push mode functions do not have a return value
typReturn = typeof(void);
}
else
{
// Pull mode functions have a return value
typReturn = XmlILTypeHelper.GetStorageType(ndFunc.XmlType);
}
// Create the method metadata
methAttrs = ndFunc.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
methInfo = _module.DefineMethod(ndFunc.DebugName, typReturn, paramTypes, paramNames, methAttrs);
for (int arg = 0; arg < ndFunc.Arguments.Count; arg++)
{
// Set location of parameter on Let node annotation
XmlILAnnotation.Write(ndFunc.Arguments[arg]).ArgumentPosition = arg;
}
// Annotate function with the MethodInfo
XmlILAnnotation.Write(ndFunc).FunctionBinding = methInfo;
}
}
/// <summary>
/// Generate metadata for a method that calculates a global value.
/// </summary>
private void CreateGlobalValueMetadata(IList<QilNode> globalList)
{
MethodInfo methInfo;
Type typReturn;
XmlILMethodAttributes methAttrs;
foreach (QilReference ndRef in globalList)
{
// public T GlobalValue()
typReturn = XmlILTypeHelper.GetStorageType(ndRef.XmlType);
methAttrs = ndRef.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
methInfo = _module.DefineMethod(ndRef.DebugName.ToString(), typReturn, new Type[] { }, new string[] { }, methAttrs);
// Annotate function with MethodBuilder
XmlILAnnotation.Write(ndRef).FunctionBinding = methInfo;
}
}
/// <summary>
/// Generate the "Execute" method, which is the entry point to the query.
/// </summary>
private MethodInfo GenerateExecuteFunction(MethodInfo methExec, MethodInfo methRoot)
{
_helper.MethodBegin(methExec, null, false);
// Force some or all global values to be evaluated at start of query
EvaluateGlobalValues(_qil.GlobalVariableList);
EvaluateGlobalValues(_qil.GlobalParameterList);
// Root(runtime);
_helper.LoadQueryRuntime();
_helper.Call(methRoot);
_helper.MethodEnd();
return methExec;
}
/// <summary>
/// Create and generate various helper methods, which are called by the generated code.
/// </summary>
private void CreateHelperFunctions()
{
MethodInfo meth;
Label lblClone;
// public static XPathNavigator SyncToNavigator(XPathNavigator, XPathNavigator);
meth = _module.DefineMethod(
"SyncToNavigator",
typeof(XPathNavigator),
new Type[] { typeof(XPathNavigator), typeof(XPathNavigator) },
new string[] { null, null },
XmlILMethodAttributes.NonUser | XmlILMethodAttributes.Raw);
_helper.MethodBegin(meth, null, false);
// if (navigatorThis != null && navigatorThis.MoveTo(navigatorThat))
// return navigatorThis;
lblClone = _helper.DefineLabel();
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Brfalse, lblClone);
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Ldarg_1);
_helper.Call(XmlILMethods.NavMoveTo);
_helper.Emit(OpCodes.Brfalse, lblClone);
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Ret);
// LabelClone:
// return navigatorThat.Clone();
_helper.MarkLabel(lblClone);
_helper.Emit(OpCodes.Ldarg_1);
_helper.Call(XmlILMethods.NavClone);
_helper.MethodEnd();
}
/// <summary>
/// Generate code to force evaluation of some or all global variables and/or parameters.
/// </summary>
private void EvaluateGlobalValues(IList<QilNode> iterList)
{
MethodInfo methInfo;
foreach (QilIterator ndIter in iterList)
{
// Evaluate global if generating debug code, or if global might have side effects
if (_qil.IsDebug || OptimizerPatterns.Read(ndIter).MatchesPattern(OptimizerPatternName.MaybeSideEffects))
{
// Get MethodInfo that evaluates the global value and discard its return value
methInfo = XmlILAnnotation.Write(ndIter).FunctionBinding;
Debug.Assert(methInfo != null, "MethodInfo for global value should have been created previously.");
_helper.LoadQueryRuntime();
_helper.Call(methInfo);
_helper.Emit(OpCodes.Pop);
}
}
}
/// <summary>
/// Create static constructor that initializes XmlQueryStaticData instance at runtime.
/// </summary>
public void CreateTypeInitializer(XmlQueryStaticData staticData)
{
byte[] data;
Type[] ebTypes;
FieldInfo fldInitData, fldData, fldTypes;
ConstructorInfo cctor;
staticData.GetObjectData(out data, out ebTypes);
fldInitData = _module.DefineInitializedData("__" + XmlQueryStaticData.DataFieldName, data);
fldData = _module.DefineField(XmlQueryStaticData.DataFieldName, typeof(object));
fldTypes = _module.DefineField(XmlQueryStaticData.TypesFieldName, typeof(Type[]));
cctor = _module.DefineTypeInitializer();
_helper.MethodBegin(cctor, null, false);
// s_data = new byte[s_initData.Length] { s_initData };
_helper.LoadInteger(data.Length);
_helper.Emit(OpCodes.Newarr, typeof(byte));
_helper.Emit(OpCodes.Dup);
_helper.Emit(OpCodes.Ldtoken, fldInitData);
_helper.Call(XmlILMethods.InitializeArray);
_helper.Emit(OpCodes.Stsfld, fldData);
if (ebTypes != null)
{
// Type[] types = new Type[s_ebTypes.Length];
LocalBuilder locTypes = _helper.DeclareLocal("$$$types", typeof(Type[]));
_helper.LoadInteger(ebTypes.Length);
_helper.Emit(OpCodes.Newarr, typeof(Type));
_helper.Emit(OpCodes.Stloc, locTypes);
for (int idx = 0; idx < ebTypes.Length; idx++)
{
// types[idx] = ebTypes[idx];
_helper.Emit(OpCodes.Ldloc, locTypes);
_helper.LoadInteger(idx);
_helper.LoadType(ebTypes[idx]);
_helper.Emit(OpCodes.Stelem_Ref);
}
// s_types = types;
_helper.Emit(OpCodes.Ldloc, locTypes);
_helper.Emit(OpCodes.Stsfld, fldTypes);
}
_helper.MethodEnd();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// GameScreen.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.Graphics;
#endregion
namespace RobotGameData.Screen
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
Finished,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
#region Fields
GameScreen nextScreen = null;
#endregion
#region Properties
public GameScreen NextScreen
{
get { return nextScreen; }
set { nextScreen = value; }
}
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
bool isPopup = false;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
float transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 255 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public byte TransitionAlpha
{
get { return (byte)(255 - TransitionPosition * 255); }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected set { isExiting = value; }
}
bool isExiting = false;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
bool otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public GameScreenManager GameScreenManager
{
get { return gameScreenManager; }
internal set { gameScreenManager = value; }
}
GameScreenManager gameScreenManager;
#endregion
#region Initialization
/// <summary>
/// Initialize for the screen.
/// called after finished LoadGraphicsContent function of GameScreen.
/// </summary>
public virtual void InitializeScreen() { }
/// <summary>
/// Finalize for the screen.
/// called before jump to next GameScreen.
/// </summary>
public virtual void FinalizeScreen() { }
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent() { }
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
/// <summary>
/// calling when screen size has changed
/// </summary>
/// <param name="viewRect">new view area</param>
public virtual void OnSize(Rectangle newRect) { }
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
this.otherScreenHasFocus = otherScreenHasFocus;
if (isExiting)
{
// If the screen is going away to die, it should transition off.
screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
gameScreenManager.RemoveScreen(this);
isExiting = false;
screenState = ScreenState.Finished;
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds /
time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if ((transitionPosition <= 0) || (transitionPosition >= 1))
{
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(GameTime gameTime) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public abstract void Draw(GameTime gameTime);
#endregion
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
GameScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
isExiting = true;
}
}
public void OnSize()
{
Viewport viewport = RobotGameData.Render.Viewer.CurrentViewport;
OnSize(new Rectangle(viewport.X, viewport.Y, viewport.Width,
viewport.Height));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace PWMIS.OAuth2.AuthorizationCenter.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//==============================================================================
// MyGeneration.dOOdads
//
// VistaDBDynamicQuery.cs
// Version 5.0
// Updated - 10/09/2005
//------------------------------------------------------------------------------
// Copyright 2004, 2005 by MyGeneration Software.
// All Rights Reserved.
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose and without fee is hereby granted,
// provided that the above copyright notice appear in all copies and that
// both that copyright notice and this permission notice appear in
// supporting documentation.
//
// MYGENERATION SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
// SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS, IN NO EVENT SHALL MYGENERATION SOFTWARE BE LIABLE FOR ANY
// SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
// OR PERFORMANCE OF THIS SOFTWARE.
//==============================================================================
using System;
using System.Configuration;
using System.Data;
using VistaDB;
using System.Collections;
namespace MyGeneration.dOOdads
{
/// <summary>
/// VistaDBDynamicQuery is the VistaDB implementation of DynamicQuery
/// </summary>
public class VistaDBDynamicQuery : DynamicQuery
{
public VistaDBDynamicQuery(BusinessEntity entity)
: base(entity)
{
}
public override void AddOrderBy(string column, MyGeneration.dOOdads.WhereParameter.Dir direction)
{
base.AddOrderBy ("[" + column + "]", direction);
}
public override void AddOrderBy(DynamicQuery countAll, MyGeneration.dOOdads.WhereParameter.Dir direction)
{
if(countAll.CountAll)
{
base.AddOrderBy ("COUNT(*)", direction);
}
}
public override void AddOrderBy(AggregateParameter aggregate, MyGeneration.dOOdads.WhereParameter.Dir direction)
{
base.AddOrderBy (GetAggregate(aggregate, false), direction);
}
public override void AddGroupBy(string column)
{
base.AddGroupBy ("[" + column + "]");
}
public override void AddGroupBy(AggregateParameter aggregate)
{
// Support aggregates in a GROUP BY.
// Most common method
base.AddGroupBy (GetAggregate(aggregate, false));
}
public override void AddResultColumn(string columnName)
{
base.AddResultColumn ("[" + columnName + "]");
}
protected string GetAggregate(AggregateParameter wItem, bool withAlias)
{
string query = string.Empty;
switch(wItem.Function)
{
case AggregateParameter.Func.Avg:
query += "AVG(";
break;
case AggregateParameter.Func.Count:
query += "COUNT(";
break;
case AggregateParameter.Func.Max:
query += "MAX(";
break;
case AggregateParameter.Func.Min:
query += "MIN(";
break;
case AggregateParameter.Func.Sum:
query += "SUM(";
break;
case AggregateParameter.Func.StdDev:
query += "STDEV(";
break;
case AggregateParameter.Func.Var:
query += "VARIANCE(";
break;
}
if(wItem.Distinct)
{
query += "DISTINCT ";
}
query += "[" + wItem.Column + "])";
if(withAlias && wItem.Alias != string.Empty)
{
// Need DBMS string delimiter here
query += " AS [" + wItem.Alias + "]";
}
return query;
}
override protected IDbCommand _Load(string conjuction)
{
bool hasColumn = false;
bool selectAll = true;
string query;
query = "SELECT ";
if( this._distinct) query += " DISTINCT ";
if( this._top >= 0) query += " TOP " + this._top.ToString() + " ";
if(this._resultColumns.Length > 0)
{
query += this._resultColumns;
hasColumn = true;
selectAll = false;
}
if(this._countAll)
{
if(hasColumn)
{
query += ", ";
}
query += "COUNT(*)";
if(this._countAllAlias != string.Empty)
{
// Need DBMS string delimiter here
query += " AS [" + this._countAllAlias + "]";
}
hasColumn = true;
selectAll = false;
}
if(_aggregateParameters != null && _aggregateParameters.Count > 0)
{
bool isFirst = true;
if(hasColumn)
{
query += ", ";
}
AggregateParameter wItem;
foreach(object obj in _aggregateParameters)
{
wItem = obj as AggregateParameter;
if(wItem.IsDirty)
{
if(isFirst)
{
query += GetAggregate(wItem, true);
isFirst = false;
}
else
{
query += ", " + GetAggregate(wItem, true);
}
}
}
selectAll = false;
}
if(selectAll)
{
query += "*";
}
query += " FROM [" + this._entity.QuerySource + "]";
VistaDBCommand cmd = new VistaDBCommand();
if(_whereParameters != null && _whereParameters.Count > 0)
{
query += " WHERE ";
bool first = true;
bool requiresParam;
WhereParameter wItem;
bool skipConjuction = false;
string paramName;
string columnName;
foreach(object obj in _whereParameters)
{
// Maybe we injected text or a WhereParameter
if(obj.GetType().ToString() == "System.String")
{
string text = obj as string;
query += text;
if(text == "(")
{
skipConjuction = true;
}
}
else
{
wItem = obj as WhereParameter;
if(wItem.IsDirty)
{
if(!first && !skipConjuction)
{
if(wItem.Conjuction != WhereParameter.Conj.UseDefault)
{
if(wItem.Conjuction == WhereParameter.Conj.And)
query += " AND ";
else
query += " OR ";
}
else
{
query += " " + conjuction + " ";
}
}
requiresParam = true;
columnName = "[" + wItem.Column + "]";
paramName = "@" + wItem.Column + (++inc).ToString();
wItem.Param.ParameterName = paramName;
switch(wItem.Operator)
{
case WhereParameter.Operand.Equal:
query += columnName + " = " + paramName + " ";
break;
case WhereParameter.Operand.NotEqual:
query += columnName + " <> " + paramName + " ";
break;
case WhereParameter.Operand.GreaterThan:
query += columnName + " > " + paramName + " ";
break;
case WhereParameter.Operand.LessThan:
query += columnName + " < " + paramName + " ";
break;
case WhereParameter.Operand.LessThanOrEqual:
query += columnName + " <= " + paramName + " ";
break;
case WhereParameter.Operand.GreaterThanOrEqual:
query += columnName + " >= " + paramName + " ";
break;
case WhereParameter.Operand.Like:
query += columnName + " LIKE " + paramName + " ";
break;
case WhereParameter.Operand.NotLike:
query += columnName + " NOT LIKE " + paramName + " ";
break;
case WhereParameter.Operand.IsNull:
query += columnName + " IS NULL ";
requiresParam = false;
break;
case WhereParameter.Operand.IsNotNull:
query += columnName + " IS NOT NULL ";
requiresParam = false;
break;
case WhereParameter.Operand.In:
query += columnName + " IN (" + wItem.Value + ") ";
requiresParam = false;
break;
case WhereParameter.Operand.NotIn:
query += columnName + " NOT IN (" + wItem.Value + ") ";
requiresParam = false;
break;
case WhereParameter.Operand.Between:
query += columnName + " BETWEEN " + paramName;
cmd.Parameters.Add(paramName, wItem.BetweenBeginValue);
paramName = "@" + wItem.Column + (++inc).ToString();
query += " AND " + paramName;
cmd.Parameters.Add(paramName, wItem.BetweenEndValue);
requiresParam = false;
break;
}
if(requiresParam)
{
IDbCommand dbCmd = cmd as IDbCommand;
dbCmd.Parameters.Add(wItem.Param);
wItem.Param.Value = wItem.Value;
}
first = false;
skipConjuction = false;
}
}
}
}
if(_groupBy.Length > 0)
{
query += " GROUP BY " + _groupBy;
if(this._withRollup)
{
query += " WITH ROLLUP";
}
}
if(_orderBy.Length > 0)
{
query += " ORDER BY " + _orderBy;
}
cmd.CommandText = query;
return cmd;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Specifies global messaging configuration that are common to client and silo.
/// </summary>
public interface IMessagingConfiguration
{
/// <summary>
/// The ResponseTimeout attribute specifies the default timeout before a request is assumed to have failed.
/// </summary>
TimeSpan ResponseTimeout { get; set; }
/// <summary>
/// The MaxResendCount attribute specifies the maximal number of resends of the same message.
/// </summary>
int MaxResendCount { get; set; }
/// <summary>
/// The ResendOnTimeout attribute specifies whether the message should be automaticaly resend by the runtime when it times out on the sender.
/// Default is false.
/// </summary>
bool ResendOnTimeout { get; set; }
/// <summary>
/// The MaxSocketAge attribute specifies how long to keep an open socket before it is closed.
/// Default is TimeSpan.MaxValue (never close sockets automatically, unles they were broken).
/// </summary>
TimeSpan MaxSocketAge { get; set; }
/// <summary>
/// The DropExpiredMessages attribute specifies whether the message should be dropped if it has expired, that is if it was not delivered
/// to the destination before it has timed out on the sender.
/// Default is true.
/// </summary>
bool DropExpiredMessages { get; set; }
/// <summary>
/// The SiloSenderQueues attribute specifies the number of parallel queues and attendant threads used by the silo to send outbound
/// messages (requests, responses, and notifications) to other silos.
/// If this attribute is not specified, then System.Environment.ProcessorCount is used.
/// </summary>
int SiloSenderQueues { get; set; }
/// <summary>
/// The GatewaySenderQueues attribute specifies the number of parallel queues and attendant threads used by the silo Gateway to send outbound
/// messages (requests, responses, and notifications) to clients that are connected to it.
/// If this attribute is not specified, then System.Environment.ProcessorCount is used.
/// </summary>
int GatewaySenderQueues { get; set; }
/// <summary>
/// The ClientSenderBuckets attribute specifies the total number of grain buckets used by the client in client-to-gateway communication
/// protocol. In this protocol, grains are mapped to buckets and buckets are mapped to gateway connections, in order to enable stickiness
/// of grain to gateway (messages to the same grain go to the same gateway, while evenly spreading grains across gateways).
/// This number should be about 10 to 100 times larger than the expected number of gateway connections.
/// If this attribute is not specified, then Math.Pow(2, 13) is used.
/// </summary>
int ClientSenderBuckets { get; set; }
/// <summary>
/// This is the period of time a gateway will wait before dropping a disconnected client.
/// </summary>
TimeSpan ClientDropTimeout { get; set; }
/// <summary>
/// The UseStandardSerializer attribute, if provided and set to "true", forces the use of the standard .NET serializer instead
/// of the custom Orleans serializer.
/// This parameter is intended for use only for testing and troubleshooting.
/// In production, the custom Orleans serializer should always be used because it performs significantly better.
/// </summary>
bool UseStandardSerializer { get; set; }
/// <summary>
/// The size of a buffer in the messaging buffer pool.
/// </summary>
int BufferPoolBufferSize { get; set; }
/// <summary>
/// The maximum size of the messaging buffer pool.
/// </summary>
int BufferPoolMaxSize { get; set; }
/// <summary>
/// The initial size of the messaging buffer pool that is pre-allocated.
/// </summary>
int BufferPoolPreallocationSize { get; set; }
/// <summary>
/// Whether to use automatic batching of messages. Default is false.
/// </summary>
bool UseMessageBatching { get; set; }
/// <summary>
/// The maximum batch size for automatic batching of messages, when message batching is used.
/// </summary>
int MaxMessageBatchingSize { get; set; }
/// <summary>
/// The list of serialization providers
/// </summary>
List<TypeInfo> SerializationProviders { get; }
}
/// <summary>
/// Messaging configuration that are common to client and silo.
/// </summary>
[Serializable]
public class MessagingConfiguration : IMessagingConfiguration
{
public TimeSpan ResponseTimeout { get; set; }
public int MaxResendCount { get; set; }
public bool ResendOnTimeout { get; set; }
public TimeSpan MaxSocketAge { get; set; }
public bool DropExpiredMessages { get; set; }
public int SiloSenderQueues { get; set; }
public int GatewaySenderQueues { get; set; }
public int ClientSenderBuckets { get; set; }
public TimeSpan ClientDropTimeout { get; set; }
public bool UseStandardSerializer { get; set; }
public bool UseJsonFallbackSerializer { get; set; }
public int BufferPoolBufferSize { get; set; }
public int BufferPoolMaxSize { get; set; }
public int BufferPoolPreallocationSize { get; set; }
public bool UseMessageBatching { get; set; }
public int MaxMessageBatchingSize { get; set; }
/// <summary>
/// The MaxForwardCount attribute specifies the maximal number of times a message is being forwared from one silo to another.
/// Forwarding is used internally by the tuntime as a recovery mechanism when silos fail and the membership is unstable.
/// In such times the messages might not be routed correctly to destination, and runtime attempts to forward such messages a number of times before rejecting them.
/// </summary>
public int MaxForwardCount { get; set; }
public List<TypeInfo> SerializationProviders { get; private set; }
internal double RejectionInjectionRate { get; set; }
internal double MessageLossInjectionRate { get; set; }
private static readonly TimeSpan DEFAULT_MAX_SOCKET_AGE = TimeSpan.MaxValue;
internal const int DEFAULT_MAX_FORWARD_COUNT = 2;
private const bool DEFAULT_RESEND_ON_TIMEOUT = false;
private const bool DEFAULT_USE_STANDARD_SERIALIZER = false;
private static readonly int DEFAULT_SILO_SENDER_QUEUES = Environment.ProcessorCount;
private static readonly int DEFAULT_GATEWAY_SENDER_QUEUES = Environment.ProcessorCount;
private static readonly int DEFAULT_CLIENT_SENDER_BUCKETS = (int)Math.Pow(2, 13);
private const int DEFAULT_BUFFER_POOL_BUFFER_SIZE = 4 * 1024;
private const int DEFAULT_BUFFER_POOL_MAX_SIZE = 10000;
private const int DEFAULT_BUFFER_POOL_PREALLOCATION_SIZE = 250;
private const bool DEFAULT_DROP_EXPIRED_MESSAGES = true;
private const double DEFAULT_ERROR_INJECTION_RATE = 0.0;
private const bool DEFAULT_USE_MESSAGE_BATCHING = false;
private const int DEFAULT_MAX_MESSAGE_BATCH_SIZE = 10;
private readonly bool isSiloConfig;
internal MessagingConfiguration(bool isSilo)
{
isSiloConfig = isSilo;
ResponseTimeout = Constants.DEFAULT_RESPONSE_TIMEOUT;
MaxResendCount = 0;
ResendOnTimeout = DEFAULT_RESEND_ON_TIMEOUT;
MaxSocketAge = DEFAULT_MAX_SOCKET_AGE;
DropExpiredMessages = DEFAULT_DROP_EXPIRED_MESSAGES;
SiloSenderQueues = DEFAULT_SILO_SENDER_QUEUES;
GatewaySenderQueues = DEFAULT_GATEWAY_SENDER_QUEUES;
ClientSenderBuckets = DEFAULT_CLIENT_SENDER_BUCKETS;
ClientDropTimeout = Constants.DEFAULT_CLIENT_DROP_TIMEOUT;
UseStandardSerializer = DEFAULT_USE_STANDARD_SERIALIZER;
BufferPoolBufferSize = DEFAULT_BUFFER_POOL_BUFFER_SIZE;
BufferPoolMaxSize = DEFAULT_BUFFER_POOL_MAX_SIZE;
BufferPoolPreallocationSize = DEFAULT_BUFFER_POOL_PREALLOCATION_SIZE;
if (isSiloConfig)
{
MaxForwardCount = DEFAULT_MAX_FORWARD_COUNT;
RejectionInjectionRate = DEFAULT_ERROR_INJECTION_RATE;
MessageLossInjectionRate = DEFAULT_ERROR_INJECTION_RATE;
}
else
{
MaxForwardCount = 0;
RejectionInjectionRate = 0.0;
MessageLossInjectionRate = 0.0;
}
UseMessageBatching = DEFAULT_USE_MESSAGE_BATCHING;
MaxMessageBatchingSize = DEFAULT_MAX_MESSAGE_BATCH_SIZE;
SerializationProviders = new List<TypeInfo>();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat(" Messaging:").AppendLine();
sb.AppendFormat(" Response timeout: {0}", ResponseTimeout).AppendLine();
sb.AppendFormat(" Maximum resend count: {0}", MaxResendCount).AppendLine();
sb.AppendFormat(" Resend On Timeout: {0}", ResendOnTimeout).AppendLine();
sb.AppendFormat(" Maximum Socket Age: {0}", MaxSocketAge).AppendLine();
sb.AppendFormat(" Drop Expired Messages: {0}", DropExpiredMessages).AppendLine();
if (isSiloConfig)
{
sb.AppendFormat(" Silo Sender queues: {0}", SiloSenderQueues).AppendLine();
sb.AppendFormat(" Gateway Sender queues: {0}", GatewaySenderQueues).AppendLine();
sb.AppendFormat(" Client Drop Timeout: {0}", ClientDropTimeout).AppendLine();
}
else
{
sb.AppendFormat(" Client Sender Buckets: {0}", ClientSenderBuckets).AppendLine();
}
sb.AppendFormat(" Use standard (.NET) serializer: {0}", UseStandardSerializer)
.AppendLine(isSiloConfig ? "" : " [NOTE: This *MUST* match the setting on the server or nothing will work!]");
sb.AppendFormat(" Use fallback json serializer: {0}", UseJsonFallbackSerializer)
.AppendLine(isSiloConfig ? "" : " [NOTE: This *MUST* match the setting on the server or nothing will work!]");
sb.AppendFormat(" Buffer Pool Buffer Size: {0}", BufferPoolBufferSize).AppendLine();
sb.AppendFormat(" Buffer Pool Max Size: {0}", BufferPoolMaxSize).AppendLine();
sb.AppendFormat(" Buffer Pool Preallocation Size: {0}", BufferPoolPreallocationSize).AppendLine();
sb.AppendFormat(" Use Message Batching: {0}", UseMessageBatching).AppendLine();
sb.AppendFormat(" Max Message Batching Size: {0}", MaxMessageBatchingSize).AppendLine();
if (isSiloConfig)
{
sb.AppendFormat(" Maximum forward count: {0}", MaxForwardCount).AppendLine();
}
SerializationProviders.ForEach(sp =>
sb.AppendFormat(" Serialization provider: {0}", sp.FullName).AppendLine());
return sb.ToString();
}
internal virtual void Load(XmlElement child)
{
ResponseTimeout = child.HasAttribute("ResponseTimeout")
? ConfigUtilities.ParseTimeSpan(child.GetAttribute("ResponseTimeout"),
"Invalid ResponseTimeout")
: Constants.DEFAULT_RESPONSE_TIMEOUT;
if (child.HasAttribute("MaxResendCount"))
{
MaxResendCount = ConfigUtilities.ParseInt(child.GetAttribute("MaxResendCount"),
"Invalid integer value for the MaxResendCount attribute on the Messaging element");
}
if (child.HasAttribute("ResendOnTimeout"))
{
ResendOnTimeout = ConfigUtilities.ParseBool(child.GetAttribute("ResendOnTimeout"),
"Invalid Boolean value for the ResendOnTimeout attribute on the Messaging element");
}
if (child.HasAttribute("MaxSocketAge"))
{
MaxSocketAge = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxSocketAge"),
"Invalid time span set for the MaxSocketAge attribute on the Messaging element");
}
if (child.HasAttribute("DropExpiredMessages"))
{
DropExpiredMessages = ConfigUtilities.ParseBool(child.GetAttribute("DropExpiredMessages"),
"Invalid integer value for the DropExpiredMessages attribute on the Messaging element");
}
//--
if (isSiloConfig)
{
if (child.HasAttribute("SiloSenderQueues"))
{
SiloSenderQueues = ConfigUtilities.ParseInt(child.GetAttribute("SiloSenderQueues"),
"Invalid integer value for the SiloSenderQueues attribute on the Messaging element");
}
if (child.HasAttribute("GatewaySenderQueues"))
{
GatewaySenderQueues = ConfigUtilities.ParseInt(child.GetAttribute("GatewaySenderQueues"),
"Invalid integer value for the GatewaySenderQueues attribute on the Messaging element");
}
ClientDropTimeout = child.HasAttribute("ClientDropTimeout")
? ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientDropTimeout"),
"Invalid ClientDropTimeout")
: Constants.DEFAULT_CLIENT_DROP_TIMEOUT;
}
else
{
if (child.HasAttribute("ClientSenderBuckets"))
{
ClientSenderBuckets = ConfigUtilities.ParseInt(child.GetAttribute("ClientSenderBuckets"),
"Invalid integer value for the ClientSenderBuckets attribute on the Messaging element");
}
}
if (child.HasAttribute("UseStandardSerializer"))
{
UseStandardSerializer =
ConfigUtilities.ParseBool(child.GetAttribute("UseStandardSerializer"),
"invalid boolean value for the UseStandardSerializer attribute on the Messaging element");
}
if (child.HasAttribute("UseJsonFallbackSerializer"))
{
UseJsonFallbackSerializer =
ConfigUtilities.ParseBool(child.GetAttribute("UseJsonFallbackSerializer"),
"invalid boolean value for the UseJsonFallbackSerializer attribute on the Messaging element");
}
//--
if (child.HasAttribute("BufferPoolBufferSize"))
{
BufferPoolBufferSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolBufferSize"),
"Invalid integer value for the BufferPoolBufferSize attribute on the Messaging element");
}
if (child.HasAttribute("BufferPoolMaxSize"))
{
BufferPoolMaxSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolMaxSize"),
"Invalid integer value for the BufferPoolMaxSize attribute on the Messaging element");
}
if (child.HasAttribute("BufferPoolPreallocationSize"))
{
BufferPoolPreallocationSize = ConfigUtilities.ParseInt(child.GetAttribute("BufferPoolPreallocationSize"),
"Invalid integer value for the BufferPoolPreallocationSize attribute on the Messaging element");
}
if (child.HasAttribute("UseMessageBatching"))
{
UseMessageBatching = ConfigUtilities.ParseBool(child.GetAttribute("UseMessageBatching"),
"Invalid boolean value for the UseMessageBatching attribute on the Messaging element");
}
if (child.HasAttribute("MaxMessageBatchingSize"))
{
MaxMessageBatchingSize = ConfigUtilities.ParseInt(child.GetAttribute("MaxMessageBatchingSize"),
"Invalid integer value for the MaxMessageBatchingSize attribute on the Messaging element");
}
//--
if (isSiloConfig)
{
if (child.HasAttribute("MaxForwardCount"))
{
MaxForwardCount = ConfigUtilities.ParseInt(child.GetAttribute("MaxForwardCount"),
"Invalid integer value for the MaxForwardCount attribute on the Messaging element");
}
}
if (child.HasChildNodes)
{
var serializerNode = child.ChildNodes.Cast<XmlElement>().FirstOrDefault(n => n.Name == "SerializationProviders");
if (serializerNode != null && serializerNode.HasChildNodes)
{
var typeNames = serializerNode.ChildNodes.Cast<XmlElement>()
.Where(n => n.Name == "Provider")
.Select(e => e.Attributes["type"])
.Where(a => a != null)
.Select(a => a.Value);
var types = typeNames.Select(t => ConfigUtilities.ParseFullyQualifiedType(t, "The type specification for the 'type' attribute of the Provider element could not be loaded"));
foreach (var type in types)
{
var typeinfo = type.GetTypeInfo();
ConfigUtilities.ValidateSerializationProvider(typeinfo);
if (SerializationProviders.Contains(typeinfo) == false)
{
SerializationProviders.Add(typeinfo);
}
}
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using NDesk.Options;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// This module loads and saves OpenSimulator inventory archives
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryArchiverModule")]
public class InventoryArchiverModule : ISharedRegionModule, IInventoryArchiverModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Enable or disable checking whether the iar user is actually logged in
/// </value>
// public bool DisablePresenceChecks { get; set; }
public event InventoryArchiveSaved OnInventoryArchiveSaved;
public event InventoryArchiveLoaded OnInventoryArchiveLoaded;
/// <summary>
/// The file to load and save inventory if no filename has been specified
/// </summary>
protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar";
/// <value>
/// Pending save and load completions initiated from the console
/// </value>
protected List<UUID> m_pendingConsoleTasks = new List<UUID>();
/// <value>
/// All scenes that this module knows about
/// </value>
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
private Scene m_aScene;
private IUserAccountService m_UserAccountService;
protected IUserAccountService UserAccountService
{
get
{
if (m_UserAccountService == null)
// What a strange thing to do...
foreach (Scene s in m_scenes.Values)
{
m_UserAccountService = s.RequestModuleInterface<IUserAccountService>();
break;
}
return m_UserAccountService;
}
}
public InventoryArchiverModule() {}
// public InventoryArchiverModule(bool disablePresenceChecks)
// {
// DisablePresenceChecks = disablePresenceChecks;
// }
#region ISharedRegionModule
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene scene)
{
if (m_scenes.Count == 0)
{
scene.RegisterModuleInterface<IInventoryArchiverModule>(this);
OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted;
OnInventoryArchiveLoaded += LoadInvConsoleCommandCompleted;
scene.AddCommand(
"Archiving", this, "load iar",
"load iar [-m|--merge] <first> <last> <inventory path> <password> [<IAR path>]",
"Load user inventory archive (IAR).",
"-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones"
+ "<first> is user's first name." + Environment.NewLine
+ "<last> is user's last name." + Environment.NewLine
+ "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine
+ "<password> is the user's password." + Environment.NewLine
+ "<IAR path> is the filesystem path or URI from which to load the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME),
HandleLoadInvConsoleCommand);
scene.AddCommand(
"Archiving", this, "save iar",
"save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]",
"Save user inventory archive (IAR).",
"<first> is the user's first name.\n"
+ "<last> is the user's last name.\n"
+ "<inventory path> is the path inside the user's inventory for the folder/item to be saved.\n"
+ "<IAR path> is the filesystem path at which to save the IAR."
+ string.Format(" If this is not given then the filename {0} in the current directory is used.\n", DEFAULT_INV_BACKUP_FILENAME)
+ "-h|--home=<url> adds the url of the profile service to the saved user information.\n"
+ "-c|--creators preserves information about foreign creators.\n"
+ "-e|--exclude=<name/uuid> don't save the inventory item in archive" + Environment.NewLine
+ "-f|--excludefolder=<folder/uuid> don't save contents of the folder in archive" + Environment.NewLine
+ "-v|--verbose extra debug messages.\n"
+ "--noassets stops assets being saved to the IAR."
+ "--perm=<permissions> stops items with insufficient permissions from being saved to the IAR.\n"
+ " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer, \"M\" = Modify.\n",
HandleSaveInvConsoleCommand);
m_aScene = scene;
}
m_scenes[scene.RegionInfo.RegionID] = scene;
}
public void RemoveRegion(Scene scene)
{
}
public void Close() {}
public void RegionLoaded(Scene scene)
{
}
public void PostInitialise()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name { get { return "Inventory Archiver Module"; } }
#endregion
/// <summary>
/// Trigger the inventory archive saved event.
/// </summary>
protected internal void TriggerInventoryArchiveSaved(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException, int SaveCount, int FilterCount)
{
InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
if (handlerInventoryArchiveSaved != null)
handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException, SaveCount , FilterCount);
}
/// <summary>
/// Trigger the inventory archive loaded event.
/// </summary>
protected internal void TriggerInventoryArchiveLoaded(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream,
Exception reportedException, int LoadCount)
{
InventoryArchiveLoaded handlerInventoryArchiveLoaded = OnInventoryArchiveLoaded;
if (handlerInventoryArchiveLoaded != null)
handlerInventoryArchiveLoaded(id, succeeded, userInfo, invPath, loadStream, reportedException, LoadCount);
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
{
return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>());
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream saveStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
InventoryArchiveWriteRequest iarReq = new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream);
iarReq.Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool ArchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, string savePath,
Dictionary<string, object> options)
{
// if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, savePath))
// return false;
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
try
{
InventoryArchiveWriteRequest iarReq = new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath);
iarReq.Execute(options, UserAccountService);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
public bool DearchiveInventory(UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream)
{
return DearchiveInventory(id, firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>());
}
public bool DearchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, Stream loadStream,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadStream, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
else
m_log.ErrorFormat("[INVENTORY ARCHIVER]: User {0} {1} not found",
firstName, lastName);
}
return false;
}
public bool DearchiveInventory(
UUID id, string firstName, string lastName, string invPath, string pass, string loadPath,
Dictionary<string, object> options)
{
if (m_scenes.Count > 0)
{
UserAccount userInfo = GetUserInfo(firstName, lastName, pass);
if (userInfo != null)
{
// if (CheckPresence(userInfo.PrincipalID))
// {
InventoryArchiveReadRequest request;
bool merge = (options.ContainsKey("merge") ? (bool)options["merge"] : false);
try
{
request = new InventoryArchiveReadRequest(id, this, m_aScene.InventoryService, m_aScene.AssetService, m_aScene.UserAccountService, userInfo, invPath, loadPath, merge);
}
catch (EntryPointNotFoundException e)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
+ "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
m_log.Error(e);
return false;
}
UpdateClientWithLoadedNodes(userInfo, request.Execute());
return true;
// }
// else
// {
// m_log.ErrorFormat(
// "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
// userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
// }
}
}
return false;
}
/// <summary>
/// Load inventory from an inventory file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
{
try
{
UUID id = UUID.Random();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; });
List<string> mainParams = optionSet.Parse(cmdparams);
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] <first name> <last name> <inventory path> <user password> [<load file path>]");
return;
}
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
loadPath, invPath, firstName, lastName);
lock (m_pendingConsoleTasks)
m_pendingConsoleTasks.Add(id);
DearchiveInventory(id, firstName, lastName, invPath, pass, loadPath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
/// <summary>
/// Save inventory to a file archive
/// </summary>
/// <param name="cmdparams"></param>
protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
{
UUID id = UUID.Random();
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet ops = new OptionSet();
//ops.Add("v|version=", delegate(string v) { options["version"] = v; });
ops.Add("h|home=", delegate(string v) { options["home"] = v; });
ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; });
ops.Add("c|creators", delegate(string v) { options["creators"] = v; });
ops.Add("noassets", delegate(string v) { options["noassets"] = v != null; });
ops.Add("e|exclude=", delegate(string v)
{
if (!options.ContainsKey("exclude"))
options["exclude"] = new List<String>();
((List<String>)options["exclude"]).Add(v);
});
ops.Add("f|excludefolder=", delegate(string v)
{
if (!options.ContainsKey("excludefolders"))
options["excludefolders"] = new List<String>();
((List<String>)options["excludefolders"]).Add(v);
});
ops.Add("perm=", delegate(string v) { options["checkPermissions"] = v; });
List<string> mainParams = ops.Parse(cmdparams);
try
{
if (mainParams.Count < 6)
{
m_log.Error(
"[INVENTORY ARCHIVER]: save iar [-h|--home=<url>] [--noassets] <first> <last> <inventory path> <password> [<IAR path>] [-c|--creators] [-e|--exclude=<name/uuid>] [-f|--excludefolder=<foldername/uuid>] [-v|--verbose]");
return;
}
if (options.ContainsKey("home"))
m_log.WarnFormat("[INVENTORY ARCHIVER]: Please be aware that inventory archives with creator information are not compatible with OpenSim 0.7.0.2 and earlier. Do not use the -home option if you want to produce a compatible IAR");
string firstName = mainParams[2];
string lastName = mainParams[3];
string invPath = mainParams[4];
string pass = mainParams[5];
string savePath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
savePath, invPath, firstName, lastName);
lock (m_pendingConsoleTasks)
m_pendingConsoleTasks.Add(id);
ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, options);
}
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
private void SaveInvConsoleCommandCompleted(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException, int SaveCount, int FilterCount)
{
lock (m_pendingConsoleTasks)
{
if (m_pendingConsoleTasks.Contains(id))
m_pendingConsoleTasks.Remove(id);
else
return;
}
if (succeeded)
{
// Report success and include item count and filter count (Skipped items due to --perm or --exclude switches)
if(FilterCount == 0)
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}", SaveCount, userInfo.FirstName, userInfo.LastName);
else
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive with {0} items for {1} {2}. Skipped {3} items due to exclude and/or perm switches", SaveCount, userInfo.FirstName, userInfo.LastName, FilterCount);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
private void LoadInvConsoleCommandCompleted(
UUID id, bool succeeded, UserAccount userInfo, string invPath, Stream loadStream,
Exception reportedException, int LoadCount)
{
lock (m_pendingConsoleTasks)
{
if (m_pendingConsoleTasks.Contains(id))
m_pendingConsoleTasks.Remove(id);
else
return;
}
if (succeeded)
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Loaded {0} items from archive {1} for {2} {3}", LoadCount, invPath, userInfo.FirstName, userInfo.LastName);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Archive load for {0} {1} failed - {2}",
userInfo.FirstName, userInfo.LastName, reportedException.Message);
}
}
/// <summary>
/// Get user information for the given name.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="pass">User password</param>
/// <returns></returns>
protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
{
UserAccount account
= m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
if (null == account)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
firstName, lastName);
return null;
}
try
{
string encpass = Util.Md5Hash(pass);
if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty)
{
return account;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e);
return null;
}
}
/// <summary>
/// Notify the client of loaded nodes if they are logged in
/// </summary>
/// <param name="loadedNodes">Can be empty. In which case, nothing happens</param>
private void UpdateClientWithLoadedNodes(UserAccount userInfo, Dictionary<UUID, InventoryNodeBase> loadedNodes)
{
if (loadedNodes.Count == 0)
return;
foreach (Scene scene in m_scenes.Values)
{
ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID);
if (user != null && !user.IsChildAgent)
{
foreach (InventoryNodeBase node in loadedNodes.Values)
{
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
// user.Name, node.Name);
user.ControllingClient.SendBulkUpdateInventory(node);
}
break;
}
}
}
// /// <summary>
// /// Check if the given user is present in any of the scenes.
// /// </summary>
// /// <param name="userId">The user to check</param>
// /// <returns>true if the user is in any of the scenes, false otherwise</returns>
// protected bool CheckPresence(UUID userId)
// {
// if (DisablePresenceChecks)
// return true;
//
// foreach (Scene scene in m_scenes.Values)
// {
// ScenePresence p;
// if ((p = scene.GetScenePresence(userId)) != null)
// {
// p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false);
// return true;
// }
// }
//
// return false;
// }
}
}
| |
//#define FULLBLOCKS
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MineLib.Core.Data.Anvil;
using MineLib.PGL.Extensions;
namespace MineLib.PGL.World
{
public class SectionVBO : IDisposable
{
public Vector3 GlobalPos { get; private set; }
public bool IsFilled { get { return TotalVerticesCount > 0; } }
public BoundingBox BoundingBox { get; private set; }
public IVertexType[] OpaqueVerticesArray { get { return OpaqueVertices.ToArray(); } }
public int OpaqueVerticesCount { get { return OpaqueVertices.Count; } }
private List<IVertexType> OpaqueVertices { get; set; }
public IVertexType[] TransparentVerticesArray { get { return TransparentVertices.ToArray(); } }
public int TransparentVerticesCount { get { return TransparentVertices.Count; } }
private List<IVertexType> TransparentVertices { get; set; }
public int TotalVerticesCount { get { return OpaqueVerticesCount + TransparentVerticesCount; } }
//public ThreadSafeList<int> Indicies;
public SectionVBO(Section section)
{
GlobalPos = section.ChunkPosition.ToXNAVector3() * new Vector3(Section.Width, Section.Height, Section.Depth);
var topFrontRight = GlobalPos + new Vector3(0, 0, 0);
var bottomBackLeft = GlobalPos + new Vector3(16, 16, 16);
BoundingBox = new BoundingBox(topFrontRight, bottomBackLeft);
OpaqueVertices = new List<IVertexType>();
TransparentVertices = new List<IVertexType>();
//Indicies = new ThreadSafeList<int>();
/*
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var block = section.Blocks[x, y, z];
if (block.IsAir)
continue;
var pos = section.GetGlobalPositionByArrayIndex(x, y, z).ToXNAVector3();
OpaqueVertices.AddRange(BlockVBO.CubeFull(new BlockRenderInfo(pos, new Block(block.ID, block.Meta, 15, 15))));
}
*/
BuildInside(section);
}
public SectionVBO(Section center, Section front, Section back, Section left, Section right, Section top, Section bottom) : this(center)
{
///*
if (front != null && front.IsFilled)
BuildFrontBorders(center, front);
if (back != null && back.IsFilled)
BuildBackBorders(center, back);
if (left != null && left.IsFilled)
BuildLeftBorders(center, left);
if (right != null && right.IsFilled)
BuildRightBorders(center, right);
if (top != null && top.IsFilled)
BuildTopBorders(center, top);
if (bottom != null && bottom.IsFilled)
BuildBottomBorders(center, bottom);
//*/
//OpaqueVerticesCount = OpaqueVertices.Count;
//TotalVerticesCount = OpaqueVertices.Count + TransparentVertices.Count;
}
#region Build
#if FULLBLOCKS
private void AddCubeSide(Vector3 pos, Block block, bool isTranspared)
{
if (isTranspared)
{
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.NegativeX, block)));
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.NegativeY, block)));
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.NegativeZ, block)));
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.PositiveX, block)));
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.PositiveY, block)));
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.PositiveZ, block)));
}
else
{
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.NegativeX, block)));
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.NegativeY, block)));
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.NegativeZ, block)));
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.PositiveX, block)));
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.PositiveY, block)));
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, BlockFace.PositiveZ, block)));
}
}
private void BuildInside(Section section)
{
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var block = section.Blocks[x, y, z];
if (block.IsAir) continue;
var pos = section.GetGlobalPositionByArrayIndex(x, y, z).ToXNAVector3();
if (x > 0)
{
var tempBlock = section.Blocks[x - 1, y, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (x < Section.Width - 1)
{
var tempBlock = section.Blocks[x + 1, y, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (y > 0)
{
var tempBlock = section.Blocks[x, y - 1, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (y < Section.Height - 1)
{
var tempBlock = section.Blocks[x, y + 1, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (z > 0)
{
var tempBlock = section.Blocks[x, y, z - 1];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (z < Section.Depth - 1)
{
var tempBlock = section.Blocks[x, y, z + 1];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
}
}
private void BuildFrontBorders(Section front, Section back)
{
var pos1 = front.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
{
var newSecBlock = back.Blocks[x, y, 0];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid) // IsOpaque
continue;
var oldSecBlock = front.Blocks[x, y, Section.Depth - 1];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, y, Section.Depth - 1);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildBackBorders(Section back, Section front)
{
var pos1 = back.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
{
var newSecBlock = front.Blocks[x, y, Section.Depth - 1];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = back.Blocks[x, y, 0];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, y, 0);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildRightBorders(Section left, Section right)
{
var pos1 = right.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = left.Blocks[0, y, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = right.Blocks[Section.Width - 1, y, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(Section.Width - 1, y, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildLeftBorders(Section right, Section left)
{
var pos1 = left.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = right.Blocks[Section.Width - 1, y, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = left.Blocks[0, y, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(0, y, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildTopBorders(Section top, Section bottom)
{
var pos1 = bottom.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = top.Blocks[x, 0, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = bottom.Blocks[x, Section.Height - 1, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, Section.Height - 1, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildBottomBorders(Section bottom, Section top)
{
var pos1 = top.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = bottom.Blocks[x, Section.Height - 1, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = top.Blocks[x, 0, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, 0, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, block, block.IsTransparent || block.IsFluid);
}
}
#else
private void AddCubeSide1(Vector3 pos, BlockFace face, Block block, bool isTranspared)
{
//if (isTranspared)
//{
// var v = BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, face, block), Indicies.Count, out i);
// TransparentVertices.AddRange(v);
// Indicies.AddRange(i);
//}
//else
//{
// int[] i;
// var v = BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, face, block), Indicies.Count, out i);
// OpaqueVertices.AddRange(v);
// Indicies.AddRange(i);
//}
}
private void AddCubeSide(Vector3 pos, BlockFace face, Block block, bool isTranspared)
{
if (isTranspared)
TransparentVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, face, block)));
else
OpaqueVertices.AddRange(BlockVBO.CreateQuadSideTriagled(new BlockRenderInfo(pos, face, block)));
}
private static bool Check(Block block, Block tempBlock)
{
if (tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) // render only near air blocks
if (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) // if block have light or non-light block enabled
if (!block.IsFluid || !tempBlock.IsFluid) // render only liqiuds surface
return true;
return false;
}
private static bool CheckN(Block newSecBlock, Block block)
{
if (newSecBlock.IsAir || newSecBlock.IsTransparent || newSecBlock.IsFluid)
if (block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight)
if (!newSecBlock.IsFluid || !block.IsFluid)
return true;
return false;
}
private void BuildInside(Section section)
{
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var block = section.Blocks[x, y, z];
if (block.IsAir) continue;
var pos = section.GetGlobalPositionByArrayIndex(x, y, z).ToXNAVector3();
if (x > 0)
{
var tempBlock = section.Blocks[x - 1, y, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, BlockFace.PositiveX, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (x < Section.Width - 1)
{
var tempBlock = section.Blocks[x + 1, y, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, BlockFace.NegativeX, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (y > 0)
{
var tempBlock = section.Blocks[x, y - 1, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, BlockFace.PositiveY, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (y < Section.Height - 1)
{
var tempBlock = section.Blocks[x, y + 1, z];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, BlockFace.NegativeY, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (z > 0)
{
var tempBlock = section.Blocks[x, y, z - 1];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, BlockFace.PositiveZ, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
if (z < Section.Depth - 1)
{
var tempBlock = section.Blocks[x, y, z + 1];
if ((tempBlock.IsAir || tempBlock.IsTransparent || tempBlock.IsFluid) && (tempBlock.SkyLight != 0 || tempBlock.Light != 0 || BlockVBO.BuildWithLight) && (!block.IsFluid || !tempBlock.IsFluid))
AddCubeSide(pos, BlockFace.NegativeZ, new Block(block.ID, block.Meta, tempBlock.Light, tempBlock.SkyLight), block.IsTransparent || block.IsFluid);
}
}
}
private void BuildFrontBorders(Section front, Section back)
{
var pos1 = front.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
{
var newSecBlock = back.Blocks[x, y, 0];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid) // IsOpaque
continue;
var oldSecBlock = front.Blocks[x, y, Section.Depth - 1];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, y, Section.Depth - 1);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, BlockFace.NegativeZ, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildBackBorders(Section back, Section front)
{
var pos1 = back.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int y = 0; y < Section.Height; y++)
{
var newSecBlock = front.Blocks[x, y, Section.Depth - 1];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = back.Blocks[x, y, 0];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, y, 0);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, BlockFace.PositiveZ, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildRightBorders(Section left, Section right)
{
var pos1 = right.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = left.Blocks[0, y, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = right.Blocks[Section.Width - 1, y, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(Section.Width - 1, y, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, BlockFace.NegativeX, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildLeftBorders(Section right, Section left)
{
var pos1 = left.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int y = 0; y < Section.Height; y++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = right.Blocks[Section.Width - 1, y, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = left.Blocks[0, y, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(0, y, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, BlockFace.PositiveX, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildTopBorders(Section top, Section bottom)
{
var pos1 = bottom.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = top.Blocks[x, 0, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = bottom.Blocks[x, Section.Height - 1, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, Section.Height - 1, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, BlockFace.NegativeY, block, block.IsTransparent || block.IsFluid);
}
}
private void BuildBottomBorders(Section bottom, Section top)
{
var pos1 = top.GetGlobalPositionByArrayIndex(0, 0, 0).ToXNAVector3();
for (int x = 0; x < Section.Width; x++)
for (int z = 0; z < Section.Depth; z++)
{
var newSecBlock = bottom.Blocks[x, Section.Height - 1, z];
if (!newSecBlock.IsAir && !newSecBlock.IsTransparent && !newSecBlock.IsFluid)
continue;
var oldSecBlock = top.Blocks[x, 0, z];
if (oldSecBlock.IsAir)
continue;
var pos = pos1 + new Vector3(x, 0, z);
var block = new Block(oldSecBlock.ID, oldSecBlock.Meta, newSecBlock.Light, newSecBlock.SkyLight);
if ((block.SkyLight != 0 || block.Light != 0 || BlockVBO.BuildWithLight) && (!newSecBlock.IsFluid || !block.IsFluid))
AddCubeSide(pos, BlockFace.PositiveY, block, block.IsTransparent || block.IsFluid);
}
}
#endif
#endregion Build
public void ClearVerticies()
{
if (OpaqueVertices != null)
{
OpaqueVertices.Clear();
OpaqueVertices = null;
OpaqueVertices = new List<IVertexType>();
}
if (TransparentVertices != null)
{
TransparentVertices.Clear();
TransparentVertices = null;
TransparentVertices = new List<IVertexType>();
}
//OpaqueVertices = new List<VertexPositionTextureLight>();
//TransparentVertices = new List<VertexPositionTextureLight>();
}
public void Dispose()
{
if(OpaqueVertices != null)
OpaqueVertices.Clear();
if (TransparentVertices != null)
TransparentVertices.Clear();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TrueCraft.API
{
/// <summary>
/// Enumerates the different types of containment between two bounding boxes.
/// </summary>
public enum ContainmentType
{
/// <summary>
/// The two bounding boxes are disjoint.
/// </summary>
Disjoint,
/// <summary>
/// One bounding box contains the other.
/// </summary>
Contains,
/// <summary>
/// The two bounding boxes intersect.
/// </summary>
Intersects
}
/// <summary>
/// Represents an axis-aligned bounding box.
/// </summary>
// Mostly taken from the MonoXna project, which is licensed under the MIT license
public struct BoundingBox : IEquatable<BoundingBox>
{
#region Public Fields
/// <summary>
/// The minimum vector for the bounding box.
/// </summary>
public Vector3 Min;
/// <summary>
/// The maximum vector for the bounding box.
/// </summary>
public Vector3 Max;
/// <summary>
/// The number of corners a bounding box has.
/// </summary>
public const int CornerCount = 8;
#endregion Public Fields
#region Public Constructors
/// <summary>
/// Creates a new bounding box from specified values
/// </summary>
/// <param name="min">The minimum vector for the bounding box.</param>
/// <param name="max">The number of corners a bounding box has.</param>
public BoundingBox(Vector3 min, Vector3 max)
{
this.Min = min;
this.Max = max;
}
/// <summary>
/// Creates a new bounding box by copying another.
/// </summary>
/// <param name="b">The bounding box to clone.</param>
public BoundingBox(BoundingBox b)
{
this.Min = new Vector3(b.Min);
this.Max = new Vector3(b.Max);
}
#endregion Public Constructors
#region Public Methods
/// <summary>
/// Determines the type of containment between this and another bounding box.
/// </summary>
/// <param name="box">The other bounding box.</param>
/// <returns></returns>
public ContainmentType Contains(BoundingBox box)
{
//test if all corner is in the same side of a face by just checking min and max
if (box.Max.X < Min.X
|| box.Min.X > Max.X
|| box.Max.Y < Min.Y
|| box.Min.Y > Max.Y
|| box.Max.Z < Min.Z
|| box.Min.Z > Max.Z)
return ContainmentType.Disjoint;
if (box.Min.X >= Min.X
&& box.Max.X <= Max.X
&& box.Min.Y >= Min.Y
&& box.Max.Y <= Max.Y
&& box.Min.Z >= Min.Z
&& box.Max.Z <= Max.Z)
return ContainmentType.Contains;
return ContainmentType.Intersects;
}
/// <summary>
/// Determines whether the specified vector is contained within this bounding box.
/// </summary>
/// <param name="vec">The vector.</param>
/// <returns></returns>
public bool Contains(Vector3 vec)
{
return Min.X <= vec.X && vec.X <= Max.X &&
Min.Y <= vec.Y && vec.Y <= Max.Y &&
Min.Z <= vec.Z && vec.Z <= Max.Z;
}
/// <summary>
/// Creates and returns a new bounding box from an enumeration of corner points.
/// </summary>
/// <param name="points">The enumeration of corner points.</param>
/// <returns></returns>
public static BoundingBox CreateFromPoints(IEnumerable<Vector3> points)
{
if (points == null)
throw new ArgumentNullException();
bool empty = true;
Vector3 vector2 = new Vector3(float.MaxValue);
Vector3 vector1 = new Vector3(float.MinValue);
foreach (Vector3 vector3 in points)
{
vector2 = Vector3.Min(vector2, vector3);
vector1 = Vector3.Max(vector1, vector3);
empty = false;
}
if (empty)
throw new ArgumentException();
return new BoundingBox(vector2, vector1);
}
/// <summary>
/// Offsets this BoundingBox. Does not modify this object, but returns a new one
/// </summary>
/// <returns>
/// The offset bounding box.
/// </returns>
/// <param name='Offset'>
/// The offset.
/// </param>
public BoundingBox OffsetBy(Vector3 Offset)
{
return new BoundingBox(Min + Offset, Max + Offset);
}
/// <summary>
/// Returns an array of vectors containing the corners of this bounding box.
/// </summary>
/// <returns></returns>
public Vector3[] GetCorners()
{
return new Vector3[]
{
new Vector3(this.Min.X, this.Max.Y, this.Max.Z),
new Vector3(this.Max.X, this.Max.Y, this.Max.Z),
new Vector3(this.Max.X, this.Min.Y, this.Max.Z),
new Vector3(this.Min.X, this.Min.Y, this.Max.Z),
new Vector3(this.Min.X, this.Max.Y, this.Min.Z),
new Vector3(this.Max.X, this.Max.Y, this.Min.Z),
new Vector3(this.Max.X, this.Min.Y, this.Min.Z),
new Vector3(this.Min.X, this.Min.Y, this.Min.Z)
};
}
/// <summary>
/// Determines whether this and another bounding box are equal.
/// </summary>
/// <param name="other">The other bounding box.</param>
/// <returns></returns>
public bool Equals(BoundingBox other)
{
return (this.Min == other.Min) && (this.Max == other.Max);
}
/// <summary>
/// Determines whether this and another object are equal.
/// </summary>
/// <param name="obj">The other object.</param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (obj is BoundingBox) && this.Equals((BoundingBox)obj);
}
/// <summary>
/// Returns the hash code for this bounding box.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return this.Min.GetHashCode() + this.Max.GetHashCode();
}
/// <summary>
/// Determines whether this bounding box intersects another.
/// </summary>
/// <param name="box">The other bounding box.</param>
/// <returns></returns>
public bool Intersects(BoundingBox box)
{
bool result;
Intersects(ref box, out result);
return result;
}
/// <summary>
/// Determines whether this bounding box intersects another.
/// </summary>
/// <param name="box">The other bounding box.</param>
/// <param name="result">Set to whether the two bounding boxes intersect.</param>
public void Intersects(ref BoundingBox box, out bool result)
{
if ((this.Max.X > box.Min.X) && (this.Min.X < box.Max.X))
{
if ((this.Max.Y < box.Min.Y) || (this.Min.Y > box.Max.Y))
{
result = false;
return;
}
result = (this.Max.Z > box.Min.Z) && (this.Min.Z < box.Max.Z);
return;
}
result = false;
}
public static bool operator ==(BoundingBox a, BoundingBox b)
{
return a.Equals(b);
}
public static bool operator !=(BoundingBox a, BoundingBox b)
{
return !a.Equals(b);
}
/// <summary>
/// Returns a string representation of this bounding box.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{{Min:{0} Max:{1}}}", this.Min.ToString(), this.Max.ToString());
}
#endregion
/// <summary>
/// Gets the height of this bounding box.
/// </summary>
public double Height
{
get { return Max.Y - Min.Y; }
}
/// <summary>
/// Gets the width of this bounding box.
/// </summary>
public double Width
{
get { return Max.X - Min.X; }
}
/// <summary>
/// Gets the depth of this bounding box.
/// </summary>
public double Depth
{
get { return Max.Z - Min.Z; }
}
/// <summary>
/// Gets the center of this bounding box.
/// </summary>
public Vector3 Center
{
get
{
return (this.Min + this.Max) / 2;
}
}
public double Volume
{
get
{
return Width * Height * Depth;
}
}
}
}
| |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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.Collections;
using System.Data;
//this class is used at the WebServices Test Harness
namespace GHTUtils
{
public class ValueGen
{
private const int ARRAY_SIZE = 7;
public static object GHTTypeGenerator( Type t )
{
object result = null;
if ( t.Name == "XmlNode" || t.Name == "XmlElement" || t.Name == "DataSet" || t.Name == "DataTable" )
{
result = GetRandomValue( t );
return result;
}
//====================================================================================
// Primitive
//====================================================================================
else if ( isPrimitive( t ) )
{
result = GetRandomValue( t );
return result;
}
//====================================================================================
// Array
//====================================================================================
else if (typeof(Array).IsAssignableFrom(t) )
//The Array class returns false because it is not an array.
//To check for an array, use code such as typeof(Array).IsAssignableFrom(type).
{
result = GenerateArray(t);
return result;
}
//====================================================================================
// Collection
//====================================================================================
else if ( isCollection( t ) )
{
result = GenerateCollection(t);
return result;
}
//====================================================================================
// User Defined Type
//====================================================================================
else
{
result = Activator_CreateInstance( t );
result = Generate ( result );
}
return result;
}
public static object GHTObjModifier( object obj )
{
if ( isPrimitive( obj.GetType() ) )
{
return GetModifiedValue( obj );
}
else if ( obj.GetType().IsArray )
{
Type ElementType;
//get the type of the elements in the array.
//work around of GH behavior for array of enums : will give type enum (Array)obj).GetValue(0).GetType()
// : will give type Int32 obj.GetType().GetElementType()
if ( ((Array)obj).Length > 0)
ElementType = ((Array)obj).GetValue(0).GetType();
else
ElementType = obj.GetType().GetElementType();
if ( isPrimitive(ElementType) )
{
Array arr = (Array)obj;
for (int i=0; i < arr.Length; i++)
{
arr.SetValue(GetModifiedValue( arr.GetValue( i ) ), i );
}
return arr;
}
else
{
Array arr = (Array)obj;
for ( int i=0; i < arr.Length; i++ )
{
object new_obj = arr.GetValue( i );
new_obj = GHTObjModifier( new_obj );
arr.SetValue( new_obj, i );
}
return arr;
}
}
else if ( obj.GetType().IsEnum )
{
Array a = Enum.GetValues(obj.GetType());
if (a.Length >= 2)
return a.GetValue(a.Length-2);
else
return a.GetValue(a.Length-1); //leave the same value
}
else if (obj.GetType().Name == "DataTable")
{
ModifyDataTable((System.Data.DataTable)obj);
return obj;
}
else if (obj.GetType().Name == "DataSet")
{
ModifyDataSet((System.Data.DataSet)obj);
return obj;
}
else if (obj.GetType().Name == "XmlNode" || obj.GetType().Name == "XmlElement")
{
ModifyXmlElement((System.Xml.XmlElement)obj);
return obj;
}
else if (isCollection(obj.GetType()))
{
ModifyCollection(obj);
return obj;
}
else
{
object result = obj;
Modify( result );
return result;
}
}
static object GetRandomValue(Type t)
{
object objOut = null;
string str = null;
System.Threading.Thread.Sleep(10);
System.Random rnd = new System.Random(unchecked((int)DateTime.Now.Ticks));
if (t.FullName == "System.Boolean")
{
objOut = System.Convert.ToBoolean(rnd.Next(0, 1));
return objOut;
}
else if (t.FullName == "System.Byte")
{
objOut = System.Convert.ToByte(rnd.Next(System.Byte.MinValue+1, System.Byte.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.Char")
{
objOut = System.Convert.ToChar(rnd.Next(System.Char.MinValue+65, System.Char.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.DateTime")
{
//GH precision is only milliseconds
objOut = System.Convert.ToDateTime(new System.DateTime(632083133257660000));
return objOut;
}
else if (t.FullName == "System.Decimal")
{
objOut = System.Convert.ToDecimal(rnd.Next(System.Int16.MinValue+1, System.Int16.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.Double")
{
//give max length of "MaxLength" digits
int MaxLength = 2;
str = rnd.NextDouble().ToString();
if (str.Length > MaxLength) str = str.Remove(MaxLength+1,str.Length-(MaxLength+1));
objOut = System.Convert.ToDouble(str);
return objOut;
}
else if (t.FullName == "System.Int16")
{
objOut = System.Convert.ToInt16(rnd.Next(System.Int16.MinValue+1,System.Int16.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.Int32")
{
objOut = System.Convert.ToInt32(rnd.Next(System.Int16.MinValue+1,System.Int16.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.Int64")
{
objOut = System.Convert.ToInt64(rnd.Next(System.Int16.MinValue+1,System.Int16.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.SByte")
{
objOut = System.Convert.ToSByte(rnd.Next(System.SByte.MinValue+1,System.SByte.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.Single")
{
objOut = System.Convert.ToSingle(rnd.Next(System.Int16.MinValue+1, System.Int16.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.String")
{
long size = DateTime.Now.Ticks;
size = size % 99;
if (size==0) size = 16;
for (int i=0; i<size ;i++)
{
str += System.Convert.ToChar(rnd.Next(System.Byte.MinValue+65, System.Byte.MaxValue-128));
}
objOut = str;
return objOut;
}
else if (t.FullName == "System.UInt16")
{
objOut = System.Convert.ToUInt16(rnd.Next(System.UInt16.MinValue+1,System.UInt16.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.UInt32")
{
objOut = System.Convert.ToUInt32(rnd.Next((int)System.UInt32.MinValue+1,System.Int32.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.UInt64")
{
objOut = System.Convert.ToUInt64(rnd.Next((int)System.UInt64.MinValue+1,System.Int32.MaxValue-128));
return objOut;
}
else if (t.FullName == "System.Data.DataTable")
{
objOut = GenerateDataTable();
return objOut;
}
else if (t.FullName == "System.Data.DataSet")
{
objOut = GenerateDataSet();
return objOut;
}
else if (t.FullName == "System.Xml.XmlNode" || t.FullName == "System.Xml.XmlElement")
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
objOut = xmlDoc.CreateElement("myElement");
((System.Xml.XmlElement)objOut).InnerText = "1234";
// ((System.Xml.XmlElement)objOut).InnerXml = "<books>" +
// "<book>" +
// "<author>Carson</author>" +
// "<price format=\"dollar\">31.95</price>" +
// "<pubdate>05/01/2001</pubdate>" +
// "</book>" +
// "<pubinfo>" +
// "<publisher>MSPress</publisher>" +
// "<state>WA</state>" +
// "</pubinfo>" +
// "</books>";
return objOut;
}
else
{
throw new System.NotImplementedException("GetRandomValue error: Type " + t.Name + " not implemented.");
}
}
static object GetModifiedValue(object objIn)
{
object objOut = null;
if (objIn.GetType().FullName == "System.Boolean")
{
bool BoolVar =!(bool)objIn;
return BoolVar ;
}
else if (objIn.GetType().FullName == "System.Byte")
{
if ((byte)objIn == byte.MaxValue)
return (byte)1;
else
return System.Convert.ToByte((byte)objIn + (byte)1);
}
else if (objIn.GetType().FullName == "System.Char")
{
if ((char)objIn == char.MaxValue)
return (char)1;
else
return System.Convert.ToChar((char)objIn + (char)1);
}
else if (objIn.GetType().FullName == "System.DateTime")
{
objOut = System.Convert.ToDateTime(objIn);
objOut = ((DateTime)objOut).AddHours(1);
return objOut;
}
else if (objIn.GetType().FullName == "System.Decimal")
{
if ((decimal)objIn == decimal.MaxValue)
objOut = (decimal)1;
else
objOut = System.Convert.ToDecimal(System.Convert.ToDecimal(objIn) + (decimal)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.Double")
{
if ((double)objIn == double.MaxValue)
objOut = (double)1;
else
objOut = System.Convert.ToDouble(System.Convert.ToDouble(objIn) + (double)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.Int16")
{
if ((Int16)objIn == Int16.MaxValue)
objOut = (Int16)1;
else
objOut = System.Convert.ToInt16(System.Convert.ToInt16(objIn) + (Int16)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.Int32")
{
if ((Int32)objIn == Int32.MaxValue)
objOut = (Int32)1;
else
objOut = System.Convert.ToInt32(System.Convert.ToInt32(objIn) + (Int32)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.Int64")
{
if ((Int64)objIn == Int64.MaxValue)
objOut = (Int64)1;
else
objOut = System.Convert.ToInt64(System.Convert.ToInt64(objIn) + (Int64)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.SByte")
{
if ((SByte)objIn == SByte.MaxValue)
objOut = (SByte)1;
else
objOut = System.Convert.ToSByte(System.Convert.ToSByte(objIn) + (SByte)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.Single")
{
if ((Single)objIn == Single.MaxValue)
objOut = (Single)1;
else
objOut = System.Convert.ToSingle(System.Convert.ToSingle(objIn) + (Single)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.String")
{
string strin;
strin = System.Convert.ToString(System.Convert.ToString(objIn));
objOut = System.Convert.ToString("");
for (int ii=0; ii < strin.Length; ii++)
if ( strin[ii] > 'Z' )
objOut += strin[ii].ToString().ToUpper();
else
objOut += strin[ii].ToString().ToLower();
return objOut;
}
else if (objIn.GetType().FullName == "System.UInt16")
{
if ((UInt16)objIn == UInt16.MaxValue)
objOut = (UInt16)1;
else
objOut = System.Convert.ToUInt16(System.Convert.ToUInt16(objIn) + (UInt16)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.UInt32")
{
if ((UInt32)objIn == UInt32.MaxValue)
objOut = (UInt32)1;
else
objOut = System.Convert.ToUInt32(System.Convert.ToUInt32(objIn) + (UInt32)1);
return objOut;
}
else if (objIn.GetType().FullName == "System.UInt64")
{
if ((UInt64)objIn == UInt64.MaxValue)
objOut = (UInt64)1;
else
objOut = System.Convert.ToUInt64(System.Convert.ToUInt64(objIn) + (UInt64)1);
return objOut;
}
else
{
throw new System.NotImplementedException("GetModifiedValue error: Type " + objIn.GetType().FullName + " not implemented.");
}
}
static void Modify( object obj )
{
if ( obj.GetType().IsEnum )
{
Array a = Enum.GetValues(obj.GetType());
if (a.Length >= 2)
obj = a.GetValue(a.Length-2);
else
obj = a.GetValue(a.Length-1); //leave the same value
return;
}
MemberInfo [] mic;
mic = obj.GetType().GetMembers( BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic );
foreach ( MemberInfo mi in mic )
{
// ---------- FieldInfo ----------
if ( mi is FieldInfo )
{
FieldInfo field = (FieldInfo)mi;
Type fieldType = field.FieldType;
if ( fieldType.IsArray )
{
// is array of primitive
if ( isPrimitive( fieldType.GetElementType() ) )
{
Array arr = (Array)field.GetValue( obj );
for (int i=0; i < arr.Length; i++)
{
arr.SetValue(GetModifiedValue( arr.GetValue( i ) ), i );
}
field.SetValue( obj, arr );
}
// is array of user defined type
if ( !isSystem( fieldType ) && !isCollection( fieldType ) )
{
Array arr = (Array)field.GetValue( obj );
for ( int i=0; i < arr.Length; i++ )
{
object new_obj = arr.GetValue( i );
Modify( new_obj );
arr.SetValue( new_obj, i );
}
field.SetValue( obj, arr );
}
}
else
{
if ( isPrimitive( fieldType ) )
{
field.SetValue( obj, GetModifiedValue( field.GetValue( obj ) ) );
}
if ( !isSystem( fieldType ) && !isCollection( fieldType ) )
{
object new_obj = field.GetValue( obj );
Modify(new_obj);
field.SetValue( obj, new_obj );
}
// object
if ( isObject( fieldType ) )
{
object new_obj = field.GetValue( obj );
Modify(new_obj);
field.SetValue( obj, new_obj );
}
}
} // field info
// ---------- PropertyInfo ----------
//
if ( mi is PropertyInfo )
{
PropertyInfo prop = (PropertyInfo)mi;
if ( prop.PropertyType.IsArray )
{
// is array of primitive type member
if ( isPrimitive( prop.PropertyType.GetElementType() ) )
{
Array arr = (Array)prop.GetValue( obj, null );
for (int i=0; i < arr.Length; i++)
{
arr.SetValue(GetModifiedValue( arr.GetValue( i ) ), i );
}
prop.SetValue( obj, arr, null );
}
//is array user defined type
if ( !isSystem( prop.PropertyType ) && !isCollection( prop.PropertyType ) )
{
Array arr = (Array)prop.GetValue( obj, null );
for ( int i=0; i < arr.Length; i++ )
{
object new_obj = arr.GetValue( i );
Modify( new_obj );
arr.SetValue( new_obj, i );
}
prop.SetValue( obj, arr, null );
}
}
else
{
//primitive type
if ( isPrimitive( prop.PropertyType ) )
{
prop.SetValue( obj, GetModifiedValue( prop.GetValue( obj, null ) ), null );
}
//user defined type
if ( !isSystem( prop.PropertyType ) && !isCollection( prop.PropertyType ) )
{
object new_obj = prop.GetValue( obj, null );
Modify(new_obj);
prop.SetValue( obj, new_obj, null );
}
// object
if ( isObject( prop.PropertyType ) )
{
object new_obj = prop.GetValue( obj, null );
Modify(new_obj);
prop.SetValue( obj, new_obj, null );
}
}
} // field info
} // for each
//return obj;
}
static void ModifyDataSet(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
ModifyDataTable(dt);
}
}
static void ModifyDataTable(DataTable dt)
{
foreach(DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
switch (dc.DataType.Name)
{
case "String":
dr[dc] = dr[dc].ToString() + "mod";
break;
case "Int32":
dr[dc] = Convert.ToInt32( dr[dc] ) * 100;
break;
}
}
}
}
static void ModifyXmlElement(System.Xml.XmlElement xmlElem)
{
xmlElem.InnerText = "54321";
// xmlElem.InnerXml = "<books>" +
// "<book>" +
// "<author>Carson</author>" +
// "<price format=\"dollar\">33.99</price>" +
// "<pubdate>01/01/2003</pubdate>" +
// "</book>" +
// "<pubinfo>" +
// "<publisher>MisPress</publisher>" +
// "<state>CA</state>" +
// "</pubinfo>" +
// "</books>";
}
static void ModifyCollection(object co)
{
for (int i=0; i < ((IList)co).Count; i++)
{
object o = ((IList)co)[i];
o = GHTObjModifier(o);
((IList)co)[i] = o;
}
}
static object Generate( object obj )
{
MemberInfo [] mic;
if ( obj == null ) return null;
if (obj.GetType().IsEnum)
{
Array a = Enum.GetValues(obj.GetType());
return a.GetValue(a.Length-1);
}
if ( isObject( obj.GetType() ))
{
//obj = GetRandomValue( typeof( System.String ) );
obj = new object();
return obj;
}
mic = obj.GetType().GetMembers( BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic );
foreach ( MemberInfo mi in mic )
{
// FieldInfo
//
if ( mi is FieldInfo )
{
FieldInfo field = (FieldInfo)mi;
// is array of primitive
//
if ( field.FieldType.IsArray )
{
if ( isPrimitive( field.FieldType.GetElementType() ) )
{
Array arr = Array.CreateInstance( field.FieldType.GetElementType(), ARRAY_SIZE);
for (int i=0; i < arr.Length; i++)
{
arr.SetValue(GetRandomValue( field.FieldType.GetElementType() ), i );
}
field.SetValue( obj, arr );
}
}
else
{
if ( isPrimitive( field.FieldType ) )
{
field.SetValue( obj, GetRandomValue( field.FieldType ) );
}
}
// Collection type member
//
if ( isCollection( field.FieldType ) )
{
object new_obj = Activator_CreateInstance(field.FieldType);
MethodInfo mm = null;
MethodInfo [] mmi = field.FieldType.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
foreach ( MethodInfo m in mmi )
{
if ( m.Name == "Add" )
{
mm = m;
break;
}
}
if ( mm != null )
{
ParameterInfo [] pi = mm.GetParameters();
Type prmType1 = pi[0].ParameterType;
Type prmType2 = null;
if (pi.Length > 1) prmType2 = pi[1].ParameterType;
if ( field.FieldType.GetInterface("IList") != null )
{
for ( int i=0; i < ARRAY_SIZE; i++ )
{
if ( isPrimitive( prmType1 ) )
{
((IList)new_obj).Add( GetRandomValue( prmType1 ) );
}
else
{
object prm_obj = Activator_CreateInstance( prmType1 );
((IList)new_obj).Add( Generate( prm_obj ) );
}
}
field.SetValue( obj, new_obj );
}
if ( prmType2 != null)
{
if ( field.FieldType.GetInterface("IDictionary") != null)
{
for ( int i=0; i < ARRAY_SIZE; i++ )
{
if ( isPrimitive( prmType1 ) && isPrimitive( prmType2 ) )
{
((IDictionary)new_obj).Add( GetRandomValue( prmType1 ), GetRandomValue( prmType2 ) );
}
else
{
object prm_obj1 = Activator_CreateInstance( prmType1 );
object prm_obj2 = Activator_CreateInstance( prmType2 );
((IDictionary)new_obj).Add( Generate( prm_obj1 ), Generate( prm_obj2 ) );
}
}
}
field.SetValue( obj, new_obj );
}
}
} // collection
// is array of user defined type
//
if ( field.FieldType.IsArray )
{
if ( !isCollection( field.FieldType ) )
{
Array arr = Array.CreateInstance( field.FieldType.GetElementType(), ARRAY_SIZE );
for ( int i=0; i < arr.Length; i++ )
{
object new_obj = GHTTypeGenerator( field.FieldType.GetElementType() );
arr.SetValue( new_obj, i );
}
field.SetValue( obj, arr );
}
}
else
{
if ( !isCollection( field.FieldType ) )
{
object new_obj = GHTTypeGenerator( field.FieldType );
field.SetValue( obj, new_obj );
}
} // user defined type
// object
//
if ( isObject( field.FieldType ) )
{
object new_obj = Activator_CreateInstance(field.FieldType);
new_obj = "GH test";
field.SetValue( obj, new_obj );
} // object
} // field info
// PropertyInfo
//
if ( mi is PropertyInfo )
{
PropertyInfo prop = (PropertyInfo)mi;
// is array of primitive type member
//
if ( prop.PropertyType.IsArray )
{
if ( isPrimitive( prop.PropertyType.GetElementType() ) )
{
Array arr = Array.CreateInstance( prop.PropertyType.GetElementType(), ARRAY_SIZE);
for (int i=0; i < arr.Length; i++)
{
arr.SetValue(GetRandomValue( prop.PropertyType.GetElementType() ), i );
}
prop.SetValue( obj, arr, null );
}
}
else
{
if ( isPrimitive( prop.PropertyType ) )
{
prop.SetValue( obj, GetRandomValue( prop.PropertyType ), null );
}
} // primitive
// Colletion type member
//
if ( isCollection( prop.PropertyType ) )
{
object new_obj = Activator_CreateInstance( prop.PropertyType );
MethodInfo mm = null;
MethodInfo [] mmi = prop.PropertyType.GetMethods( BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
foreach ( MethodInfo m in mmi )
{
if ( m.Name == "Add" )
{
mm = m;
break;
}
}
if ( mm != null )
{
ParameterInfo [] pi = mm.GetParameters();
Type prmType1 = pi[0].ParameterType;
Type prmType2 = null;
if (pi.Length > 1) prmType2 = pi[1].ParameterType;
if ( prop.PropertyType.GetInterface("IList") != null )
{
for ( int i=0; i < ARRAY_SIZE; i++ )
{
if ( isPrimitive( prmType1 ) )
{
((IList)new_obj).Add( GetRandomValue( prmType1 ) );
}
else
{
object prm_obj = Activator_CreateInstance( prmType1 );
((IList)new_obj).Add( Generate( prm_obj ) );
}
}
prop.SetValue( obj, new_obj, null );
}
if ( prmType2 != null)
{
if ( prop.PropertyType.GetInterface("IDictionary") != null)
{
for ( int i=0; i < ARRAY_SIZE; i++ )
{
if ( isPrimitive( prmType1 ) && isPrimitive( prmType2 ) )
{
((IDictionary)new_obj).Add( GetRandomValue( prmType1 ), GetRandomValue( prmType2 ) );
}
else
{
object prm_obj1 = Activator_CreateInstance( prmType1 );
object prm_obj2 = Activator_CreateInstance( prmType2 );
((IDictionary)new_obj).Add( Generate( prm_obj1 ), Generate( prm_obj2 ) );
}
}
prop.SetValue( obj, new_obj, null );
}
}
}
} // collection
// is array user defined type
//
if ( prop.PropertyType.IsArray )
{
if ( !isSystem( prop.PropertyType ) && !isCollection( prop.PropertyType ) )
{
Array arr = Array.CreateInstance( prop.PropertyType.GetElementType(), ARRAY_SIZE );
for ( int i=0; i < arr.Length; i++ )
{
object new_obj = Activator_CreateInstance( prop.PropertyType.GetElementType() );
Generate( new_obj );
arr.SetValue( new_obj, i );
}
prop.SetValue( obj, arr, null );
}
}
else
{
if ( !isSystem( prop.PropertyType ) && !isCollection( prop.PropertyType ) )
{
object new_obj = Activator_CreateInstance( prop.PropertyType );
Generate(new_obj);
prop.SetValue( obj, new_obj, null );
}
} // user defined type
// object
//
if ( isObject( prop.PropertyType ) )
{
object new_obj = Activator_CreateInstance( prop.PropertyType );
new_obj = "GH test";
prop.SetValue( obj, new_obj, null );
} // object
} // field info
} // for each
return obj;
}
static DataSet GenerateDataSet()
{
string strTemp = string.Empty;
DataSet ds = new DataSet("CustOrdersDS");
DataTable dtCusts = new DataTable("Customers");
ds.Tables.Add(dtCusts);
DataTable dtOrders = new DataTable("Orders");
ds.Tables.Add(dtOrders);
// add ID column with autoincrement numbering
// and Unique constraint
DataColumn dc = dtCusts.Columns.Add("ID", typeof(Int32));
dc.AllowDBNull = false;
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.Unique = true;
// make the ID column part of the PrimaryKey
// for the table
dtCusts.PrimaryKey = new DataColumn[] {dc};
// add name and company columns with length restrictions
// and default values
dc = dtCusts.Columns.Add("Name", typeof(String));
dc.MaxLength = 255;
dc.DefaultValue = "nobody";
dc = dtCusts.Columns.Add("Company", typeof(String));
dc.MaxLength = 255;
dc.DefaultValue = "nonexistent";
// fill the table
for (int i=0; i < 10; i++)
{
DataRow dr = dtCusts.NewRow();
strTemp = (string)GetRandomValue(typeof(String));
if (strTemp.Length > 255) strTemp = strTemp.Remove(0,254);
dr["Name"] = strTemp;
strTemp = (string)GetRandomValue(typeof(String));
if (strTemp.Length > 255) strTemp = strTemp.Remove(0,254);
dr["Company"] = strTemp;
dtCusts.Rows.Add(dr);
}
// add ID columns with autoincrement numbering
// and Unique constraint
dc = dtOrders.Columns.Add("ID", typeof(Int32));
dc.AllowDBNull = false;
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.Unique = true;
// add custid, date and total columns
dtOrders.Columns.Add("CustID", typeof(Int32));
dtOrders.Columns.Add("Date", typeof(DateTime));
dtOrders.Columns.Add("Total", typeof(Decimal));
for (int i=0; i < 10; i++)
{
DataRow dr = dtOrders.NewRow();
dr["CustID"] = i;
dr["Date"] = GetRandomValue(typeof(DateTime));
dr["Total"] = i * i;
dtOrders.Rows.Add(dr);
}
// make the ID column part of the PrimaryKey
// for the table
dtOrders.PrimaryKey = new DataColumn[] {dc};
return ds;
}
static DataTable GenerateDataTable()
{
DataTable dt = new DataTable("Customers");
string strTemp = string.Empty;
// add ID column with autoincrement numbering
// and Unique constraint
DataColumn dc = dt.Columns.Add("ID", typeof(Int32));
dc.AllowDBNull = false;
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.Unique = true;
// make the ID column part of the PrimaryKey
// for the table
dt.PrimaryKey = new DataColumn[] {dc};
// add name and company columns with length restrictions
//' and default values
dc = dt.Columns.Add("Name", typeof(String));
dc.MaxLength = 255;
dc.DefaultValue = "nobody";
dc = dt.Columns.Add("Company", typeof(String));
dc.MaxLength = 255;
dc.DefaultValue = "nonexistent";
// fill the table
for (int i=0; i < 10; i++)
{
DataRow dr = dt.NewRow();
strTemp = (string)GetRandomValue(typeof(String));
if (strTemp.Length > 255) strTemp = strTemp.Remove(0,254);
dr["Name"] = strTemp;
strTemp = (string)GetRandomValue(typeof(String));
if (strTemp.Length > 255) strTemp = strTemp.Remove(0,254);
dr["Company"] = strTemp;
dt.Rows.Add(dr);
}
return dt;
}
static object GenerateCollection(Type t)
{
object new_obj = Activator_CreateInstance( t );
MethodInfo MI = null;
MethodInfo [] arrMI = t.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
foreach ( MethodInfo m in arrMI )
{
if ( m.Name == "Add" )
{
MI = m;
break;
}
}
if ( MI != null )
{
ParameterInfo [] pi = MI.GetParameters();
Type prmType1 = pi[0].ParameterType;
Type prmType2 = null;
if (pi.Length > 1) prmType2 = pi[1].ParameterType;
if ( t.GetInterface("IList") != null )
{
for ( int i=0; i < ARRAY_SIZE; i++ )
{
if ( isPrimitive( prmType1 ) )
{
((IList)new_obj).Add( GetRandomValue( prmType1 ) );
}
else
{
//object prm_obj = Activator_CreateInstance( prmType1 );
//((IList)new_obj).Add( Generate( prm_obj ) );
((IList)new_obj).Add(GHTTypeGenerator(prmType1));
}
}
return new_obj;
}
if ( prmType2 != null)
{
if ( t.GetInterface("IDictionary") != null)
{
for ( int i=0; i < ARRAY_SIZE; i++ )
{
if ( isPrimitive( prmType1 ) && isPrimitive( prmType2 ) )
{
((IDictionary)new_obj).Add( GetRandomValue( prmType1 ), GetRandomValue( prmType2 ) );
}
else
{
object prm_obj1 = Activator_CreateInstance( prmType1 );
object prm_obj2 = Activator_CreateInstance( prmType2 );
((IDictionary)new_obj).Add( Generate( prm_obj1 ), Generate( prm_obj2 ) );
}
}
}
return new_obj;
}
}// if ( MI != null )
return new_obj;
}
static Array GenerateArray(Type t)
{
if ( isPrimitive( t.GetElementType() ) )
{
Array arr = Array.CreateInstance( t.GetElementType(), ARRAY_SIZE);
for (int i=0; i < arr.Length; i++)
{
arr.SetValue(GetRandomValue( t.GetElementType() ), i );
}
return arr;
}
else
{
Array arr = Array.CreateInstance( t.GetElementType(), ARRAY_SIZE );
for ( int i=0; i < arr.Length; i++ )
{
//object new_obj = Activator_CreateInstance( t.GetElementType() );
//Generate( new_obj );
object new_obj = GHTTypeGenerator(t.GetElementType());
arr.SetValue( new_obj, i );
}
return arr;
}
}
static bool isPrimitive(Type t)
{
if ( t.IsPrimitive ) return true;
if ( t.Name == "String" ) return true;
if ( t.Name == "DateTime" ) return true;
if ( t.Name == "Decimal" ) return true;
return false;
}
static bool isSystem(Type t)
{
if ( t.FullName == "System.Collections" ) return false;
if ( t.FullName.StartsWith("System.") ) return true;
return false;
}
static bool isObject(Type t)
{
if ( t.FullName == "System.Object" ) return true;
return false;
}
static bool isCollection(Type t)
{
if ( t.GetInterface("IList") != null) return true;
if ( t.GetInterface("IDictionary") != null) return true;
if ( t.GetInterface("ICollection") != null) return true;
return false;
}
static object Activator_CreateInstance(Type t)
{
try
{
if (t.IsEnum)
{
Array a = Enum.GetNames(t);
return Enum.Parse(t,a.GetValue(0).ToString());
}
else
return t.GetConstructor(new Type[]{}).Invoke(new object[]{});
}
catch( Exception ex )
{
throw new Exception("Activator - Could not create type " + t.Name + " - " + ex.Message);
}
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_TempatTidur_Edit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["TempatTidurManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>";
btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>";
Draw();
}
}
public void GetListRuang(string RuangId)
{
int kelasId = 0;
if (cmbKelas.SelectedIndex > 0)
kelasId = int.Parse(cmbKelas.SelectedItem.Value);
SIMRS.DataAccess.RS_Ruang myObj = new SIMRS.DataAccess.RS_Ruang();
DataTable dt = myObj.GetListByKelasId(kelasId);
cmbRuang.Items.Clear();
int i = 0;
cmbRuang.Items.Add("");
cmbRuang.Items[i].Text = "";
cmbRuang.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbRuang.Items.Add("");
cmbRuang.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbRuang.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == RuangId)
{
cmbRuang.SelectedIndex = i;
}
i++;
}
}
public void GetListKelas(string KelasId)
{
SIMRS.DataAccess.RS_Kelas myObj = new SIMRS.DataAccess.RS_Kelas();
DataTable dt = myObj.GetList();
cmbKelas.Items.Clear();
int i = 0;
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = "";
cmbKelas.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = dr["Nama"].ToString();
cmbKelas.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelasId)
{
cmbKelas.SelectedIndex = i;
}
i++;
}
}
public void GetListNomorRuang(string NomorRuang)
{
SIMRS.DataAccess.RS_RuangRawat myObj = new SIMRS.DataAccess.RS_RuangRawat();
if (cmbKelas.SelectedIndex > 0)
myObj.KelasId = int.Parse(cmbKelas.SelectedItem.Value);
if (cmbRuang.SelectedIndex > 0)
myObj.RuangId = int.Parse(cmbRuang.SelectedItem.Value);
DataTable dt = myObj.GetListNomorRuang();
cmbNoRuang.Items.Clear();
int i = 0;
cmbNoRuang.Items.Add("");
cmbNoRuang.Items[i].Text = "";
cmbNoRuang.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbNoRuang.Items.Add("");
cmbNoRuang.Items[i].Text = dr["NomorRuang"].ToString();
cmbNoRuang.Items[i].Value = dr["NomorRuang"].ToString();
if (dr["NomorRuang"].ToString() == NomorRuang)
{
cmbNoRuang.SelectedIndex = i;
}
i++;
}
}
public void Draw()
{
try
{
string TempatTidurId = Request.QueryString["TempatTidurId"].ToString();
SIMRS.DataAccess.RS_TempatTidur myObj = new SIMRS.DataAccess.RS_TempatTidur();
myObj.TempatTidurId = Convert.ToInt32(TempatTidurId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtTempatTidurId.Text = row["TempatTidurId"].ToString();
GetListKelas(row["KelasId"].ToString());
GetListRuang(row["RuangId"].ToString());
GetListNomorRuang(row["NomorRuang"].ToString());
txtNomorTempat.Text = row["NomorTempat"].ToString();
txtKeterangan.Text = row["Keterangan"].ToString();
}
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("Backoffice.Referensi.TempatTidur::Edit::Draw::Error occured.", ex);
}
}
/// <summary>
/// This function is responsible for save data into database.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSave(Object sender, EventArgs e)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (!Page.IsValid)
{
return;
}
SIMRS.DataAccess.RS_RuangRawat myRR = new SIMRS.DataAccess.RS_RuangRawat();
if (cmbKelas.SelectedIndex > 0)
myRR.KelasId = int.Parse(cmbKelas.SelectedItem.Value);
if (cmbRuang.SelectedIndex > 0)
myRR.RuangId = int.Parse(cmbRuang.SelectedItem.Value);
if (cmbNoRuang.SelectedIndex > 0)
myRR.NomorRuang = cmbNoRuang.SelectedItem.Value;
SIMRS.DataAccess.RS_TempatTidur myObj = new SIMRS.DataAccess.RS_TempatTidur();
myObj.TempatTidurId = int.Parse(txtTempatTidurId.Text);
myObj.SelectOne();
myObj.RuangRawatId = myRR.GetRuangRawatId();
myObj.Kode = txtNomorTempat.Text;
myObj.NomorTempat = txtNomorTempat.Text;
myObj.Keterangan = txtKeterangan.Text;
myObj.ModifiedBy = UserId;
myObj.ModifiedDate = DateTime.Now;
if (myObj.IsExist())
{
lblError.Text = Resources.GetString("Referensi", "WarExistTempatTidur");
return;
}
else
{
myObj.Update();
HttpRuntime.Cache.Remove("SIMRS_TempatTidur");
string CurrentPage = "";
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
CurrentPage = Request.QueryString["CurrentPage"].ToString();
Response.Redirect("List.aspx?CurrentPage=" + CurrentPage);
}
}
/// <summary>
/// This function is responsible for cancel save data into database.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnCancel(Object sender, EventArgs e)
{
string CurrentPage = "";
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
CurrentPage = Request.QueryString["CurrentPage"].ToString();
Response.Redirect("List.aspx?CurrentPage=" + CurrentPage);
}
protected void cmbKelas_SelectedIndexChanged(object sender, EventArgs e)
{
GetListRuang("");
}
protected void cmbRuang_SelectedIndexChanged(object sender, EventArgs e)
{
GetListNomorRuang("");
}
}
| |
#region License
//
// MethodScanner.cs April 2007
//
// Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
import static SimpleFramework.Xml.DefaultType.PROPERTY;
/// <summary>
/// The <c>MethodScanner</c> object is used to scan an object
/// for matching get and set methods for an XML annotation. This will
/// scan for annotated methods starting with the most specialized
/// class up the class hierarchy. Thus, annotated methods can be
/// overridden in a type specialization.
/// <p>
/// The annotated methods must be either a getter or setter method
/// following the Java Beans naming conventions. This convention is
/// such that a method must begin with "get", "set", or "is". A pair
/// of set and get methods for an annotation must make use of the
/// same type. For instance if the return type for the get method
/// was <c>String</c> then the set method must have a single
/// argument parameter that takes a <c>String</c> type.
/// <p>
/// For a method to be considered there must be both the get and set
/// methods. If either method is missing then the scanner fails with
/// an exception. Also, if an annotation marks a method which does
/// not follow Java Bean naming conventions an exception is thrown.
/// </summary>
class MethodScanner : ContactList {
/// <summary>
/// This is a factory used for creating property method parts.
/// </summary>
private readonly MethodPartFactory factory;
/// <summary>
/// This is used to acquire the hierarchy for the class scanned.
/// </summary>
private readonly Hierarchy hierarchy;
/// <summary>
/// This is the default access type to be used for this scanner.
/// </summary>
private readonly DefaultType access;
/// <summary>
/// This is used to collect all the set methods from the object.
/// </summary>
private readonly PartMap write;
/// <summary>
/// This is used to collect all the get methods from the object.
/// </summary>
private readonly PartMap read;
/// <summary>
/// This is the type of the object that is being scanned.
/// </summary>
private readonly Class type;
/// <summary>
/// Constructor for the <c>MethodScanner</c> object. This is
/// used to create an object that will scan the specified class
/// such that all bean property methods can be paired under the
/// XML annotation specified within the class.
/// </summary>
/// <param name="type">
/// this is the type that is to be scanned for methods
/// </param>
public MethodScanner(Class type) {
this(type, null);
}
/// <summary>
/// Constructor for the <c>MethodScanner</c> object. This is
/// used to create an object that will scan the specified class
/// such that all bean property methods can be paired under the
/// XML annotation specified within the class.
/// </summary>
/// <param name="type">
/// this is the type that is to be scanned for methods
/// </param>
public MethodScanner(Class type, DefaultType access) {
this.factory = new MethodPartFactory();
this.hierarchy = new Hierarchy(type);
this.write = new PartMap();
this.read = new PartMap();
this.access = access;
this.type = type;
this.Scan(type);
}
/// <summary>
/// This method is used to scan the class hierarchy for each class
/// in order to extract methods that contain XML annotations. If
/// a method is annotated it is converted to a contact so that
/// it can be used during serialization and deserialization.
/// </summary>
/// <param name="type">
/// this is the type to be scanned for methods
/// </param>
public void Scan(Class type) {
for(Class next : hierarchy) {
Scan(next, access);
}
for(Class next : hierarchy) {
Scan(next, type);
}
Build();
Validate();
}
/// <summary>
/// This is used to scan the declared methods within the specified
/// class. Each method will be checked to determine if it contains
/// an XML element and can be used as a <c>Contact</c> for
/// an entity within the object.
/// </summary>
/// <param name="real">
/// this is the actual type of the object scanned
/// </param>
/// <param name="type">
/// this is one of the super classes for the object
/// </param>
public void Scan(Class type, Class real) {
Method[] list = type.getDeclaredMethods();
for(Method method : list) {
Scan(method);
}
}
/// <summary>
/// This is used to scan all annotations within the given method.
/// Each annotation is checked against the set of supported XML
/// annotations. If the annotation is one of the XML annotations
/// then the method is considered for acceptance as either a
/// get method or a set method for the annotated property.
/// </summary>
/// <param name="method">
/// the method to be scanned for XML annotations
/// </param>
public void Scan(Method method) {
Annotation[] list = method.getDeclaredAnnotations();
for(Annotation label : list) {
Scan(method, label);
}
}
/// <summary>
/// This is used to scan all the methods of the class in order to
/// determine if it should have a default annotation. If the method
/// should have a default XML annotation then it is added to the
/// list of contacts to be used to form the class schema.
/// </summary>
/// <param name="type">
/// this is the type to have its methods scanned
/// </param>
/// <param name="access">
/// this is the default access type for the class
/// </param>
public void Scan(Class type, DefaultType access) {
Method[] list = type.getDeclaredMethods();
if(access == PROPERTY) {
for(Method method : list) {
Class value = factory.GetType(method);
if(value != null) {
Process(method);
}
}
}
}
/// <summary>
/// This reflectively checks the annotation to determine the type
/// of annotation it represents. If it represents an XML schema
/// annotation it is used to create a <c>Contact</c> which
/// can be used to represent the method within the source object.
/// </summary>
/// <param name="method">
/// the method that the annotation comes from
/// </param>
/// <param name="label">
/// the annotation used to model the XML schema
/// </param>
public void Scan(Method method, Annotation label) {
if(label instanceof Attribute) {
Process(method, label);
}
if(label instanceof ElementList) {
Process(method, label);
}
if(label instanceof ElementArray) {
Process(method, label);
}
if(label instanceof ElementMap) {
Process(method, label);
}
if(label instanceof Element) {
Process(method, label);
}
if(label instanceof Transient) {
Remove(method, label);
}
if(label instanceof Version) {
Process(method, label);
}
if(label instanceof Text) {
Process(method, label);
}
}
/// <summary>
/// This is used to classify the specified method into either a get
/// or set method. If the method is neither then an exception is
/// thrown to indicate that the XML annotations can only be used
/// with methods following the Java Bean naming conventions. Once
/// the method is classified is is added to either the read or
/// write map so that it can be paired after scanning is complete.
/// </summary>
/// <param name="method">
/// this is the method that is to be classified
/// </param>
/// <param name="label">
/// this is the annotation applied to the method
/// </param>
public void Process(Method method, Annotation label) {
MethodPart part = factory.GetInstance(method, label);
MethodType type = part.GetMethodType();
if(type == MethodType.GET) {
Process(part, read);
}
if(type == MethodType.IS) {
Process(part, read);
}
if(type == MethodType.SET) {
Process(part, write);
}
}
/// <summary>
/// This is used to classify the specified method into either a get
/// or set method. If the method is neither then an exception is
/// thrown to indicate that the XML annotations can only be used
/// with methods following the Java Bean naming conventions. Once
/// the method is classified is is added to either the read or
/// write map so that it can be paired after scanning is complete.
/// </summary>
/// <param name="method">
/// this is the method that is to be classified
/// </param>
public void Process(Method method) {
MethodPart part = factory.GetInstance(method);
MethodType type = part.GetMethodType();
if(type == MethodType.GET) {
Process(part, read);
}
if(type == MethodType.IS) {
Process(part, read);
}
if(type == MethodType.SET) {
Process(part, write);
}
}
/// <summary>
/// This is used to determine whether the specified method can be
/// inserted into the given <c>PartMap</c>. This ensures
/// that only the most specialized method is considered, which
/// enables annotated methods to be overridden in subclasses.
/// </summary>
/// <param name="method">
/// this is the method part that is to be inserted
/// </param>
/// <param name="map">
/// this is the part map used to contain the method
/// </param>
public void Process(MethodPart method, PartMap map) {
String name = method.GetName();
if(name != null) {
map.put(name, method);
}
}
/// <summary>
/// This method is used to remove a particular method from the list
/// of contacts. If the <c>Transient</c> annotation is used
/// by any method then this method must be removed from the schema.
/// In particular it is important to remove methods if there are
/// defaults applied to the class.
/// </summary>
/// <param name="method">
/// this is the method that is to be removed
/// </param>
/// <param name="label">
/// this is the label associated with the method
/// </param>
public void Remove(Method method, Annotation label) {
MethodPart part = factory.GetInstance(method, label);
MethodType type = part.GetMethodType();
if(type == MethodType.GET) {
Remove(part, read);
}
if(type == MethodType.IS) {
Remove(part, read);
}
if(type == MethodType.SET) {
Remove(part, write);
}
}
/// <summary>
/// This is used to remove the method part from the specified map.
/// Removal is performed using the name of the method part. If it
/// has been scanned and added to the map then it will be removed
/// and will not form part of the class schema.
/// </summary>
/// <param name="part">
/// this is the part to be removed from the map
/// </param>
/// <param name="map">
/// this is the map to removed the method part from
/// </param>
public void Remove(MethodPart part, PartMap map) {
String name = part.GetName();
if(name != null) {
map.Remove(name);
}
}
/// <summary>
/// This method is used to pair the get methods with a matching set
/// method. This pairs methods using the Java Bean method name, the
/// names must match exactly, meaning that the case and value of
/// the strings must be identical. Also in order for this to succeed
/// the types for the methods and the annotation must also match.
/// </summary>
public void Build() {
for(String name : read) {
MethodPart part = read.get(name);
if(part != null) {
Build(part, name);
}
}
}
/// <summary>
/// This method is used to pair the get methods with a matching set
/// method. This pairs methods using the Java Bean method name, the
/// names must match exactly, meaning that the case and value of
/// the strings must be identical. Also in order for this to succeed
/// the types for the methods and the annotation must also match.
/// </summary>
/// <param name="read">
/// this is a get method that has been extracted
/// </param>
/// <param name="name">
/// this is the Java Bean methods name to be matched
/// </param>
public void Build(MethodPart read, String name) {
MethodPart match = write.Take(name);
if(match != null) {
Build(read, match);
} else {
Build(read); // read only
}
}
/// <summary>
/// This method is used to create a read only contact. A read only
/// contact object is used when there is constructor injection used
/// by the class schema. So, read only methods can be used in a
/// fully serializable and deserializable object.
/// </summary>
/// <param name="read">
/// this is the part to add as a read only contact
/// </param>
public void Build(MethodPart read) {
add(new MethodContact(read));
}
/// <summary>
/// This method is used to pair the get methods with a matching set
/// method. This pairs methods using the Java Bean method name, the
/// names must match exactly, meaning that the case and value of
/// the strings must be identical. Also in order for this to succeed
/// the types for the methods and the annotation must also match.
/// </summary>
/// <param name="read">
/// this is a get method that has been extracted
/// </param>
/// <param name="write">
/// this is the write method to compare details with
/// </param>
public void Build(MethodPart read, MethodPart write) {
Annotation label = read.GetAnnotation();
String name = read.GetName();
if(!write.GetAnnotation().equals(label)) {
throw new MethodException("Annotations do not match for '%s' in %s", name, type);
}
Class type = read.GetType();
if(type != write.GetType()) {
throw new MethodException("Method types do not match for %s in %s", name, type);
}
add(new MethodContact(read, write));
}
/// <summary>
/// This is used to validate the object once all the get methods
/// have been matched with a set method. This ensures that there
/// is not a set method within the object that does not have a
/// match, therefore violating the contract of a property.
/// </summary>
public void Validate() {
for(String name : write) {
MethodPart part = write.get(name);
if(part != null) {
Validate(part, name);
}
}
}
/// <summary>
/// This is used to validate the object once all the get methods
/// have been matched with a set method. This ensures that there
/// is not a set method within the object that does not have a
/// match, therefore violating the contract of a property.
/// </summary>
/// <param name="write">
/// this is a get method that has been extracted
/// </param>
/// <param name="name">
/// this is the Java Bean methods name to be matched
/// </param>
public void Validate(MethodPart write, String name) {
MethodPart match = read.Take(name);
Method method = write.getMethod();
if(match == null) {
throw new MethodException("No matching get method for %s in %s", method, type);
}
}
/// <summary>
/// The <c>PartMap</c> is used to contain method parts using
/// the Java Bean method name for the part. This ensures that the
/// scanned and extracted methods can be acquired using a common
/// name, which should be the parsed Java Bean method name.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Core.MethodPart
/// </seealso>
private class PartMap : LinkedHashMap<String, MethodPart> : Iterable<String>{
/// <summary>
/// This returns an iterator for the Java Bean method names for
/// the <c>MethodPart</c> objects that are stored in the
/// map. This allows names to be iterated easily in a for loop.
/// </summary>
/// <returns>
/// this returns an iterator for the method name keys
/// </returns>
public Iterator<String> Iterator() {
return keySet().Iterator();
}
/// <summary>
/// This is used to acquire the method part for the specified
/// method name. This will remove the method part from this map
/// so that it can be checked later to ensure what remains.
/// </summary>
/// <param name="name">
/// this is the method name to get the method with
/// </param>
/// <returns>
/// this returns the method part for the given key
/// </returns>
public MethodPart Take(String name) {
return Remove(name);
}
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel; // need this for the properties metadata
using System.Xml;
using System.Text.RegularExpressions;
using Oranikle.Report.Engine;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// PropertyReportItem - The ReportItem Properties
/// </summary>
//[PropertyTab(typeof(PropertyTableTab), PropertyTabScope.Component),
// DefaultPropertyAttribute("Name")]
[DefaultPropertyAttribute("Name")]
internal class PropertyReportItem : ICustomTypeDescriptor, IReportItem
{
private DesignXmlDraw _Draw;
private DesignCtl _DesignCtl;
List<XmlNode> _RIs;
private XmlNode _node;
private XmlNode _tnode = null;
private XmlNode _mnode = null;
private object _custom = null;
bool bGroup = false;
bool InTable = false;
bool InMatrix = false;
bool bCustom = false;
internal PropertyReportItem(DesignXmlDraw d, DesignCtl dc, List<XmlNode> ris)
{
_Draw = d;
_DesignCtl = dc;
_RIs = ris;
_node = _RIs[0]; // the first node is the model for all of the nodes
if (_RIs.Count > 1)
bGroup = true;
else
bCustom = _node.Name == "CustomReportItem";
InTable = _Draw.InTable(_node);
if (InTable)
_tnode = _Draw.GetTableFromReportItem(_node);
InMatrix = _Draw.InMatrix(_node);
if (InMatrix)
_mnode = _Draw.GetMatrixFromReportItem(_node);
}
internal XmlNode TableNode
{
get { return _tnode; }
}
internal DesignXmlDraw Draw
{
get { return _Draw; }
}
internal DesignCtl DesignCtl
{
get { return _DesignCtl; }
}
internal XmlNode Node
{
get { return _node; }
}
internal List<XmlNode> Nodes
{
get { return _RIs; }
}
#region Design
[CategoryAttribute("Design"),
ParenthesizePropertyName(true),
DescriptionAttribute("The unique name of the report item.")]
public string Name
{
get
{
return GetName(_node);
}
set
{
SetName(_node, value);
}
}
#endregion
#region Style
[CategoryAttribute("Style"),
DescriptionAttribute("Defines the border of the report item.")]
public PropertyBorder Border
{
get
{
return new PropertyBorder(this);
}
}
[CategoryAttribute("Style"),
DescriptionAttribute("Controls the padding expressions")]
public PropertyPadding Padding
{
get
{
return new PropertyPadding(this);
}
}
[CategoryAttribute("Style"),
DescriptionAttribute("Controls the background expressions")]
public PropertyBackground Background
{
get
{
return new PropertyBackground(this);
}
}
#endregion
#region Behavior
[CategoryAttribute("Behavior"),
DescriptionAttribute("Defines a hyperlink, bookmark link, or drillthrough action for the report item.")]
public PropertyAction Action
{
get
{
return new PropertyAction(this);
}
}
[CategoryAttribute("Behavior"),
DescriptionAttribute("In PDFs, bookmarks are created for each instance of the report item. For example, putting a bookmark on a report item in a group header will generate a list of the groups in the report.")]
public PropertyExpr Bookmark
{
get
{
string ex = GetValue("Bookmark", "");
return new PropertyExpr(ex);
}
set
{
SetValue("Bookmark", value.Expression);
}
}
[CategoryAttribute("Behavior"),
DescriptionAttribute("A ToolTip provides a label that can be used by a renderer. For example, the Viewer and PDF renderers use this to popup the specified text when the mouse is over the report item.")]
public PropertyExpr ToolTip
{
get
{
string ex = GetValue("ToolTip", "");
return new PropertyExpr(ex);
}
set
{
SetValue("ToolTip", value.Expression);
}
}
[CategoryAttribute("Behavior"),
DescriptionAttribute("Defines the visibility of the item.")]
public PropertyVisibility Visibility
{
get
{
return new PropertyVisibility(this);
}
}
#endregion
#region XML
[CategoryAttribute("XML"),
DescriptionAttribute("The name to use for the element or attribute when exporting to XML.")]
public string DataElementName
{
get
{
return GetValue("DataElementName", "");
}
set
{
SetValue("DataElementName", value);
}
}
[CategoryAttribute("XML"),
DescriptionAttribute("When rendering XML determines how or whether the item appears in the XML.")]
public DataElementOutputEnum DataElementOutput
{
get
{
string v = GetValue("DataElementOutput", "Auto");
return Oranikle.Report.Engine.DataElementOutput.GetStyle(v);
}
set
{
SetValue("DataElementOutput", value.ToString());
}
}
[CategoryAttribute("Layout"),
DescriptionAttribute("Drawing order of the report item.")]
public int ZIndex
{
get
{
string v = GetValue("ZIndex", "0");
try
{
return Convert.ToInt32(v);
}
catch
{
return 0;
}
}
set
{
if (value < 0)
throw new ArgumentException("ZIndex must be greater or equal to 0.");
SetValue("ZIndex", value.ToString());
}
}
[CategoryAttribute("Layout"),
DescriptionAttribute("Report item can span multiple columns.")]
public int ColumnSpan
{
get
{
XmlNode ris = _node.ParentNode;
XmlNode tcell = ris.ParentNode;
if (tcell == null)
return 1;
string colspan = _Draw.GetElementValue(tcell, "ColSpan", "1");
return Convert.ToInt32(colspan);
}
set
{
XmlNode ris = _node.ParentNode;
XmlNode tcell = ris.ParentNode;
if (tcell != null && tcell.Name == "TableCell")
{ // SetTableCellColSpan does all the heavy lifting;
// ie making sure the # of columns continue to match
_DesignCtl.StartUndoGroup("Column Span change");
_Draw.SetTableCellColSpan(tcell, value.ToString());
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
}
}
[CategoryAttribute("Layout"),
DescriptionAttribute("Height and width of the report item.")]
public PropertySize Size
{
get
{
string w = GetValue("Width", "");
string h = GetValue("Height", "");
return new PropertySize(this, h, w);
}
}
[CategoryAttribute("Layout"),
DescriptionAttribute("Location of the report item.")]
public PropertyLocation Location
{
get
{
string x = GetValue("Left", "");
string y = GetValue("Top", "");
return new PropertyLocation(this, x, y);
}
}
#endregion
#region Table
[CategoryAttribute("Table"),
DescriptionAttribute("Table report item properties.")]
public PropertyTable Table
{
get
{
if (_tnode == null)
return null;
List<XmlNode> ris = new List<XmlNode>();
ris.Add(_tnode);
return new PropertyTable(_Draw, _DesignCtl, ris);
}
}
#endregion
#region Matrix
[CategoryAttribute("Matrix"),
DescriptionAttribute("Matrix report item properties.")]
public PropertyMatrix Matrix
{
get
{
if (_mnode == null)
return null;
List<XmlNode> ris = new List<XmlNode>();
ris.Add(_mnode);
return new PropertyMatrix(_Draw, _DesignCtl, ris);
}
}
#endregion
internal bool IsExpression(string e)
{
if (e == null)
return false;
string t = e.Trim();
if (t.Length == 0)
return false;
return t[0] == '=';
}
internal string GetName(XmlNode node)
{
if (node == null)
return "";
XmlAttribute xa = node.Attributes["Name"];
return xa == null ? "" : xa.Value;
}
internal void SetName(XmlNode node, string name)
{
if (node == null)
return;
string n = name.Trim();
string nerr = _Draw.NameError(node, n);
if (nerr != null)
{
throw new ApplicationException(nerr);
}
_DesignCtl.StartUndoGroup("Name change");
_Draw.SetName(node, n);
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
internal string GetWithList(string def, params string[] names)
{
return GetWithList(_node, def, names);
}
internal string GetWithList(XmlNode n, string def, params string[] names)
{
foreach (string nm in names)
{
n = _Draw.GetNamedChildNode(n, nm);
if (n == null)
return def;
}
return n.InnerText;
}
internal void RemoveWithList(params string[] names)
{
// build the name of the change
StringBuilder sb = new StringBuilder();
foreach (string s in names)
{
sb.Append(s);
sb.Append(' ');
}
sb.Append("change");
_DesignCtl.StartUndoGroup(sb.ToString());
// loop thru all the selected nodes to make the change
foreach (XmlNode n in _RIs)
{
RemoveWithList(n, names);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
private void RemoveWithList(XmlNode n, params string[] names)
{
foreach (string nm in names)
{
n = _Draw.GetNamedChildNode(n, nm);
if (n == null)
return;
}
XmlNode p = n.ParentNode;
_Draw.RemoveElement(p, names[names.Length-1]);
}
internal void SetWithList(string v, params string[] names)
{
// build the name of the change
StringBuilder sb = new StringBuilder();
foreach (string s in names)
{
sb.Append(s);
sb.Append(' ');
}
sb.Append("change");
_DesignCtl.StartUndoGroup(sb.ToString());
// loop thru all the selected nodes to make the change
foreach (XmlNode n in _RIs)
{
SetWithList(n, v, names);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
private void SetWithList(XmlNode n, string v, params string[] names)
{
foreach (string nm in names)
{
n = _Draw.GetCreateNamedChildNode(n, nm);
}
n.InnerText = v;
}
internal string GetValue(string l, string v)
{
return _Draw.GetElementValue(_node, l, v);
}
internal string GetValue(string l1, string l2, string v)
{
XmlNode sNode = _Draw.GetNamedChildNode(_node, l1);
if (sNode == null)
return v;
return _Draw.GetElementValue(sNode, l2, v);
}
internal string GetValue(string l1, string l2, string l3, string v)
{
XmlNode sNode = _Draw.GetNamedChildNode(_node, l1);
if (sNode == null)
return v;
sNode = _Draw.GetNamedChildNode(sNode, l2);
if (sNode == null)
return v;
return _Draw.GetElementValue(sNode, l3, v);
}
internal void SetValue(string l, bool b)
{
SetValue(l, b ? "true" : "false");
}
internal void SetValue(string l, string v)
{
_DesignCtl.StartUndoGroup(l+ " change");
foreach (XmlNode n in _RIs)
{
_Draw.SetElement(n, l, v);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
internal void SetValue(string l1, string l2, string v)
{
_DesignCtl.StartUndoGroup(string.Format("{0} {1} change", l1, l2));
foreach (XmlNode n in _RIs)
{
XmlNode lNode = _Draw.GetCreateNamedChildNode(n, l1);
_Draw.SetElement(lNode, l2, v);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
internal void SetValue(string l1, string l2, string l3, string v)
{
_DesignCtl.StartUndoGroup(string.Format("{0} {1} change", l1, l2));
foreach (XmlNode n in _RIs)
{
XmlNode aNode = _Draw.GetCreateNamedChildNode(n, l1);
XmlNode lNode = _Draw.GetCreateNamedChildNode(aNode, l2);
_Draw.SetElement(lNode, l3, v);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
internal void RemoveValue(string l1)
{
_DesignCtl.StartUndoGroup(string.Format("{0} change", l1));
foreach (XmlNode n in _RIs)
{
_Draw.RemoveElement(n, l1);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
internal void RemoveValue(string l1, string l2)
{
_DesignCtl.StartUndoGroup(string.Format("{0} {1} change", l1, l2));
foreach (XmlNode n in _RIs)
{
XmlNode lNode = _Draw.GetNamedChildNode(n, l1);
if (lNode != null)
_Draw.RemoveElement(lNode, l2);
}
_DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
}
#region ICustomTypeDescriptor Members
// Implementation of ICustomTypeDescriptor:
public String GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
public String GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, true);
}
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return GetProperties();
}
public PropertyDescriptorCollection GetProperties()
{
// Get the collection of properties
PropertyDescriptorCollection bProps =
TypeDescriptor.GetProperties(this, true);
PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(null);
// For each property use a property descriptor of our own that is able to
// be globalized
foreach( PropertyDescriptor p in bProps )
{
if (p.Name == "Name" && bGroup)
continue;
if (InTable || InMatrix)
{ // Never show size or location when in a table or matrix
if (p.Name == "Size" || p.Name == "Location")
continue;
}
if (!InTable)
{ // Only show table related properties when in a table
if (p.Category == "Table")
continue;
if (p.Name == "ColumnSpan")
continue;
}
if (!InMatrix)
{ // Only show matrix related properties when in a matrix
if (p.Category == "Matrix")
continue;
}
// create our custom property descriptor and add it to the collection
pdc.Add(p);
}
if (bCustom)
SetCustomReportItem(pdc);
return pdc;
}
private void SetCustomReportItem(PropertyDescriptorCollection pdc)
{
ICustomReportItem cri = null;
try
{
string t = _Draw.GetElementValue(this.Node, "Type", "");
cri = RdlEngineConfig.CreateCustomReportItem(t);
_custom = cri.GetPropertiesInstance(_Draw.GetNamedChildNode(this.Node, "CustomProperties"));
TypeDescriptor.CreateAssociation(this, _custom);
PropertyDescriptorCollection bProps =
TypeDescriptor.GetProperties(_custom, true);
foreach (PropertyDescriptor p in bProps)
{
// create our custom property descriptor and add it to the collection
pdc.Add(p);
}
}
catch
{
}
finally
{
if (cri != null)
cri.Dispose();
}
return;
}
#endregion
#region IReportItem Members
public PropertyReportItem GetPRI()
{
return this;
}
#endregion
}
#region ColorValues
internal class ColorConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false; // allow user to also edit the color directly
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(StaticLists.ColorList);
}
}
#endregion
#region IReportItem
internal interface IReportItem
{
PropertyReportItem GetPRI();
}
#endregion
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gccv = Google.Cloud.Channel.V1;
using sys = System;
namespace Google.Cloud.Channel.V1
{
/// <summary>Resource name for the <c>Offer</c> resource.</summary>
public sealed partial class OfferName : gax::IResourceName, sys::IEquatable<OfferName>
{
/// <summary>The possible contents of <see cref="OfferName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>accounts/{account}/offers/{offer}</c>.</summary>
AccountOffer = 1,
}
private static gax::PathTemplate s_accountOffer = new gax::PathTemplate("accounts/{account}/offers/{offer}");
/// <summary>Creates a <see cref="OfferName"/> 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="OfferName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static OfferName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new OfferName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="OfferName"/> with the pattern <c>accounts/{account}/offers/{offer}</c>.
/// </summary>
/// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offerId">The <c>Offer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="OfferName"/> constructed from the provided ids.</returns>
public static OfferName FromAccountOffer(string accountId, string offerId) =>
new OfferName(ResourceNameType.AccountOffer, accountId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), offerId: gax::GaxPreconditions.CheckNotNullOrEmpty(offerId, nameof(offerId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="OfferName"/> with pattern
/// <c>accounts/{account}/offers/{offer}</c>.
/// </summary>
/// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offerId">The <c>Offer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="OfferName"/> with pattern <c>accounts/{account}/offers/{offer}</c>
/// .
/// </returns>
public static string Format(string accountId, string offerId) => FormatAccountOffer(accountId, offerId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="OfferName"/> with pattern
/// <c>accounts/{account}/offers/{offer}</c>.
/// </summary>
/// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offerId">The <c>Offer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="OfferName"/> with pattern <c>accounts/{account}/offers/{offer}</c>
/// .
/// </returns>
public static string FormatAccountOffer(string accountId, string offerId) =>
s_accountOffer.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), gax::GaxPreconditions.CheckNotNullOrEmpty(offerId, nameof(offerId)));
/// <summary>Parses the given resource name string into a new <see cref="OfferName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>accounts/{account}/offers/{offer}</c></description></item></list>
/// </remarks>
/// <param name="offerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="OfferName"/> if successful.</returns>
public static OfferName Parse(string offerName) => Parse(offerName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="OfferName"/> 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>accounts/{account}/offers/{offer}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="offerName">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="OfferName"/> if successful.</returns>
public static OfferName Parse(string offerName, bool allowUnparsed) =>
TryParse(offerName, allowUnparsed, out OfferName 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="OfferName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>accounts/{account}/offers/{offer}</c></description></item></list>
/// </remarks>
/// <param name="offerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="OfferName"/>, 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 offerName, out OfferName result) => TryParse(offerName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="OfferName"/> 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>accounts/{account}/offers/{offer}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="offerName">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="OfferName"/>, 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 offerName, bool allowUnparsed, out OfferName result)
{
gax::GaxPreconditions.CheckNotNull(offerName, nameof(offerName));
gax::TemplatedResourceName resourceName;
if (s_accountOffer.TryParseName(offerName, out resourceName))
{
result = FromAccountOffer(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(offerName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private OfferName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string accountId = null, string offerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AccountId = accountId;
OfferId = offerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="OfferName"/> class from the component parts of pattern
/// <c>accounts/{account}/offers/{offer}</c>
/// </summary>
/// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="offerId">The <c>Offer</c> ID. Must not be <c>null</c> or empty.</param>
public OfferName(string accountId, string offerId) : this(ResourceNameType.AccountOffer, accountId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), offerId: gax::GaxPreconditions.CheckNotNullOrEmpty(offerId, nameof(offerId)))
{
}
/// <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>Account</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AccountId { get; }
/// <summary>
/// The <c>Offer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string OfferId { 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.AccountOffer: return s_accountOffer.Expand(AccountId, OfferId);
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 OfferName);
/// <inheritdoc/>
public bool Equals(OfferName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(OfferName a, OfferName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(OfferName a, OfferName b) => !(a == b);
}
public partial class Offer
{
/// <summary>
/// <see cref="gccv::OfferName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::OfferName OfferName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::OfferName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace ManiX
{
public partial class XButton : Button
{
#region Fields
private Theme thm = Theme.MSOffice2010_BLUE;
private enum MouseState { None = 1, Down = 2, Up = 3, Enter = 4, Leave = 5, Move = 6 }
private MouseState MState = MouseState.None;
#endregion
#region Constructor
public XButton()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor |
ControlStyles.Opaque |
ControlStyles.ResizeRedraw |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.CacheText | // We gain about 2% in painting by avoiding extra GetWindowText calls
ControlStyles.StandardClick,
true);
this.colorTable = new Colortable();
this.MouseLeave += new EventHandler(_MouseLeave);
this.MouseDown += new MouseEventHandler(_MouseDown);
this.MouseUp += new MouseEventHandler(_MouseUp);
this.MouseMove += new MouseEventHandler(_MouseMove);
}
#endregion
#region Events
#region Paint Transparent Background
protected void PaintTransparentBackground(Graphics g, Rectangle clipRect)
{
// check if we have a parent
if (this.Parent != null)
{
// convert the clipRects coordinates from ours to our parents
clipRect.Offset(this.Location);
PaintEventArgs e = new PaintEventArgs(g, clipRect);
// save the graphics state so that if anything goes wrong
// we're not fubar
GraphicsState state = g.Save();
try
{
// move the graphics object so that we are drawing in
// the correct place
g.TranslateTransform((float)-this.Location.X, (float)-this.Location.Y);
// draw the parents background and foreground
this.InvokePaintBackground(this.Parent, e);
this.InvokePaint(this.Parent, e);
return;
}
finally
{
// reset everything back to where they were before
g.Restore(state);
clipRect.Offset(-this.Location.X, -this.Location.Y);
}
}
// we don't have a parent, so fill the rect with
// the default control color
g.FillRectangle(SystemBrushes.Control, clipRect);
}
#endregion
#region Mouse Events
private void _MouseDown(object sender, MouseEventArgs mevent)
{
MState = MouseState.Down;
Invalidate();
}
private void _MouseUp(object sender, MouseEventArgs mevent)
{
MState = MouseState.Up;
Invalidate();
}
private void _MouseMove(object sender, MouseEventArgs mevent)
{
MState = MouseState.Move;
Invalidate();
}
private void _MouseLeave(object sender, EventArgs e)
{
MState = MouseState.Leave;
Invalidate();
}
#endregion
#region Path
public static GraphicsPath GetRoundedRect(RectangleF r, float radius)
{
GraphicsPath gp = new GraphicsPath();
gp.StartFigure();
r = new RectangleF(r.Left, r.Top, r.Width, r.Height);
if (radius <= 0.0F || radius <= 0.0F)
{
gp.AddRectangle(r);
}
else
{
gp.AddArc((float)r.X, (float)r.Y, radius, radius, 180, 90);
gp.AddArc((float)r.Right - radius, (float)r.Y, radius - 1, radius, 270, 90);
gp.AddArc((float)r.Right - radius, ((float)r.Bottom) - radius - 1, radius - 1, radius, 0, 90);
gp.AddArc((float)r.X, ((float)r.Bottom) - radius - 1, radius - 1, radius, 90, 90);
}
gp.CloseFigure();
return gp;
}
#endregion
#region Paint
protected override void OnPaint(PaintEventArgs e)
{
this.PaintTransparentBackground(e.Graphics, e.ClipRectangle);
#region Painting
//now let's we begin painting
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.HighQuality;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
#endregion
#region Color
Color tTopColorBegin = this.colorTable.ButtonNormalColor1;
Color tTopColorEnd = this.colorTable.ButtonNormalColor2;
Color tBottomColorBegin = this.colorTable.ButtonNormalColor3;
Color tBottomColorEnd = this.colorTable.ButtonNormalColor4;
Color Textcol = this.colorTable.TextColor;
if (!this.Enabled)
{
tTopColorBegin = Color.FromArgb((int)(tTopColorBegin.GetBrightness() * 255),
(int)(tTopColorBegin.GetBrightness() * 255),
(int)(tTopColorBegin.GetBrightness() * 255));
tBottomColorEnd = Color.FromArgb((int)(tBottomColorEnd.GetBrightness() * 255),
(int)(tBottomColorEnd.GetBrightness() * 255),
(int)(tBottomColorEnd.GetBrightness() * 255));
}
else
{
if (MState == MouseState.None || MState == MouseState.Leave)
{
tTopColorBegin = this.colorTable.ButtonNormalColor1;
tTopColorEnd = this.colorTable.ButtonNormalColor2;
tBottomColorBegin = this.colorTable.ButtonNormalColor3;
tBottomColorEnd = this.colorTable.ButtonNormalColor4;
Textcol = this.colorTable.TextColor;
}
else if (MState == MouseState.Down)
{
tTopColorBegin = this.colorTable.ButtonSelectedColor1;
tTopColorEnd = this.colorTable.ButtonSelectedColor2;
tBottomColorBegin = this.colorTable.ButtonSelectedColor3;
tBottomColorEnd = this.colorTable.ButtonSelectedColor4;
Textcol = this.colorTable.SelectedTextColor;
}
else if (MState == MouseState.Move || MState == MouseState.Up)
{
tTopColorBegin = this.colorTable.ButtonMouseOverColor1;
tTopColorEnd = this.colorTable.ButtonMouseOverColor2;
tBottomColorBegin = this.colorTable.ButtonMouseOverColor3;
tBottomColorEnd = this.colorTable.ButtonMouseOverColor4;
Textcol = this.colorTable.HoverTextColor;
}
}
#endregion
#region Theme 2010
if (thm == Theme.MSOffice2010_BLUE || thm == Theme.MSOffice2010_Green || thm == Theme.MSOffice2010_Yellow || thm == Theme.MSOffice2010_Publisher ||
thm == Theme.MSOffice2010_RED || thm == Theme.MSOffice2010_WHITE || thm == Theme.MSOffice2010_Pink)
{
Paint2010Background(e, g, tTopColorBegin, tTopColorEnd, tBottomColorBegin, tBottomColorEnd);
TEXTandIMAGE(e.ClipRectangle, g, Textcol);
}
#endregion
}
#endregion
#region Paint 2010 Background
protected void Paint2010Background(PaintEventArgs e, Graphics g, Color tTopColorBegin, Color tTopColorEnd, Color tBottomColorBegin, Color tBottomColorEnd)
{
int _roundedRadiusX = 6;
Rectangle r = new Rectangle(e.ClipRectangle.Left, e.ClipRectangle.Top, e.ClipRectangle.Width, e.ClipRectangle.Height);
Rectangle j = r;
Rectangle r2 = r;
r2.Inflate(-1, -1);
Rectangle r3 = r2;
r3.Inflate(-1, -1);
//rectangle for gradient, half upper and lower
RectangleF halfup = new RectangleF(r.Left, r.Top, r.Width, r.Height);
RectangleF halfdown = new RectangleF(r.Left, r.Top + (r.Height / 2) - 1, r.Width, r.Height);
//BEGIN PAINT BACKGROUND
//for half upper, we paint using linear gradient
using (GraphicsPath thePath = GetRoundedRect(r, _roundedRadiusX))
{
LinearGradientBrush lgb = new LinearGradientBrush(halfup, tBottomColorEnd, tBottomColorBegin, 90f, true);
Blend blend = new Blend(4);
blend.Positions = new float[] { 0, 0.18f, 0.35f, 1f };
blend.Factors = new float[] { 0f, .4f, .9f, 1f };
lgb.Blend = blend;
g.FillPath(lgb, thePath);
lgb.Dispose();
//for half lower, we paint using radial gradient
using (GraphicsPath p = new GraphicsPath())
{
p.AddEllipse(halfdown); //make it radial
using (PathGradientBrush gradient = new PathGradientBrush(p))
{
gradient.WrapMode = WrapMode.Clamp;
gradient.CenterPoint = new PointF(Convert.ToSingle(halfdown.Left + halfdown.Width / 2), Convert.ToSingle(halfdown.Bottom));
gradient.CenterColor = tBottomColorEnd;
gradient.SurroundColors = new Color[] { tBottomColorBegin };
blend = new Blend(4);
blend.Positions = new float[] { 0, 0.15f, 0.4f, 1f };
blend.Factors = new float[] { 0f, .3f, 1f, 1f };
gradient.Blend = blend;
g.FillPath(gradient, thePath);
}
}
//END PAINT BACKGROUND
//BEGIN PAINT BORDERS
using (GraphicsPath gborderDark = thePath)
{
using (Pen p = new Pen(tTopColorBegin, 1))
{
g.DrawPath(p, gborderDark);
}
}
using (GraphicsPath gborderLight = GetRoundedRect(r2, _roundedRadiusX))
{
using (Pen p = new Pen(tTopColorEnd, 1))
{
g.DrawPath(p, gborderLight);
}
}
using (GraphicsPath gborderMed = GetRoundedRect(r3, _roundedRadiusX))
{
SolidBrush bordermed = new SolidBrush(Color.FromArgb(50, tTopColorEnd));
using (Pen p = new Pen(bordermed, 1))
{
g.DrawPath(p, gborderMed);
}
}
//END PAINT BORDERS
}
}
#endregion
#region Paint TEXT AND IMAGE
protected void TEXTandIMAGE(Rectangle Rec, Graphics g, Color textColor)
{
//BEGIN PAINT TEXT
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
#region Top
if (this.TextAlign == ContentAlignment.TopLeft)
{
sf.LineAlignment = StringAlignment.Near;
sf.Alignment = StringAlignment.Near;
}
else if (this.TextAlign == ContentAlignment.TopCenter)
{
sf.LineAlignment = StringAlignment.Near;
sf.Alignment = StringAlignment.Center;
}
else if (this.TextAlign == ContentAlignment.TopRight)
{
sf.LineAlignment = StringAlignment.Near;
sf.Alignment = StringAlignment.Far;
}
#endregion
#region Middle
else if (this.TextAlign == ContentAlignment.MiddleLeft)
{
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Near;
}
else if (this.TextAlign == ContentAlignment.MiddleCenter)
{
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
}
else if (this.TextAlign == ContentAlignment.MiddleRight)
{
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Far;
}
#endregion
#region Bottom
else if (this.TextAlign == ContentAlignment.BottomLeft)
{
sf.LineAlignment = StringAlignment.Far;
sf.Alignment = StringAlignment.Near;
}
else if (this.TextAlign == ContentAlignment.BottomCenter)
{
sf.LineAlignment = StringAlignment.Far;
sf.Alignment = StringAlignment.Center;
}
else if (this.TextAlign == ContentAlignment.BottomRight)
{
sf.LineAlignment = StringAlignment.Far;
sf.Alignment = StringAlignment.Far;
}
#endregion
if (this.ShowKeyboardCues)
sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show;
else
sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Hide;
g.DrawString(this.Text, this.Font, new SolidBrush(textColor), Rec, sf);
}
#endregion
#endregion
#region Properties
#region ColorTable
Colortable colorTable = null;
[DefaultValue(typeof(Colortable), "Office2010Blue")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public Colortable ColorTable
{
get
{
if (colorTable == null)
colorTable = new Colortable();
return colorTable;
}
set
{
if (value == null)
value = Colortable.Office2010Blue;
colorTable = (Colortable)value;
this.Invalidate();
}
}
public Theme Theme
{
get
{
if (this.colorTable == Colortable.Office2010Green)
{
return Theme.MSOffice2010_Green;
}
else if (this.colorTable == Colortable.Office2010Red)
{
return Theme.MSOffice2010_RED;
}
else if (this.colorTable == Colortable.Office2010Pink)
{
return Theme.MSOffice2010_Pink;
}
else if (this.colorTable == Colortable.Office2010Yellow)
{
return Theme.MSOffice2010_Yellow;
}
else if (this.colorTable == Colortable.Office2010White)
{
return Theme.MSOffice2010_WHITE;
}
else if (this.colorTable == Colortable.Office2010Publisher)
{
return Theme.MSOffice2010_Publisher;
}
return Theme.MSOffice2010_BLUE;
}
set
{
this.thm = value;
if (thm == Theme.MSOffice2010_Green)
{
this.colorTable = Colortable.Office2010Green;
}
else if (thm == Theme.MSOffice2010_RED)
{
this.colorTable = Colortable.Office2010Red;
}
else if (thm == Theme.MSOffice2010_Pink)
{
this.colorTable = Colortable.Office2010Pink;
}
else if (thm == Theme.MSOffice2010_WHITE)
{
this.colorTable = Colortable.Office2010White;
}
else if (thm == Theme.MSOffice2010_Yellow)
{
this.colorTable = Colortable.Office2010Yellow;
}
else if (thm == Theme.MSOffice2010_Publisher)
{
this.colorTable = Colortable.Office2010Publisher;
}
else
{
this.colorTable = Colortable.Office2010Blue;
}
}
}
#endregion
#region Background Image
[Browsable(false)]
public override Image BackgroundImage
{
get
{
return base.BackgroundImage;
}
set
{
base.BackgroundImage = value;
}
}
[Browsable(false)]
public override ImageLayout BackgroundImageLayout
{
get
{
return base.BackgroundImageLayout;
}
set
{
base.BackgroundImageLayout = value;
}
}
#endregion
#endregion
}
#region ENUM
public enum Theme
{
MSOffice2010_BLUE = 1,
MSOffice2010_WHITE = 2,
MSOffice2010_RED = 3,
MSOffice2010_Green = 4,
MSOffice2010_Pink = 5,
MSOffice2010_Yellow = 6,
MSOffice2010_Publisher = 7
}
#endregion
#region COLOR TABLE
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Colortable
{
#region Static Color Tables
static Office2010Blue office2010blu = new Office2010Blue();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010Blue
{
get { return office2010blu; }
}
static Office2010Green office2010gr = new Office2010Green();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010Green
{
get { return office2010gr; }
}
static Office2010Red office2010rd = new Office2010Red();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010Red
{
get { return office2010rd; }
}
static Office2010Pink office2010pk = new Office2010Pink();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010Pink
{
get { return office2010pk; }
}
static Office2010Yellow office2010yl = new Office2010Yellow();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010Yellow
{
get { return office2010yl; }
}
static Office2010White office2010wt = new Office2010White();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010White
{
get { return office2010wt; }
}
static Office2010Publisher office2010pb = new Office2010Publisher();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public static Colortable Office2010Publisher
{
get { return office2010pb; }
}
#endregion
#region Custom Properties
Color textColor = Color.White;
Color selectedTextColor = Color.FromArgb(30, 57, 91);
Color OverTextColor = Color.FromArgb(30, 57, 91);
Color borderColor = Color.FromArgb(31, 72, 161);
Color innerborderColor = Color.FromArgb(68, 135, 228);
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color TextColor
{
get { return textColor; }
set { textColor = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color SelectedTextColor
{
get { return selectedTextColor; }
set { selectedTextColor = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color HoverTextColor
{
get { return OverTextColor; }
set { OverTextColor = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color BorderColor1
{
get { return borderColor; }
set { borderColor = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color BorderColor2
{
get { return innerborderColor; }
set { innerborderColor = value; }
}
#endregion
#region Button Normal
Color buttonNormalBegin = Color.FromArgb(31, 72, 161);
Color buttonNormalMiddleBegin = Color.FromArgb(68, 135, 228);
Color buttonNormalMiddleEnd = Color.FromArgb(41, 97, 181);
Color buttonNormalEnd = Color.FromArgb(62, 125, 219);
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonNormalColor1
{
get { return buttonNormalBegin; }
set { buttonNormalBegin = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonNormalColor2
{
get { return buttonNormalMiddleBegin; }
set { buttonNormalMiddleBegin = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonNormalColor3
{
get { return buttonNormalMiddleEnd; }
set { buttonNormalMiddleEnd = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonNormalColor4
{
get { return buttonNormalEnd; }
set { buttonNormalEnd = value; }
}
#endregion
#region Button Selected
Color buttonSelectedBegin = Color.FromArgb(236, 199, 87);
Color buttonSelectedMiddleBegin = Color.FromArgb(252, 243, 215);
Color buttonSelectedMiddleEnd = Color.FromArgb(255, 229, 117);
Color buttonSelectedEnd = Color.FromArgb(255, 216, 107);
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonSelectedColor1
{
get { return buttonSelectedBegin; }
set { buttonSelectedBegin = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonSelectedColor2
{
get { return buttonSelectedMiddleBegin; }
set { buttonSelectedMiddleBegin = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonSelectedColor3
{
get { return buttonSelectedMiddleEnd; }
set { buttonSelectedMiddleEnd = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonSelectedColor4
{
get { return buttonSelectedEnd; }
set { buttonSelectedEnd = value; }
}
#endregion
#region Button Mouse Over
Color buttonMouseOverBegin = Color.FromArgb(236, 199, 87);
Color buttonMouseOverMiddleBegin = Color.FromArgb(252, 243, 215);
Color buttonMouseOverMiddleEnd = Color.FromArgb(249, 225, 137);
Color buttonMouseOverEnd = Color.FromArgb(251, 249, 224);
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonMouseOverColor1
{
get { return buttonMouseOverBegin; }
set { buttonMouseOverBegin = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonMouseOverColor2
{
get { return buttonMouseOverMiddleBegin; }
set { buttonMouseOverMiddleBegin = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonMouseOverColor3
{
get { return buttonMouseOverMiddleEnd; }
set { buttonMouseOverMiddleEnd = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public virtual Color ButtonMouseOverColor4
{
get { return buttonMouseOverEnd; }
set { buttonMouseOverEnd = value; }
}
#endregion
}
#region Office 2010 Blue
public class Office2010Blue : Colortable
{
public Office2010Blue()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.White;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(31, 72, 161);
this.ButtonNormalColor2 = Color.FromArgb(68, 135, 228);
this.ButtonNormalColor3 = Color.FromArgb(41, 97, 181);
this.ButtonNormalColor4 = Color.FromArgb(62, 125, 219);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010Blue";
}
}
#endregion
#region Office 2010 GREEN
public class Office2010Green : Colortable
{
public Office2010Green()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.White;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(42, 126, 43);
this.ButtonNormalColor2 = Color.FromArgb(94, 184, 67);
this.ButtonNormalColor3 = Color.FromArgb(42, 126, 43);
this.ButtonNormalColor4 = Color.FromArgb(94, 184, 67);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010Green";
}
}
#endregion
#region Office 2010 Red
public class Office2010Red : Colortable
{
public Office2010Red()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.White;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(227, 77, 45);
this.ButtonNormalColor2 = Color.FromArgb(245, 148, 64);
this.ButtonNormalColor3 = Color.FromArgb(227, 77, 45);
this.ButtonNormalColor4 = Color.FromArgb(245, 148, 64);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010Red";
}
}
#endregion
#region Office 2010 Pink
public class Office2010Pink : Colortable
{
public Office2010Pink()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.White;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(175, 6, 77);
this.ButtonNormalColor2 = Color.FromArgb(222, 52, 119);
this.ButtonNormalColor3 = Color.FromArgb(175, 6, 77);
this.ButtonNormalColor4 = Color.FromArgb(222, 52, 119);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010Pink";
}
}
#endregion
#region Office 2010 White
public class Office2010White : Colortable
{
public Office2010White()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.Black;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(154, 154, 154);
this.ButtonNormalColor2 = Color.FromArgb(255, 255, 255);
this.ButtonNormalColor3 = Color.FromArgb(235, 235, 235);
this.ButtonNormalColor4 = Color.FromArgb(255, 255, 255);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010White";
}
}
#endregion
#region Office 2010 Yellow
public class Office2010Yellow : Colortable
{
public Office2010Yellow()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.White;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(252, 161, 8);
this.ButtonNormalColor2 = Color.FromArgb(251, 191, 45);
this.ButtonNormalColor3 = Color.FromArgb(252, 161, 8);
this.ButtonNormalColor4 = Color.FromArgb(251, 191, 45);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010Yellow";
}
}
#endregion
#region Office 2010 Publisher
public class Office2010Publisher : Colortable
{
public Office2010Publisher()
{
// Border Color
this.BorderColor1 = Color.FromArgb(31, 72, 161);
this.BorderColor2 = Color.FromArgb(68, 135, 228);
// Button Text Color
this.TextColor = Color.White;
this.SelectedTextColor = Color.FromArgb(30, 57, 91);
this.HoverTextColor = Color.FromArgb(30, 57, 91);
// Button normal color
this.ButtonNormalColor1 = Color.FromArgb(0, 126, 126);
this.ButtonNormalColor2 = Color.FromArgb(31, 173, 167);
this.ButtonNormalColor3 = Color.FromArgb(0, 126, 126);
this.ButtonNormalColor4 = Color.FromArgb(31, 173, 167);
// Button mouseover color
this.ButtonMouseOverColor1 = Color.FromArgb(236, 199, 87);
this.ButtonMouseOverColor2 = Color.FromArgb(252, 243, 215);
this.ButtonMouseOverColor3 = Color.FromArgb(249, 225, 137);
this.ButtonMouseOverColor4 = Color.FromArgb(251, 249, 224);
// Button selected color
this.ButtonSelectedColor1 = Color.FromArgb(236, 199, 87);
this.ButtonSelectedColor2 = Color.FromArgb(252, 243, 215);
this.ButtonSelectedColor3 = Color.FromArgb(255, 229, 117);
this.ButtonSelectedColor4 = Color.FromArgb(255, 216, 107);
}
public override string ToString()
{
return "Office2010Publisher";
}
}
#endregion
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Social.Messaging.Scheduler
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web.Caching;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Scheduling;
using DotNetNuke.Services.Social.Messaging.Internal;
using Localization = DotNetNuke.Services.Localization.Localization;
/// <summary>
/// A SchedulerClient instance that handles all the offline messaging actions.
/// </summary>
public class CoreMessagingScheduler : SchedulerClient
{
/// <summary>The setting name for number hours since last hourly digest run.</summary>
private const string SettingLastHourlyRun = "CoreMessagingLastHourlyDigestRun";
/// <summary>The setting name for number hours since last daily digest run.</summary>
private const string SettingLastDailyRun = "CoreMessagingLastDailyDigestRun";
/// <summary>The setting name for number hours since last weekly digest run.</summary>
private const string SettingLastWeeklyRun = "CoreMessagingLastWeeklyDigestRun";
/// <summary>The setting name for number hours since last monthly digest run.</summary>
private const string SettingLastMonthlyRun = "CoreMessagingLastMonthlyDigestRun";
/// <summary>Initializes a new instance of the <see cref="CoreMessagingScheduler"/> class.</summary>
/// <param name="objScheduleHistoryItem">The object schedule history item.</param>
public CoreMessagingScheduler(ScheduleHistoryItem objScheduleHistoryItem)
{
this.ScheduleHistoryItem = objScheduleHistoryItem;
}
/// <summary>This is the method that kicks off the actual work within the SchedulerClient's subclass.</summary>
public override void DoWork()
{
try
{
var schedulerInstance = Guid.NewGuid();
this.ScheduleHistoryItem.AddLogNote("Messaging Scheduler DoWork Starting " + schedulerInstance);
if (string.IsNullOrEmpty(Host.SMTPServer))
{
this.ScheduleHistoryItem.AddLogNote("<br>No SMTP Servers have been configured for this host. Terminating task.");
this.ScheduleHistoryItem.Succeeded = true;
}
else
{
this.Progressing();
var instantMessages = this.HandleInstantMessages(schedulerInstance);
var remainingMessages = Host.MessageSchedulerBatchSize - instantMessages;
if (remainingMessages > 0)
{
this.HandleFrequentDigests(schedulerInstance, remainingMessages);
}
this.ScheduleHistoryItem.Succeeded = true;
}
}
catch (Exception ex)
{
this.ScheduleHistoryItem.Succeeded = false;
this.ScheduleHistoryItem.AddLogNote("<br>Messaging Scheduler Failed: " + ex);
this.Errored(ref ex);
}
}
/// <summary>Determines whether [is send email enable] [the specified portal identifier].</summary>
/// <param name="portalId">The portal identifier.</param>
/// <returns>True if mail is enabled in PortalSettings.</returns>
private static bool IsSendEmailEnable(int portalId)
{
return PortalController.GetPortalSetting("MessagingSendEmail", portalId, "YES") == "YES";
}
/// <summary>Determines whether [is user able to receive an email] [the specified recipient user].</summary>
/// <param name="recipientUser">The recipient user.</param>
/// <returns>True if the user can receive email, otherwise false.</returns>
private static bool IsUserAbleToReceiveAnEmail(UserInfo recipientUser)
{
return recipientUser != null && !recipientUser.IsDeleted && recipientUser.Membership.Approved;
}
/// <summary>Gets the sender address.</summary>
/// <param name="sender">The sender.</param>
/// <param name="fromAddress">From address.</param>
/// <returns>The formatted sender address.</returns>
private static string GetSenderAddress(string sender, string fromAddress)
{
return string.Format("{0} < {1} >", sender, fromAddress);
}
/// <summary>Gets the email body.</summary>
/// <param name="template">The template.</param>
/// <param name="messageBody">The message body.</param>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="recipientUser">The recipient user.</param>
/// <returns>A string containing the email body with any tokens replaced.</returns>
private static string GetEmailBody(string template, string messageBody, PortalSettings portalSettings, UserInfo recipientUser)
{
template = template.Replace("[MESSAGEBODY]", messageBody); // moved to top since that we we can replace tokens in there too...
template = template.Replace("[RECIPIENTUSERID]", recipientUser.UserID.ToString(CultureInfo.InvariantCulture));
template = template.Replace("[RECIPIENTDISPLAYNAME]", recipientUser.DisplayName);
template = template.Replace("[RECIPIENTEMAIL]", recipientUser.Email);
template = template.Replace("[SITEURL]", GetPortalHomeUrl(portalSettings));
template = template.Replace("[NOTIFICATIONURL]", GetNotificationUrl(portalSettings, recipientUser.UserID));
template = template.Replace("[PORTALNAME]", portalSettings.PortalName);
template = template.Replace("[LOGOURL]", GetPortalLogoUrl(portalSettings));
template = template.Replace("[UNSUBSCRIBEURL]", GetSubscriptionsUrl(portalSettings, recipientUser.UserID));
template = template.Replace("[YEAR]", DateTime.Now.Year.ToString());
template = ResolveUrl(portalSettings, template);
return template;
}
/// <summary>Gets the content of the email item.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="message">The message.</param>
/// <param name="itemTemplate">The item template.</param>
/// <returns>A string with all email tokens replaced with content.</returns>
private static string GetEmailItemContent(PortalSettings portalSettings, MessageRecipient message, string itemTemplate)
{
var messageDetails = InternalMessagingController.Instance.GetMessage(message.MessageID);
var authorId = message.CreatedByUserID > 0 ? message.CreatedByUserID : messageDetails.SenderUserID;
var emailItemContent = itemTemplate;
emailItemContent = emailItemContent.Replace("[TITLE]", messageDetails.Subject);
emailItemContent = emailItemContent.Replace("[CONTENT]", HtmlUtils.ConvertToHtml(messageDetails.Body));
emailItemContent = emailItemContent.Replace("[PROFILEPICURL]", GetProfilePicUrl(portalSettings, authorId));
emailItemContent = emailItemContent.Replace("[PROFILEURL]", GetProfileUrl(portalSettings, authorId));
emailItemContent = emailItemContent.Replace("[DISPLAYNAME]", GetDisplayName(portalSettings, authorId));
if (messageDetails.NotificationTypeID == 1)
{
var toUser = UserController.Instance.GetUser(messageDetails.PortalID, message.UserID);
var defaultLanguage = toUser.Profile.PreferredLocale;
var acceptUrl = GetRelationshipAcceptRequestUrl(portalSettings, authorId, "AcceptFriend");
var profileUrl = GetProfileUrl(portalSettings, authorId);
var linkContent = GetFriendRequestActionsTemplate(portalSettings, defaultLanguage);
emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl));
}
if (messageDetails.NotificationTypeID == 3)
{
var toUser = UserController.Instance.GetUser(messageDetails.PortalID, message.UserID);
var defaultLanguage = toUser.Profile.PreferredLocale;
var acceptUrl = GetRelationshipAcceptRequestUrl(portalSettings, authorId, "FollowBack");
var profileUrl = GetProfileUrl(portalSettings, authorId);
var linkContent = GetFollowRequestActionsTemplate(portalSettings, defaultLanguage);
emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Format(linkContent, acceptUrl, profileUrl));
}
// No social actions for the rest of notifications types
emailItemContent = emailItemContent.Replace("[FOLLOWREQUESTACTIONS]", string.Empty);
emailItemContent = emailItemContent.Replace("[FRIENDREQUESTACTIONS]", string.Empty);
return emailItemContent;
}
/// <summary>Marks the messages as dispatched.</summary>
/// <param name="messages">The messages.</param>
private static void MarkMessagesAsDispatched(IEnumerable<MessageRecipient> messages)
{
foreach (var message in messages)
{
InternalMessagingController.Instance.MarkMessageAsDispatched(message.MessageID, message.RecipientID);
}
}
/// <summary>Gets the email body item template.</summary>
/// <param name="language">The language.</param>
/// <returns>The email body template item from the Global Resource File: EMAIL_MESSAGING_DISPATCH_ITEM.</returns>
private static string GetEmailBodyItemTemplate(PortalSettings portalSettings, string language)
{
return Localization.GetString("EMAIL_MESSAGING_DISPATCH_ITEM", Localization.GlobalResourceFile, portalSettings, language);
}
/// <summary>Gets the email body template.</summary>
/// <param name="language">The language.</param>
/// <returns>The email body template from the Global Resource File: EMAIL_MESSAGING_DISPATCH_BODY.</returns>
private static string GetEmailBodyTemplate(PortalSettings portalSettings, string language)
{
return Localization.GetString("EMAIL_MESSAGING_DISPATCH_BODY", Localization.GlobalResourceFile, portalSettings, language);
}
/// <summary>Gets the email subject template.</summary>
/// <param name="language">The language.</param>
/// <returns>The email subject template from the Global Resource File: EMAIL_SUBJECT_FORMAT.</returns>
private static string GetEmailSubjectTemplate(PortalSettings portalSettings, string language)
{
return Localization.GetString("EMAIL_SUBJECT_FORMAT", Localization.GlobalResourceFile, language);
}
/// <summary>Gets the friend request actions template.</summary>
/// <param name="language">The language.</param>
/// <returns>The friend request actions defined in the Global Resource File: EMAIL_SOCIAL_FRIENDREQUESTACTIONS.</returns>
private static string GetFriendRequestActionsTemplate(PortalSettings portalSettings, string language)
{
return Localization.GetString("EMAIL_SOCIAL_FRIENDREQUESTACTIONS", Localization.GlobalResourceFile, portalSettings, language);
}
/// <summary>Gets the follow request actions template.</summary>
/// <param name="language">The language.</param>
/// <returns>The follow request actions defined in the Global Resource File: EMAIL_SOCIAL_FOLLOWREQUESTACTIONS.</returns>
private static string GetFollowRequestActionsTemplate(PortalSettings portalSettings, string language)
{
return Localization.GetString("EMAIL_SOCIAL_FOLLOWREQUESTACTIONS", Localization.GlobalResourceFile, portalSettings, language);
}
/// <summary>Gets the name of the sender.</summary>
/// <param name="displayName">The display name.</param>
/// <param name="portalName">Name of the portal.</param>
/// <returns>Either the display name for the sender or the portal name.</returns>
private static string GetSenderName(string displayName, string portalName)
{
return string.IsNullOrEmpty(displayName) ? portalName : displayName;
}
/// <summary>Gets the profile pic URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>The handler url to fetch the picture for the specified userId.</returns>
private static string GetProfilePicUrl(PortalSettings portalSettings, int userId)
{
return string.Format(
"http://{0}/DnnImageHandler.ashx?mode=profilepic&userId={1}&h={2}&w={3}",
portalSettings.DefaultPortalAlias,
userId,
64,
64);
}
/// <summary>Gets the relationship accept request URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="userId">The user identifier.</param>
/// <param name="action">The action.</param>
/// <returns>The handler url to fetch the relationship picture for the specified userId.</returns>
private static string GetRelationshipAcceptRequestUrl(PortalSettings portalSettings, int userId, string action)
{
return string.Format(
"http://{0}/tabid/{1}/userId/{2}/action/{3}/{4}",
portalSettings.DefaultPortalAlias,
portalSettings.UserTabId,
userId.ToString(CultureInfo.InvariantCulture),
action,
Globals.glbDefaultPage);
}
/// <summary>Gets the profile URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>The handler url to fetch the profile picture for the specified userId.</returns>
private static string GetProfileUrl(PortalSettings portalSettings, int userId)
{
return string.Format(
"http://{0}/tabid/{1}/userId/{2}/{3}",
portalSettings.DefaultPortalAlias,
portalSettings.UserTabId,
userId.ToString(CultureInfo.InvariantCulture),
Globals.glbDefaultPage);
}
/// <summary>Gets the display name.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>The display name for the given user.</returns>
private static string GetDisplayName(PortalSettings portalSettings, int userId)
{
return (UserController.GetUserById(portalSettings.PortalId, userId) != null)
? UserController.GetUserById(portalSettings.PortalId, userId).DisplayName
: portalSettings.PortalName;
}
/// <summary>Gets the notification URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>The handler url to fetch a notification for the specified userId.</returns>
private static string GetNotificationUrl(PortalSettings portalSettings, int userId)
{
var cacheKey = string.Format("MessageCenterTab:{0}:{1}", portalSettings.PortalId, portalSettings.CultureCode);
var messageTabId = DataCache.GetCache<int>(cacheKey);
if (messageTabId <= 0)
{
messageTabId = portalSettings.UserTabId;
var profileTab = TabController.Instance.GetTab(portalSettings.UserTabId, portalSettings.PortalId, false);
if (profileTab != null)
{
var childTabs = TabController.Instance.GetTabsByPortal(profileTab.PortalID).DescendentsOf(profileTab.TabID);
foreach (var tab in childTabs)
{
foreach (var kvp in ModuleController.Instance.GetTabModules(tab.TabID))
{
var module = kvp.Value;
if (module.DesktopModule.FriendlyName == "Message Center")
{
messageTabId = tab.TabID;
break;
}
}
}
}
DataCache.SetCache(cacheKey, messageTabId, TimeSpan.FromMinutes(20));
}
return string.Format(
"http://{0}/tabid/{1}/userId/{2}/{3}#dnnCoreNotification",
portalSettings.DefaultPortalAlias,
messageTabId,
userId,
Globals.glbDefaultPage);
}
/// <summary>Gets the portal logo URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <returns>A Url to the portal logo.</returns>
private static string GetPortalLogoUrl(PortalSettings portalSettings)
{
return string.Format(
"http://{0}/{1}/{2}",
GetDomainName(portalSettings),
portalSettings.HomeDirectory,
portalSettings.LogoFile);
}
/// <summary>Gets the name of the domain.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <returns>Resolves the domain name (portal alias) for the specified portal.</returns>
private static string GetDomainName(PortalSettings portalSettings)
{
var portalAlias = portalSettings.DefaultPortalAlias;
return portalAlias.IndexOf("/", StringComparison.InvariantCulture) != -1 ?
portalAlias.Substring(0, portalAlias.IndexOf("/", StringComparison.InvariantCulture)) :
portalAlias;
}
/// <summary>Gets the portal home URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <returns>The default portal alias url.</returns>
private static string GetPortalHomeUrl(PortalSettings portalSettings)
{
return string.Format("http://{0}", portalSettings.DefaultPortalAlias);
}
/// <summary>Gets the subscriptions URL.</summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="userId">The user identifier.</param>
/// <returns>The url for viewing subscriptions.</returns>
private static string GetSubscriptionsUrl(PortalSettings portalSettings, int userId)
{
return string.Format(
"http://{0}/tabid/{1}/ctl/Profile/userId/{2}/pageno/3",
portalSettings.DefaultPortalAlias,
GetMessageTab(portalSettings),
userId);
}
/// <summary>Gets the message tab.</summary>
/// <param name="sendingPortal">The sending portal.</param>
/// <returns>The tabId for where the Message Center is installed.</returns>
private static int GetMessageTab(PortalSettings sendingPortal)
{
var cacheKey = string.Format("MessageTab:{0}", sendingPortal.PortalId);
var cacheItemArgs = new CacheItemArgs(cacheKey, 30, CacheItemPriority.Default, sendingPortal);
return CBO.GetCachedObject<int>(cacheItemArgs, GetMessageTabCallback);
}
/// <summary>Gets the message tab callback.</summary>
/// <param name="cacheItemArgs">The cache item arguments.</param>
/// <returns>The tab Id for the Message Center OR the user profile page tab Id.</returns>
private static object GetMessageTabCallback(CacheItemArgs cacheItemArgs)
{
var portalSettings = cacheItemArgs.Params[0] as PortalSettings;
var profileTab = TabController.Instance.GetTab(portalSettings.UserTabId, portalSettings.PortalId, false);
if (profileTab != null)
{
var childTabs = TabController.Instance.GetTabsByPortal(profileTab.PortalID).DescendentsOf(profileTab.TabID);
foreach (var tab in childTabs)
{
foreach (var kvp in ModuleController.Instance.GetTabModules(tab.TabID))
{
var module = kvp.Value;
if (module.DesktopModule.FriendlyName == "Message Center")
{
return tab.TabID;
}
}
}
}
// default to User Profile Page
return portalSettings.UserTabId;
}
private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHttp, PortalSettings portalSettings)
{
if (stringContainingHttp.IndexOf("http") > -1 && portalSettings != null && (portalSettings.SSLEnabled || portalSettings.SSLEnforced))
{
var urlToReplace = GetPortalHomeUrl(portalSettings);
var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}";
stringContainingHttp = stringContainingHttp.Replace(urlToReplace, urlReplaceWith);
}
return stringContainingHttp;
}
private static string ResolveUrl(PortalSettings portalSettings, string template)
{
const string linkRegex = "(href|src)=\"(/[^\"]*?)\"";
var matches = Regex.Matches(template, linkRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
var link = match.Groups[2].Value;
var defaultAlias = portalSettings.DefaultPortalAlias;
var domain = Globals.AddHTTP(defaultAlias);
if (defaultAlias.Contains("/"))
{
var subDomain =
defaultAlias.Substring(defaultAlias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase));
if (link.StartsWith(subDomain, StringComparison.InvariantCultureIgnoreCase))
{
link = link.Substring(subDomain.Length);
}
}
template = template.Replace(match.Value, $"{match.Groups[1].Value}=\"{domain}{link}\"");
}
return template;
}
/// <summary>Handles the frequent digests.</summary>
/// <param name="schedulerInstance">The scheduler instance.</param>
/// <param name="remainingMessages">The remaining messages.</param>
private void HandleFrequentDigests(Guid schedulerInstance, int remainingMessages)
{
var handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddHours(-1), SettingLastHourlyRun, Frequency.Hourly, schedulerInstance, remainingMessages);
remainingMessages = remainingMessages - handledMessages;
handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddDays(-1), SettingLastDailyRun, Frequency.Daily, schedulerInstance, remainingMessages);
remainingMessages = remainingMessages - handledMessages;
handledMessages = this.HandleFrequencyDigest(DateTime.Now.AddDays(-7), SettingLastWeeklyRun, Frequency.Weekly, schedulerInstance, remainingMessages);
remainingMessages = remainingMessages - handledMessages;
this.HandleFrequencyDigest(DateTime.Now.AddDays(-30), SettingLastMonthlyRun, Frequency.Monthly, schedulerInstance, remainingMessages);
}
/// <summary>Handles the frequency digest.</summary>
/// <param name="dateToCompare">The date to compare.</param>
/// <param name="settingKeyLastRunDate">The setting key last run date.</param>
/// <param name="frequency">The frequency.</param>
/// <param name="schedulerInstance">The scheduler instance.</param>
/// <param name="remainingMessages">The remaining messages.</param>
/// <returns>The count of messages processed.</returns>
private int HandleFrequencyDigest(DateTime dateToCompare, string settingKeyLastRunDate, Frequency frequency, Guid schedulerInstance, int remainingMessages)
{
int handledMessages = 0;
if (remainingMessages <= 0)
{
return handledMessages;
}
var lastRunDate = this.GetScheduleItemDateSetting(settingKeyLastRunDate);
if (dateToCompare >= lastRunDate)
{
handledMessages = this.HandleDigest(schedulerInstance, frequency, remainingMessages);
if (handledMessages < remainingMessages)
{
SchedulingProvider.Instance().AddScheduleItemSetting(
this.ScheduleHistoryItem.ScheduleID, settingKeyLastRunDate, DateTime.Now.ToString(CultureInfo.InvariantCulture));
}
}
return handledMessages;
}
/// <summary>Handles the digest.</summary>
/// <param name="schedulerInstance">The scheduler instance.</param>
/// <param name="frequency">The frequency.</param>
/// <param name="remainingMessages">The remaining messages.</param>
/// <returns>The count of messages processed.</returns>
private int HandleDigest(Guid schedulerInstance, Frequency frequency, int remainingMessages)
{
var messagesSent = 0;
// get subscribers based on frequency, utilize remaining batch size as part of count of users to return (note, if multiple subscriptions have the same frequency they will be combined into 1 email)
this.ScheduleHistoryItem.AddLogNote("<br>Messaging Scheduler Starting Digest '" + schedulerInstance + "'. ");
var messageLeft = true;
while (messageLeft)
{
var batchMessages = InternalMessagingController.Instance.GetNextMessagesForDigestDispatch(frequency, schedulerInstance, remainingMessages);
if (batchMessages != null && batchMessages.Count > 0)
{
try
{
foreach (var userId in (from t in batchMessages select t.UserID).Distinct())
{
var currentUserId = userId;
var colUserMessages = from t in batchMessages where t.UserID == currentUserId select t;
var messageRecipients = colUserMessages as MessageRecipient[] ?? colUserMessages.ToArray();
var singleMessage = (from t in messageRecipients select t).First();
if (singleMessage != null)
{
var messageDetails = InternalMessagingController.Instance.GetMessage(singleMessage.MessageID);
var portalSettings = new PortalSettings(messageDetails.PortalID);
var senderUser = UserController.Instance.GetUser(messageDetails.PortalID, messageDetails.SenderUserID);
var recipientUser = UserController.Instance.GetUser(messageDetails.PortalID, singleMessage.UserID);
this.SendDigest(messageRecipients, portalSettings, senderUser, recipientUser);
}
messagesSent = messagesSent + 1;
}
// at this point we have sent all digest notifications for this batch
this.ScheduleHistoryItem.AddLogNote("Sent " + messagesSent + " digest subscription emails for this batch. ");
return messagesSent;
}
catch (Exception e)
{
this.Errored(ref e);
}
}
else
{
messageLeft = false;
}
}
this.ScheduleHistoryItem.AddLogNote("Sent " + messagesSent + " " + frequency + " digest subscription emails. ");
return messagesSent;
}
/// <summary>Sends the digest.</summary>
/// <param name="messages">The messages.</param>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="senderUser">The sender user.</param>
/// <param name="recipientUser">The recipient user.</param>
private void SendDigest(IEnumerable<MessageRecipient> messages, PortalSettings portalSettings, UserInfo senderUser, UserInfo recipientUser)
{
var messageRecipients = messages as MessageRecipient[] ?? messages.ToArray();
if (!IsUserAbleToReceiveAnEmail(recipientUser))
{
MarkMessagesAsDispatched(messageRecipients);
return;
}
if (!IsSendEmailEnable(portalSettings.PortalId))
{
MarkMessagesAsDispatched(messageRecipients);
return;
}
var defaultLanguage = recipientUser.Profile.PreferredLocale;
var emailSubjectTemplate = GetEmailSubjectTemplate(portalSettings, defaultLanguage);
var emailBodyTemplate = GetEmailBodyTemplate(portalSettings, defaultLanguage);
var emailBodyItemTemplate = GetEmailBodyItemTemplate(portalSettings, defaultLanguage);
var emailBodyItemContent = messageRecipients.Aggregate(
string.Empty,
(current, message) => current + GetEmailItemContent(portalSettings, message, emailBodyItemTemplate));
var fromAddress = portalSettings.Email;
var toAddress = recipientUser.Email;
var senderName = GetSenderName(senderUser.DisplayName, portalSettings.PortalName);
var senderAddress = GetSenderAddress(senderName, fromAddress);
var subject = string.Format(emailSubjectTemplate, portalSettings.PortalName);
var body = GetEmailBody(emailBodyTemplate, emailBodyItemContent, portalSettings, recipientUser);
body = RemoveHttpUrlsIfSiteisSSLEnabled(body, portalSettings);
Mail.Mail.SendEmail(fromAddress, senderAddress, toAddress, subject, body);
MarkMessagesAsDispatched(messageRecipients);
}
/// <summary>Gets the schedule item date setting.</summary>
/// <param name="settingKey">The setting key.</param>
/// <returns>The date the schedule was ran.</returns>
private DateTime GetScheduleItemDateSetting(string settingKey)
{
var colScheduleItemSettings = SchedulingProvider.Instance().GetScheduleItemSettings(this.ScheduleHistoryItem.ScheduleID);
var dateValue = DateTime.Now;
if (colScheduleItemSettings.Count > 0)
{
if (colScheduleItemSettings.ContainsKey(settingKey))
{
dateValue = Convert.ToDateTime(colScheduleItemSettings[settingKey], CultureInfo.InvariantCulture);
}
}
else
{
SchedulingProvider.Instance().AddScheduleItemSetting(
this.ScheduleHistoryItem.ScheduleID, SettingLastHourlyRun, dateValue.ToString(CultureInfo.InvariantCulture));
SchedulingProvider.Instance().AddScheduleItemSetting(
this.ScheduleHistoryItem.ScheduleID, SettingLastDailyRun, dateValue.ToString(CultureInfo.InvariantCulture));
SchedulingProvider.Instance().AddScheduleItemSetting(
this.ScheduleHistoryItem.ScheduleID, SettingLastWeeklyRun, dateValue.ToString(CultureInfo.InvariantCulture));
SchedulingProvider.Instance().AddScheduleItemSetting(
this.ScheduleHistoryItem.ScheduleID, SettingLastMonthlyRun, dateValue.ToString(CultureInfo.InvariantCulture));
}
return dateValue;
}
/// <summary>Handles the sending of messages.</summary>
/// <param name="schedulerInstance">The scheduler instance.</param>
/// <returns>The count of messages sent.</returns>
private int HandleInstantMessages(Guid schedulerInstance)
{
var messageLeft = true;
var messagesSent = 0;
while (messageLeft)
{
var batchMessages = InternalMessagingController.Instance.GetNextMessagesForInstantDispatch(schedulerInstance, Host.MessageSchedulerBatchSize);
if (batchMessages != null && batchMessages.Count > 0)
{
try
{
foreach (var messageRecipient in batchMessages)
{
this.SendMessage(messageRecipient);
messagesSent = messagesSent + 1;
}
}
catch (Exception e)
{
this.Errored(ref e);
}
}
else
{
messageLeft = false;
}
}
this.ScheduleHistoryItem.AddLogNote(string.Format("<br>Messaging Scheduler '{0}' sent a total of {1} message(s)", schedulerInstance, messagesSent));
return messagesSent;
}
/// <summary>Sends the message and attachments if configured to include them.</summary>
/// <param name="messageRecipient">The message recipient.</param>
private void SendMessage(MessageRecipient messageRecipient)
{
var message = InternalMessagingController.Instance.GetMessage(messageRecipient.MessageID);
var toUser = UserController.Instance.GetUser(message.PortalID, messageRecipient.UserID);
if (!IsUserAbleToReceiveAnEmail(toUser))
{
InternalMessagingController.Instance.MarkMessageAsDispatched(messageRecipient.MessageID, messageRecipient.RecipientID);
return;
}
if (!IsSendEmailEnable(message.PortalID))
{
InternalMessagingController.Instance.MarkMessageAsSent(messageRecipient.MessageID, messageRecipient.RecipientID);
return;
}
var defaultLanguage = toUser.Profile.PreferredLocale;
var portalSettings = new PortalSettings(message.PortalID);
var emailSubjectTemplate = GetEmailSubjectTemplate(portalSettings, defaultLanguage);
var emailBodyTemplate = GetEmailBodyTemplate(portalSettings, defaultLanguage);
var emailBodyItemTemplate = GetEmailBodyItemTemplate(portalSettings, defaultLanguage);
var author = UserController.Instance.GetUser(message.PortalID, message.SenderUserID);
var fromAddress = (UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email) != null) ?
string.Format("{0} < {1} >", UserController.GetUserByEmail(portalSettings.PortalId, portalSettings.Email).DisplayName, portalSettings.Email) : portalSettings.Email;
var toAddress = toUser.Email;
if (Mail.Mail.IsValidEmailAddress(toUser.Email, toUser.PortalID))
{
var senderName = GetSenderName(author.DisplayName, portalSettings.PortalName);
var senderAddress = GetSenderAddress(senderName, portalSettings.Email);
var emailBodyItemContent = GetEmailItemContent(portalSettings, messageRecipient, emailBodyItemTemplate);
var subject = string.Format(emailSubjectTemplate, portalSettings.PortalName);
var body = GetEmailBody(emailBodyTemplate, emailBodyItemContent, portalSettings, toUser);
body = RemoveHttpUrlsIfSiteisSSLEnabled(body, portalSettings);
// Include the attachment in the email message if configured to do so
if (InternalMessagingController.Instance.AttachmentsAllowed(message.PortalID))
{
Mail.Mail.SendEmail(fromAddress, senderAddress, toAddress, subject, body, this.CreateAttachments(message.MessageID).ToList());
}
else
{
Mail.Mail.SendEmail(fromAddress, senderAddress, toAddress, subject, body);
}
}
InternalMessagingController.Instance.MarkMessageAsDispatched(messageRecipient.MessageID, messageRecipient.RecipientID);
}
/// <summary>Creates list of attachments for the specified message.</summary>
/// <param name="messageId">The message identifier.</param>
/// <returns>A list of attachments.</returns>
private IEnumerable<Attachment> CreateAttachments(int messageId)
{
foreach (var fileView in InternalMessagingController.Instance.GetAttachments(messageId))
{
var file = FileManager.Instance.GetFile(fileView.FileId);
var fileContent = FileManager.Instance.GetFileContent(file);
if (file != null)
{
yield return new Attachment(fileContent, file.ContentType);
}
}
}
}
}
| |
/*
* Author: Faraz Masood Khan
*
* Date: Saturday, July 31, 2010 2:21 AM
*
* Class: Channel
*
* Email: mk.faraz@gmail.com
*
* Blogs: http://csharplive.wordpress.com, http://farazmasoodkhan.wordpress.com
*
* Website: http://www.linkedin.com/in/farazmasoodkhan
*
* Copyright: Faraz Masood Khan @ Copyright 2010
*
/*/
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Collections.Specialized;
using CoreSystem.RefTypeExtension;
namespace Feedbook.Model
{
[DataContract]
internal class Channel : Entity
{
#region Declarations
protected string channelId = default(string);
protected FeedType feedtype = default(FeedType);
protected string downloadUrl = default(string);
protected string language = default(string);
protected string copyright = default(string);
protected DateTime updated = default(DateTime);
protected DateTime published = default(DateTime);
protected int rating = default(int);
protected string generator = default(string);
protected int ttl = default(int);
protected bool downloadpodcast = default(bool);
protected bool isSynchronizing;
protected int newFeedCount;
protected Content title;
protected Content description;
protected Icon icon;
private ObservableCollection<Feed> feeds;
#endregion
#region Properties
[DataMember]
public string ChannelId
{
get { return this.channelId; }
set
{
if (this.channelId != value)
{
this.channelId = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("ChannelId"));
}
}
}
[DataMember]
public FeedType FeedType
{
get { return this.feedtype; }
set
{
if (this.feedtype != value)
{
this.feedtype = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("FeedType"));
}
}
}
[DataMember]
public string DownloadUrl
{
get { return this.downloadUrl; }
set
{
if (this.downloadUrl != value)
{
this.downloadUrl = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("DownloadUrl"));
}
}
}
[DataMember]
public string Language
{
get { return this.language; }
set
{
if (this.language != value)
{
this.language = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Language"));
}
}
}
[DataMember]
public string Copyrights
{
get { return this.copyright; }
set
{
if (this.copyright != value)
{
this.copyright = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Copyrights"));
}
}
}
[DataMember]
public DateTime Updated
{
get { return this.updated; }
set
{
if (this.updated != value)
{
this.updated = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Updated"));
}
}
}
[DataMember]
public DateTime Published
{
get { return this.published; }
set
{
if (this.published != value)
{
this.published = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Published"));
}
}
}
[DataMember]
public int Rating
{
get { return this.rating; }
set
{
if (this.rating != value)
{
this.rating = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Rating"));
}
}
}
[DataMember]
public string Generator
{
get { return this.generator; }
set
{
if (this.generator != value)
{
this.generator = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Generator"));
}
}
}
[DataMember]
public int Ttl
{
get { return this.ttl; }
set
{
if (this.ttl != value)
{
this.ttl = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Ttl"));
}
}
}
[DataMember]
public bool DownloadPodcasts
{
get { return this.downloadpodcast; }
set
{
if (this.downloadpodcast != value)
{
this.downloadpodcast = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("DownloadPodcasts"));
}
}
}
[DataMember]
public Content Title
{
get { return this.title; }
set
{
if (this.title != value)
{
this.title = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Title"));
}
}
}
[DataMember]
public Content Description
{
get { return this.description; }
set
{
if (this.description != value)
{
this.description = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Description"));
}
}
}
[DataMember]
public Icon Icon
{
get { return this.icon; }
set
{
if (this.icon != value)
{
this.icon = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Icon"));
}
}
}
[IgnoreDataMember]
public bool IsSynchronizing
{
get { return this.isSynchronizing; }
set
{
if (this.isSynchronizing != value)
{
this.isSynchronizing = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("IsSynchronizing"));
}
}
}
[IgnoreDataMember]
public int NewFeedCount
{
get { return this.newFeedCount; }
set
{
if (this.newFeedCount != value)
{
this.newFeedCount = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("NewFeedCount"));
}
}
}
public bool IsTwitterSearch
{
get
{
string downloadUrl = this.DownloadUrl;
return downloadUrl != null && downloadUrl.StartsWith("http://search.twitter.com/search.atom");
}
}
[DataMember]
public ObservableCollection<Feed> Feeds
{
get { return this.feeds; }
set
{
this.feeds.Clear();
if (value != null)
this.feeds.AddRange(value);
}
}
[DataMember]
public ObservableCollection<DayOfWeek> SkipDays { get; set; }
[DataMember]
public ObservableCollection<int> SkipHours { get; set; }
[DataMember]
public ObservableCollection<Category> Categories { get; set; }
[DataMember]
public ObservableCollection<Link> Links { get; set; }
[DataMember]
public ObservableCollection<Person> People { get; set; }
#endregion
#region Methods
public Channel()
{
this.Initialized(new StreamingContext());
}
[OnDeserializing]
private void Initialized(StreamingContext context)
{
this.SkipDays = new ObservableCollection<DayOfWeek>();
this.SkipHours = new ObservableCollection<int>();
this.Categories = new ObservableCollection<Category>();
this.Links = new ObservableCollection<Link>();
this.People = new ObservableCollection<Person>();
this.feeds = new ObservableCollection<Feed>();
this.feeds.CollectionChanged += (sender, e) =>
{
if (e.NewItems != null)
foreach (Feed feed in e.NewItems)
feed.Channel = this;
if (e.OldItems != null)
foreach (Feed feed in e.OldItems)
feed.Channel = null;
};
}
#endregion
}
}
| |
// 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.
// File System.Windows.Controls.ItemCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
sealed public partial class ItemCollection : System.Windows.Data.CollectionView, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable, System.ComponentModel.IEditableCollectionViewAddNewItem, System.ComponentModel.IEditableCollectionView, System.ComponentModel.IItemProperties, System.Windows.IWeakEventListener
{
#region Methods and constructors
public int Add(Object newItem)
{
return default(int);
}
public void Clear()
{
}
public override bool Contains(Object containItem)
{
return default(bool);
}
public void CopyTo(Array array, int index)
{
}
public override IDisposable DeferRefresh()
{
return default(IDisposable);
}
protected override System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public override Object GetItemAt(int index)
{
return default(Object);
}
public override int IndexOf(Object item)
{
return default(int);
}
public void Insert(int insertIndex, Object insertItem)
{
}
internal ItemCollection() : base (default(System.Collections.IEnumerable))
{
}
public override bool MoveCurrentTo(Object item)
{
return default(bool);
}
public override bool MoveCurrentToFirst()
{
return default(bool);
}
public override bool MoveCurrentToLast()
{
return default(bool);
}
public override bool MoveCurrentToNext()
{
return default(bool);
}
public override bool MoveCurrentToPosition(int position)
{
return default(bool);
}
public override bool MoveCurrentToPrevious()
{
return default(bool);
}
public override bool PassesFilter(Object item)
{
return default(bool);
}
protected override void RefreshOverride()
{
}
public void Remove(Object removeItem)
{
}
public void RemoveAt(int removeIndex)
{
}
Object System.ComponentModel.IEditableCollectionView.AddNew()
{
return default(Object);
}
void System.ComponentModel.IEditableCollectionView.CancelEdit()
{
}
void System.ComponentModel.IEditableCollectionView.CancelNew()
{
}
void System.ComponentModel.IEditableCollectionView.CommitEdit()
{
}
void System.ComponentModel.IEditableCollectionView.CommitNew()
{
}
void System.ComponentModel.IEditableCollectionView.EditItem(Object item)
{
}
void System.ComponentModel.IEditableCollectionView.Remove(Object item)
{
}
void System.ComponentModel.IEditableCollectionView.RemoveAt(int index)
{
}
Object System.ComponentModel.IEditableCollectionViewAddNewItem.AddNewItem(Object newItem)
{
return default(Object);
}
bool System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
{
return default(bool);
}
#endregion
#region Properties and indexers
public override bool CanFilter
{
get
{
return default(bool);
}
}
public override bool CanGroup
{
get
{
return default(bool);
}
}
public override bool CanSort
{
get
{
return default(bool);
}
}
public override int Count
{
get
{
return default(int);
}
}
public override Object CurrentItem
{
get
{
return default(Object);
}
}
public override int CurrentPosition
{
get
{
return default(int);
}
}
public override Predicate<Object> Filter
{
get
{
return default(Predicate<Object>);
}
set
{
}
}
public override System.Collections.ObjectModel.ObservableCollection<System.ComponentModel.GroupDescription> GroupDescriptions
{
get
{
return default(System.Collections.ObjectModel.ObservableCollection<System.ComponentModel.GroupDescription>);
}
}
public override System.Collections.ObjectModel.ReadOnlyObservableCollection<Object> Groups
{
get
{
return default(System.Collections.ObjectModel.ReadOnlyObservableCollection<Object>);
}
}
public override bool IsCurrentAfterLast
{
get
{
return default(bool);
}
}
public override bool IsCurrentBeforeFirst
{
get
{
return default(bool);
}
}
public override bool IsEmpty
{
get
{
return default(bool);
}
}
public Object this [int index]
{
get
{
return default(Object);
}
set
{
}
}
public override bool NeedsRefresh
{
get
{
return default(bool);
}
}
public override System.ComponentModel.SortDescriptionCollection SortDescriptions
{
get
{
return default(System.ComponentModel.SortDescriptionCollection);
}
}
public override System.Collections.IEnumerable SourceCollection
{
get
{
return default(System.Collections.IEnumerable);
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return default(bool);
}
}
Object System.Collections.ICollection.SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IList.IsFixedSize
{
get
{
return default(bool);
}
}
bool System.Collections.IList.IsReadOnly
{
get
{
return default(bool);
}
}
bool System.ComponentModel.IEditableCollectionView.CanAddNew
{
get
{
return default(bool);
}
}
bool System.ComponentModel.IEditableCollectionView.CanCancelEdit
{
get
{
return default(bool);
}
}
bool System.ComponentModel.IEditableCollectionView.CanRemove
{
get
{
return default(bool);
}
}
Object System.ComponentModel.IEditableCollectionView.CurrentAddItem
{
get
{
return default(Object);
}
}
Object System.ComponentModel.IEditableCollectionView.CurrentEditItem
{
get
{
return default(Object);
}
}
bool System.ComponentModel.IEditableCollectionView.IsAddingNew
{
get
{
return default(bool);
}
}
bool System.ComponentModel.IEditableCollectionView.IsEditingItem
{
get
{
return default(bool);
}
}
System.ComponentModel.NewItemPlaceholderPosition System.ComponentModel.IEditableCollectionView.NewItemPlaceholderPosition
{
get
{
return default(System.ComponentModel.NewItemPlaceholderPosition);
}
set
{
}
}
bool System.ComponentModel.IEditableCollectionViewAddNewItem.CanAddNewItem
{
get
{
return default(bool);
}
}
System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.ItemPropertyInfo> System.ComponentModel.IItemProperties.ItemProperties
{
get
{
return default(System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.ItemPropertyInfo>);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using AutoRest.Core;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger
{
/// <summary>
/// The builder for building a generic swagger object into parameters,
/// service types or Json serialization types.
/// </summary>
public class ObjectBuilder
{
protected SwaggerObject SwaggerObject { get; set; }
protected SwaggerModeler Modeler { get; set; }
public ObjectBuilder(SwaggerObject swaggerObject, SwaggerModeler modeler)
{
SwaggerObject = swaggerObject;
Modeler = modeler;
}
public virtual IType ParentBuildServiceType(string serviceTypeName)
{
// Should not try to get parent from generic swagger object builder
throw new InvalidOperationException();
}
/// <summary>
/// The visitor method for building service types. This is called when an instance of this class is
/// visiting a _swaggerModeler to build a service type.
/// </summary>
/// <param name="serviceTypeName">name for the service type</param>
/// <returns>built service type</returns>
public virtual IType BuildServiceType(string serviceTypeName)
{
PrimaryType type = SwaggerObject.ToType();
Debug.Assert(type != null);
if (type.Type == KnownPrimaryType.Object && "file".Equals(SwaggerObject.Format, StringComparison.OrdinalIgnoreCase))
{
type = new PrimaryType(KnownPrimaryType.Stream);
}
type.Format = SwaggerObject.Format;
if (SwaggerObject.Enum != null && type.Type == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject)))
{
var enumType = new EnumType();
SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue { Name = v, SerializedName = v }));
if (SwaggerObject.Extensions.ContainsKey(CodeGenerator.EnumObject))
{
var enumObject = SwaggerObject.Extensions[CodeGenerator.EnumObject] as Newtonsoft.Json.Linq.JContainer;
if (enumObject != null)
{
enumType.Name= enumObject["name"].ToString();
if (enumObject["modelAsString"] != null)
{
enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString());
}
}
enumType.SerializedName = enumType.Name;
if (string.IsNullOrEmpty(enumType.Name))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
"{0} extension needs to specify an enum name.",
CodeGenerator.EnumObject));
}
var existingEnum =
Modeler.ServiceClient.EnumTypes.FirstOrDefault(
e => e.Name.Equals(enumType.Name, StringComparison.OrdinalIgnoreCase));
if (existingEnum != null)
{
if (!existingEnum.Equals(enumType))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
"Swagger document contains two or more {0} extensions with the same name '{1}' and different values.",
CodeGenerator.EnumObject,
enumType.Name));
}
}
else
{
Modeler.ServiceClient.EnumTypes.Add(enumType);
}
}
else
{
enumType.ModelAsString = true;
enumType.Name = string.Empty;
enumType.SerializedName = string.Empty;
}
return enumType;
}
if (SwaggerObject.Type == DataType.Array)
{
string itemServiceTypeName;
if (SwaggerObject.Items.Reference != null)
{
itemServiceTypeName = SwaggerObject.Items.Reference.StripDefinitionPath();
}
else
{
itemServiceTypeName = serviceTypeName + "Item";
}
var elementType =
SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName);
return new SequenceType
{
ElementType = elementType
};
}
if (SwaggerObject.AdditionalProperties != null)
{
string dictionaryValueServiceTypeName;
if (SwaggerObject.AdditionalProperties.Reference != null)
{
dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath();
}
else
{
dictionaryValueServiceTypeName = serviceTypeName + "Value";
}
return new DictionaryType
{
ValueType =
SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
.BuildServiceType((dictionaryValueServiceTypeName))
};
}
return type;
}
public static void PopulateParameter(IParameter parameter, SwaggerObject swaggerObject)
{
if (swaggerObject == null)
{
throw new ArgumentNullException("swaggerObject");
}
if (parameter == null)
{
throw new ArgumentNullException("parameter");
}
parameter.IsRequired = swaggerObject.IsRequired;
parameter.DefaultValue = swaggerObject.Default;
if (IsSwaggerObjectConstant(swaggerObject))
{
parameter.DefaultValue = swaggerObject.Enum[0];
parameter.IsConstant = true;
}
var compositeType = parameter.Type as CompositeType;
if (compositeType != null && compositeType.ComposedProperties.Any())
{
if (compositeType.ComposedProperties.All(p => p.IsConstant))
{
parameter.DefaultValue = "{}";
parameter.IsConstant = true;
}
}
parameter.Documentation = swaggerObject.Description;
parameter.CollectionFormat = swaggerObject.CollectionFormat;
var enumType = parameter.Type as EnumType;
if (enumType != null)
{
if (parameter.Documentation == null)
{
parameter.Documentation = string.Empty;
}
else
{
parameter.Documentation = parameter.Documentation.TrimEnd('.') + ". ";
}
parameter.Documentation += "Possible values include: " +
string.Join(", ", enumType.Values.Select(v =>
string.Format(CultureInfo.InvariantCulture,
"'{0}'", v.Name)));
}
swaggerObject.Extensions.ForEach(e => parameter.Extensions[e.Key] = e.Value);
SetConstraints(parameter.Constraints, swaggerObject);
}
private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject)
{
return (swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && swaggerObject.IsRequired);
}
public static void SetConstraints(Dictionary<Constraint, string> constraints, SwaggerObject swaggerObject)
{
if (constraints == null)
{
throw new ArgumentNullException("constraints");
}
if (swaggerObject == null)
{
throw new ArgumentNullException("swaggerObject");
}
if (!string.IsNullOrEmpty(swaggerObject.Maximum) && !swaggerObject.ExclusiveMaximum)
{
constraints[Constraint.InclusiveMaximum] = swaggerObject.Maximum;
}
if (!string.IsNullOrEmpty(swaggerObject.Maximum) && swaggerObject.ExclusiveMaximum)
{
constraints[Constraint.ExclusiveMaximum] = swaggerObject.Maximum;
}
if (!string.IsNullOrEmpty(swaggerObject.Minimum) && !swaggerObject.ExclusiveMinimum)
{
constraints[Constraint.InclusiveMinimum] = swaggerObject.Minimum;
}
if (!string.IsNullOrEmpty(swaggerObject.Minimum) && swaggerObject.ExclusiveMinimum)
{
constraints[Constraint.ExclusiveMinimum] = swaggerObject.Minimum;
}
if (!string.IsNullOrEmpty(swaggerObject.MaxLength))
{
constraints[Constraint.MaxLength] = swaggerObject.MaxLength;
}
if (!string.IsNullOrEmpty(swaggerObject.MinLength))
{
constraints[Constraint.MinLength] = swaggerObject.MinLength;
}
if (!string.IsNullOrEmpty(swaggerObject.Pattern))
{
constraints[Constraint.Pattern] = swaggerObject.Pattern;
}
if (!string.IsNullOrEmpty(swaggerObject.MaxItems))
{
constraints[Constraint.MaxItems] = swaggerObject.MaxItems;
}
if (!string.IsNullOrEmpty(swaggerObject.MinItems))
{
constraints[Constraint.MinItems] = swaggerObject.MinItems;
}
if (!string.IsNullOrEmpty(swaggerObject.MultipleOf))
{
constraints[Constraint.MultipleOf] = swaggerObject.MultipleOf;
}
if (swaggerObject.UniqueItems)
{
constraints[Constraint.UniqueItems] = "true";
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a VPN connection.
/// </summary>
public partial class VpnConnection
{
private string _customerGatewayConfiguration;
private string _customerGatewayId;
private VpnConnectionOptions _options;
private List<VpnStaticRoute> _routes = new List<VpnStaticRoute>();
private VpnState _state;
private List<Tag> _tags = new List<Tag>();
private GatewayType _type;
private List<VgwTelemetry> _vgwTelemetry = new List<VgwTelemetry>();
private string _vpnConnectionId;
private string _vpnGatewayId;
/// <summary>
/// Gets and sets the property CustomerGatewayConfiguration.
/// <para>
/// The configuration information for the VPN connection's customer gateway (in the native
/// XML format). This element is always present in the <a>CreateVpnConnection</a> response;
/// however, it's present in the <a>DescribeVpnConnections</a> response only if the VPN
/// connection is in the <code>pending</code> or <code>available</code> state.
/// </para>
/// </summary>
public string CustomerGatewayConfiguration
{
get { return this._customerGatewayConfiguration; }
set { this._customerGatewayConfiguration = value; }
}
// Check to see if CustomerGatewayConfiguration property is set
internal bool IsSetCustomerGatewayConfiguration()
{
return this._customerGatewayConfiguration != null;
}
/// <summary>
/// Gets and sets the property CustomerGatewayId.
/// <para>
/// The ID of the customer gateway at your end of the VPN connection.
/// </para>
/// </summary>
public string CustomerGatewayId
{
get { return this._customerGatewayId; }
set { this._customerGatewayId = value; }
}
// Check to see if CustomerGatewayId property is set
internal bool IsSetCustomerGatewayId()
{
return this._customerGatewayId != null;
}
/// <summary>
/// Gets and sets the property Options.
/// <para>
/// The VPN connection options.
/// </para>
/// </summary>
public VpnConnectionOptions Options
{
get { return this._options; }
set { this._options = value; }
}
// Check to see if Options property is set
internal bool IsSetOptions()
{
return this._options != null;
}
/// <summary>
/// Gets and sets the property Routes.
/// <para>
/// The static routes associated with the VPN connection.
/// </para>
/// </summary>
public List<VpnStaticRoute> Routes
{
get { return this._routes; }
set { this._routes = value; }
}
// Check to see if Routes property is set
internal bool IsSetRoutes()
{
return this._routes != null && this._routes.Count > 0;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The current state of the VPN connection.
/// </para>
/// </summary>
public VpnState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Any tags assigned to the VPN connection.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The type of VPN connection.
/// </para>
/// </summary>
public GatewayType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property VgwTelemetry.
/// <para>
/// Information about the VPN tunnel.
/// </para>
/// </summary>
public List<VgwTelemetry> VgwTelemetry
{
get { return this._vgwTelemetry; }
set { this._vgwTelemetry = value; }
}
// Check to see if VgwTelemetry property is set
internal bool IsSetVgwTelemetry()
{
return this._vgwTelemetry != null && this._vgwTelemetry.Count > 0;
}
/// <summary>
/// Gets and sets the property VpnConnectionId.
/// <para>
/// The ID of the VPN connection.
/// </para>
/// </summary>
public string VpnConnectionId
{
get { return this._vpnConnectionId; }
set { this._vpnConnectionId = value; }
}
// Check to see if VpnConnectionId property is set
internal bool IsSetVpnConnectionId()
{
return this._vpnConnectionId != null;
}
/// <summary>
/// Gets and sets the property VpnGatewayId.
/// <para>
/// The ID of the virtual private gateway at the AWS side of the VPN connection.
/// </para>
/// </summary>
public string VpnGatewayId
{
get { return this._vpnGatewayId; }
set { this._vpnGatewayId = value; }
}
// Check to see if VpnGatewayId property is set
internal bool IsSetVpnGatewayId()
{
return this._vpnGatewayId != null;
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics.Contacts;
using Duality;
namespace FarseerPhysics.Dynamics
{
[Flags]
public enum Category
{
None = 0,
All = int.MaxValue,
Cat1 = 1,
Cat2 = 2,
Cat3 = 4,
Cat4 = 8,
Cat5 = 16,
Cat6 = 32,
Cat7 = 64,
Cat8 = 128,
Cat9 = 256,
Cat10 = 512,
Cat11 = 1024,
Cat12 = 2048,
Cat13 = 4096,
Cat14 = 8192,
Cat15 = 16384,
Cat16 = 32768,
Cat17 = 65536,
Cat18 = 131072,
Cat19 = 262144,
Cat20 = 524288,
Cat21 = 1048576,
Cat22 = 2097152,
Cat23 = 4194304,
Cat24 = 8388608,
Cat25 = 16777216,
Cat26 = 33554432,
Cat27 = 67108864,
Cat28 = 134217728,
Cat29 = 268435456,
Cat30 = 536870912,
Cat31 = 1073741824
}
/// <summary>
/// This proxy is used internally to connect fixtures to the broad-phase.
/// </summary>
public struct FixtureProxy
{
public AABB AABB;
public int ChildIndex;
public Fixture Fixture;
public int ProxyId;
}
/// <summary>
/// A fixture is used to attach a Shape to a body for collision detection. A fixture
/// inherits its transform from its parent. Fixtures hold additional non-geometric data
/// such as friction, collision filters, etc.
/// Fixtures are created via Body.CreateFixture.
/// Warning: You cannot reuse fixtures.
/// </summary>
public class Fixture : IDisposable
{
private static int _fixtureIdCounter;
public FixtureProxy[] Proxies;
public int ProxyCount;
internal Category _collidesWith;
internal Category _collisionCategories;
internal short _collisionGroup;
internal Dictionary<int, bool> _collisionIgnores;
private float _friction;
private float _restitution;
internal Fixture()
{
}
public Fixture(Body body, Shape shape)
: this(body, shape, null)
{
}
public Fixture(Body body, Shape shape, object userData)
{
if (Settings.UseFPECollisionCategories)
this._collisionCategories = Category.All;
else
this._collisionCategories = Category.Cat1;
this._collidesWith = Category.All;
this._collisionGroup = 0;
//Fixture defaults
this.Friction = 0.2f;
this.Restitution = 0;
this.IsSensor = false;
this.Body = body;
this.UserData = userData;
this.Shape = shape.Clone();
RegisterFixture();
}
/// <summary>
/// Defaults to 0
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Collision groups allow a certain group of objects to never collide (negative)
/// or always collide (positive). Zero means no collision group. Non-zero group
/// filtering always wins against the mask bits.
///
/// If Settings.UseFPECollisionCategories is set to true:
/// If 2 fixtures are in the same collision group, they will not collide.
/// </summary>
public short CollisionGroup
{
set
{
if (this._collisionGroup == value)
return;
this._collisionGroup = value;
Refilter();
}
get { return this._collisionGroup; }
}
/// <summary>
/// Defaults to Category.All
///
/// The collision mask bits. This states the categories that this
/// fixture would accept for collision.
/// Use Settings.UseFPECollisionCategories to change the behavior.
/// </summary>
public Category CollidesWith
{
get { return this._collidesWith; }
set
{
if (this._collidesWith == value)
return;
this._collidesWith = value;
Refilter();
}
}
/// <summary>
/// The collision categories this fixture is a part of.
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Defaults to Category.Cat1
///
/// If Settings.UseFPECollisionCategories is set to true:
/// Defaults to Category.All
/// </summary>
public Category CollisionCategories
{
get { return this._collisionCategories; }
set
{
if (this._collisionCategories == value)
return;
this._collisionCategories = value;
Refilter();
}
}
/// <summary>
/// Get the type of the child Shape. You can use this to down cast to the concrete Shape.
/// </summary>
/// <value>The type of the shape.</value>
public ShapeType ShapeType
{
get { return this.Shape.ShapeType; }
}
/// <summary>
/// Get the child Shape. You can modify the child Shape, however you should not change the
/// number of vertices because this will crash some collision caching mechanisms.
/// </summary>
/// <value>The shape.</value>
public Shape Shape { get; internal set; }
/// <summary>
/// Gets or sets a value indicating whether this fixture is a sensor.
/// </summary>
/// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
public bool IsSensor { get; set; }
/// <summary>
/// Get the parent body of this fixture. This is null if the fixture is not attached.
/// </summary>
/// <value>The body.</value>
public Body Body { get; internal set; }
/// <summary>
/// Set the user data. Use this to store your application specific data.
/// </summary>
/// <value>The user data.</value>
public object UserData { get; set; }
/// <summary>
/// Get or set the coefficient of friction.
/// </summary>
/// <value>The friction.</value>
public float Friction
{
get { return this._friction; }
set
{
Debug.Assert(!float.IsNaN(value));
this._friction = value;
}
}
/// <summary>
/// Get or set the coefficient of restitution.
/// </summary>
/// <value>The restitution.</value>
public float Restitution
{
get { return this._restitution; }
set
{
Debug.Assert(!float.IsNaN(value));
this._restitution = value;
}
}
/// <summary>
/// Gets a unique ID for this fixture.
/// </summary>
/// <value>The fixture id.</value>
public int FixtureId { get; private set; }
#region IDisposable Members
public bool IsDisposed { get; set; }
public void Dispose()
{
if (!this.IsDisposed)
{
this.Body.DestroyFixture(this);
this.IsDisposed = true;
GC.SuppressFinalize(this);
}
}
#endregion
/// <summary>
/// Restores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void RestoreCollisionWith(Fixture fixture)
{
if (this._collisionIgnores == null)
return;
if (this._collisionIgnores.ContainsKey(fixture.FixtureId))
{
this._collisionIgnores[fixture.FixtureId] = false;
Refilter();
}
}
/// <summary>
/// Ignores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void IgnoreCollisionWith(Fixture fixture)
{
if (this._collisionIgnores == null)
this._collisionIgnores = new Dictionary<int, bool>();
if (this._collisionIgnores.ContainsKey(fixture.FixtureId))
this._collisionIgnores[fixture.FixtureId] = true;
else
this._collisionIgnores.Add(fixture.FixtureId, true);
Refilter();
}
/// <summary>
/// Determines whether collisions are ignored between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
/// <returns>
/// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
/// </returns>
public bool IsFixtureIgnored(Fixture fixture)
{
if (this._collisionIgnores == null)
return false;
if (this._collisionIgnores.ContainsKey(fixture.FixtureId))
return this._collisionIgnores[fixture.FixtureId];
return false;
}
/// <summary>
/// Contacts are persistant and will keep being persistant unless they are
/// flagged for filtering.
/// This methods flags all contacts associated with the body for filtering.
/// </summary>
internal void Refilter()
{
// Flag associated contacts for filtering.
ContactEdge edge = this.Body.ContactList;
while (edge != null)
{
Contact contact = edge.Contact;
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
if (fixtureA == this || fixtureB == this)
{
contact.FlagForFiltering();
}
edge = edge.Next;
}
World world = this.Body.World;
if (world == null)
{
return;
}
// Touch each proxy so that new pairs may be created
IBroadPhase broadPhase = world.ContactManager.BroadPhase;
for (int i = 0; i < this.ProxyCount; ++i)
{
broadPhase.TouchProxy(this.Proxies[i].ProxyId);
}
}
private void RegisterFixture()
{
// Reserve proxy space
this.Proxies = new FixtureProxy[this.Shape.ChildCount];
this.ProxyCount = 0;
this.FixtureId = _fixtureIdCounter++;
if ((this.Body.Flags & BodyFlags.Enabled) == BodyFlags.Enabled)
{
IBroadPhase broadPhase = this.Body.World.ContactManager.BroadPhase;
CreateProxies(broadPhase, ref this.Body.Xf);
}
this.Body.FixtureList.Add(this);
// Adjust mass properties if needed.
if (this.Shape._density > 0.0f)
{
this.Body.ResetMassData();
}
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
this.Body.World.Flags |= WorldFlags.NewFixture;
if (this.Body.World.FixtureAdded != null)
{
this.Body.World.FixtureAdded(this);
}
}
/// <summary>
/// Test a point for containment in this fixture.
/// </summary>
/// <param name="point">A point in world coordinates.</param>
public bool TestPoint(ref Vector2 point)
{
return this.Shape.TestPoint(ref this.Body.Xf, ref point);
}
/// <summary>
/// Cast a ray against this Shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="childIndex">Index of the child.</param>
public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
{
return this.Shape.RayCast(out output, ref input, ref this.Body.Xf, childIndex);
}
/// <summary>
/// Get the fixture's AABB. This AABB may be enlarge and/or stale.
/// If you need a more accurate AABB, compute it using the Shape and
/// the body transform.
/// </summary>
/// <param name="aabb">The aabb.</param>
/// <param name="childIndex">Index of the child.</param>
public void GetAABB(out AABB aabb, int childIndex)
{
Debug.Assert(0 <= childIndex && childIndex < this.ProxyCount);
aabb = this.Proxies[childIndex].AABB;
}
public Fixture Clone(Body body)
{
Fixture fixture = new Fixture();
fixture.Body = body;
fixture.Shape = this.Shape.Clone();
fixture.UserData = this.UserData;
fixture.Restitution = this.Restitution;
fixture.Friction = this.Friction;
fixture.IsSensor = this.IsSensor;
fixture._collisionGroup = this.CollisionGroup;
fixture._collisionCategories = this.CollisionCategories;
fixture._collidesWith = this.CollidesWith;
if (this._collisionIgnores != null)
{
fixture._collisionIgnores = new Dictionary<int, bool>();
foreach (KeyValuePair<int, bool> pair in this._collisionIgnores)
{
fixture._collisionIgnores.Add(pair.Key, pair.Value);
}
}
fixture.RegisterFixture();
return fixture;
}
public Fixture DeepClone()
{
Fixture fix = Clone(this.Body.Clone());
return fix;
}
internal void Destroy()
{
// The proxies must be destroyed before calling this.
Debug.Assert(this.ProxyCount == 0);
// Free the proxy array.
this.Proxies = null;
this.Shape = null;
if (this.Body.World.FixtureRemoved != null)
{
this.Body.World.FixtureRemoved(this);
}
this.Body.World.FixtureAdded = null;
this.Body.World.FixtureRemoved = null;
}
// These support body activation/deactivation.
internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf)
{
Debug.Assert(this.ProxyCount == 0);
// Create proxies in the broad-phase.
this.ProxyCount = this.Shape.ChildCount;
for (int i = 0; i < this.ProxyCount; ++i)
{
FixtureProxy proxy = new FixtureProxy();
this.Shape.ComputeAABB(out proxy.AABB, ref xf, i);
proxy.Fixture = this;
proxy.ChildIndex = i;
proxy.ProxyId = broadPhase.AddProxy(ref proxy);
this.Proxies[i] = proxy;
}
}
internal void DestroyProxies(IBroadPhase broadPhase)
{
// Destroy proxies in the broad-phase.
for (int i = 0; i < this.ProxyCount; ++i)
{
broadPhase.RemoveProxy(this.Proxies[i].ProxyId);
this.Proxies[i].ProxyId = -1;
}
this.ProxyCount = 0;
}
internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
{
if (this.ProxyCount == 0)
{
return;
}
for (int i = 0; i < this.ProxyCount; ++i)
{
FixtureProxy proxy = this.Proxies[i];
// Compute an AABB that covers the swept Shape (may miss some rotation effect).
AABB aabb1, aabb2;
this.Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
this.Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
proxy.AABB.Combine(ref aabb1, ref aabb2);
Vector2 displacement = transform2.Position - transform1.Position;
broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
}
}
internal bool CompareTo(Fixture fixture)
{
return (
this.CollidesWith == fixture.CollidesWith &&
this.CollisionCategories == fixture.CollisionCategories &&
this.CollisionGroup == fixture.CollisionGroup &&
this.Friction == fixture.Friction &&
this.IsSensor == fixture.IsSensor &&
this.Restitution == fixture.Restitution &&
this.Shape.CompareTo(fixture.Shape) &&
this.UserData == fixture.UserData);
}
}
}
| |
using WixSharp;
using WixSharp.UI.Forms;
namespace WixSharpSetup.Dialogs
{
partial class ProgressDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.topBorder = new System.Windows.Forms.Panel();
this.progress = new System.Windows.Forms.ProgressBar();
this.currentAction = new System.Windows.Forms.Label();
this.topPanel = new System.Windows.Forms.Panel();
this.dialogText = new System.Windows.Forms.Label();
this.banner = new System.Windows.Forms.PictureBox();
this.bottomPanel = new System.Windows.Forms.Panel();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.back = new System.Windows.Forms.Button();
this.next = new System.Windows.Forms.Button();
this.cancel = new System.Windows.Forms.Button();
this.bottomBorder = new System.Windows.Forms.Panel();
this.description = new System.Windows.Forms.Label();
this.currentActionLabel = new System.Windows.Forms.Label();
this.waitPrompt = new System.Windows.Forms.Label();
this.topPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.banner)).BeginInit();
this.bottomPanel.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// topBorder
//
this.topBorder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.topBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.topBorder.Location = new System.Drawing.Point(0, 58);
this.topBorder.Name = "topBorder";
this.topBorder.Size = new System.Drawing.Size(494, 1);
this.topBorder.TabIndex = 22;
//
// progress
//
this.progress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progress.Location = new System.Drawing.Point(32, 165);
this.progress.Name = "progress";
this.progress.Size = new System.Drawing.Size(434, 13);
this.progress.Step = 1;
this.progress.TabIndex = 20;
//
// currentAction
//
this.currentAction.AutoSize = true;
this.currentAction.Location = new System.Drawing.Point(34, 144);
this.currentAction.Name = "currentAction";
this.currentAction.Size = new System.Drawing.Size(0, 13);
this.currentAction.TabIndex = 19;
//
// topPanel
//
this.topPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.topPanel.BackColor = System.Drawing.SystemColors.Control;
this.topPanel.Controls.Add(this.dialogText);
this.topPanel.Controls.Add(this.banner);
this.topPanel.Location = new System.Drawing.Point(0, 0);
this.topPanel.Name = "topPanel";
this.topPanel.Size = new System.Drawing.Size(494, 58);
this.topPanel.TabIndex = 15;
//
// dialogText
//
this.dialogText.AutoSize = true;
this.dialogText.BackColor = System.Drawing.Color.Transparent;
this.dialogText.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dialogText.Location = new System.Drawing.Point(11, 22);
this.dialogText.Name = "dialogText";
this.dialogText.Size = new System.Drawing.Size(159, 13);
this.dialogText.TabIndex = 1;
this.dialogText.Text = "[ProgressDlgTitleInstalling]";
//
// banner
//
this.banner.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.banner.BackColor = System.Drawing.Color.White;
this.banner.Location = new System.Drawing.Point(0, 0);
this.banner.Name = "banner";
this.banner.Size = new System.Drawing.Size(494, 58);
this.banner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.banner.TabIndex = 0;
this.banner.TabStop = false;
//
// bottomPanel
//
this.bottomPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.bottomPanel.BackColor = System.Drawing.SystemColors.Control;
this.bottomPanel.Controls.Add(this.tableLayoutPanel1);
this.bottomPanel.Controls.Add(this.bottomBorder);
this.bottomPanel.Location = new System.Drawing.Point(0, 312);
this.bottomPanel.Name = "bottomPanel";
this.bottomPanel.Size = new System.Drawing.Size(494, 49);
this.bottomPanel.TabIndex = 14;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.ColumnCount = 5;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 14F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Controls.Add(this.back, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.next, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.cancel, 4, 0);
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 3);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 1;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(491, 43);
this.tableLayoutPanel1.TabIndex = 7;
//
// back
//
this.back.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.back.AutoSize = true;
this.back.Enabled = false;
this.back.Location = new System.Drawing.Point(222, 10);
this.back.MinimumSize = new System.Drawing.Size(75, 0);
this.back.Name = "back";
this.back.Size = new System.Drawing.Size(77, 23);
this.back.TabIndex = 0;
this.back.Text = "[WixUIBack]";
this.back.UseVisualStyleBackColor = true;
//
// next
//
this.next.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.next.AutoSize = true;
this.next.Enabled = false;
this.next.Location = new System.Drawing.Point(305, 10);
this.next.MinimumSize = new System.Drawing.Size(75, 0);
this.next.Name = "next";
this.next.Size = new System.Drawing.Size(77, 23);
this.next.TabIndex = 0;
this.next.Text = "[WixUINext]";
this.next.UseVisualStyleBackColor = true;
//
// cancel
//
this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.cancel.AutoSize = true;
this.cancel.Location = new System.Drawing.Point(402, 10);
this.cancel.MinimumSize = new System.Drawing.Size(75, 0);
this.cancel.Name = "cancel";
this.cancel.Size = new System.Drawing.Size(86, 23);
this.cancel.TabIndex = 0;
this.cancel.Text = "[WixUICancel]";
this.cancel.UseVisualStyleBackColor = true;
this.cancel.Click += new System.EventHandler(this.cancel_Click);
//
// bottomBorder
//
this.bottomBorder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.bottomBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.bottomBorder.Location = new System.Drawing.Point(0, 0);
this.bottomBorder.Name = "bottomBorder";
this.bottomBorder.Size = new System.Drawing.Size(494, 1);
this.bottomBorder.TabIndex = 21;
//
// description
//
this.description.AutoSize = true;
this.description.BackColor = System.Drawing.Color.Transparent;
this.description.Location = new System.Drawing.Point(29, 95);
this.description.Name = "description";
this.description.Size = new System.Drawing.Size(132, 13);
this.description.TabIndex = 16;
this.description.Text = "[ProgressDlgTextInstalling]";
//
// currentActionLabel
//
this.currentActionLabel.BackColor = System.Drawing.Color.Transparent;
this.currentActionLabel.Location = new System.Drawing.Point(29, 144);
this.currentActionLabel.Name = "currentActionLabel";
this.currentActionLabel.Size = new System.Drawing.Size(132, 13);
this.currentActionLabel.TabIndex = 19;
this.currentActionLabel.Text = "[ProgressDlgStatusLabel]";
this.currentActionLabel.Visible = false;
//
// waitPrompt
//
this.waitPrompt.AutoSize = true;
this.waitPrompt.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.waitPrompt.ForeColor = System.Drawing.Color.Blue;
this.waitPrompt.Location = new System.Drawing.Point(85, 209);
this.waitPrompt.Name = "waitPrompt";
this.waitPrompt.Size = new System.Drawing.Size(265, 39);
this.waitPrompt.TabIndex = 23;
this.waitPrompt.TabStop = true;
this.waitPrompt.Text = "Please wait for UAC prompt to appear.\r\n\r\nIf it appears minimized then activate it" +
" from the taskbar.";
this.waitPrompt.Visible = false;
//
// ProgressDialog
//
this.ClientSize = new System.Drawing.Size(494, 361);
this.ControlBox = false;
this.Controls.Add(this.waitPrompt);
this.Controls.Add(this.topBorder);
this.Controls.Add(this.progress);
this.Controls.Add(this.currentAction);
this.Controls.Add(this.topPanel);
this.Controls.Add(this.bottomPanel);
this.Controls.Add(this.description);
this.Controls.Add(this.currentActionLabel);
this.Name = "ProgressDialog";
this.Text = "[ProgressDlg_Title]";
this.Load += new System.EventHandler(this.ProgressDialog_Load);
this.topPanel.ResumeLayout(false);
this.topPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.banner)).EndInit();
this.bottomPanel.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox banner;
private System.Windows.Forms.Panel topPanel;
private System.Windows.Forms.Label dialogText;
private System.Windows.Forms.Panel bottomPanel;
private System.Windows.Forms.Label description;
private System.Windows.Forms.ProgressBar progress;
private System.Windows.Forms.Label currentAction;
private System.Windows.Forms.Label currentActionLabel;
private System.Windows.Forms.Panel bottomBorder;
private System.Windows.Forms.Panel topBorder;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button back;
private System.Windows.Forms.Button next;
private System.Windows.Forms.Button cancel;
private System.Windows.Forms.Label waitPrompt;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
namespace BTDB.EventStoreLayer
{
public class TypeSerializers : ITypeSerializers, ITypeSerializerMappingFactory
{
ITypeNameMapper _typeNameMapper;
readonly ConcurrentDictionary<ITypeDescriptor, Func<AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object>> _loaders = new ConcurrentDictionary<ITypeDescriptor, Func<AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object>>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
readonly ConcurrentDictionary<ITypeDescriptor, Action<object, IDescriptorSerializerLiteContext>> _newDescriptorSavers = new ConcurrentDictionary<ITypeDescriptor, Action<object, IDescriptorSerializerLiteContext>>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
readonly ConcurrentDictionary<ITypeDescriptor, bool> _descriptorSet = new ConcurrentDictionary<ITypeDescriptor, bool>();
ConcurrentDictionary<Type, ITypeDescriptor> _type2DescriptorMap = new ConcurrentDictionary<Type, ITypeDescriptor>(ReferenceEqualityComparer<Type>.Instance);
readonly object _buildTypeLock = new object();
readonly ConcurrentDictionary<ITypeDescriptor, Action<AbstractBufferedWriter, object>> _simpleSavers = new ConcurrentDictionary<ITypeDescriptor, Action<AbstractBufferedWriter, object>>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
readonly ConcurrentDictionary<ITypeDescriptor, Action<AbstractBufferedWriter, ITypeBinarySerializerContext, object>> _complexSavers = new ConcurrentDictionary<ITypeDescriptor, Action<AbstractBufferedWriter, ITypeBinarySerializerContext, object>>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
// created funcs just once as optimization
readonly Func<ITypeDescriptor, Action<AbstractBufferedWriter, object>> _newSimpleSaverAction;
readonly Func<ITypeDescriptor, Action<AbstractBufferedWriter, ITypeBinarySerializerContext, object>> _newComplexSaverAction;
readonly Func<ITypeDescriptor, Action<object, IDescriptorSerializerLiteContext>> _newDescriptorSaverFactoryAction;
readonly Func<ITypeDescriptor, Func<AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object>> _loaderFactoryAction;
readonly Func<Type, ITypeDescriptor> _buildFromTypeAction;
public TypeSerializers(): this(null)
{
}
public TypeSerializers(ITypeNameMapper typeNameMapper)
{
SetTypeNameMapper(typeNameMapper);
ForgotAllTypesAndSerializers();
_newSimpleSaverAction = NewSimpleSaver;
_newComplexSaverAction = NewComplexSaver;
_newDescriptorSaverFactoryAction = NewDescriptorSaverFactory;
_loaderFactoryAction = LoaderFactory;
_buildFromTypeAction = BuildFromType;
}
public void SetTypeNameMapper(ITypeNameMapper typeNameMapper)
{
_typeNameMapper = typeNameMapper ?? new FullNameTypeMapper();
}
public ITypeDescriptor DescriptorOf(object obj)
{
if (obj == null) return null;
var knowDescriptor = obj as IKnowDescriptor;
if (knowDescriptor != null) return knowDescriptor.GetDescriptor();
return DescriptorOf(obj.GetType());
}
public ITypeDescriptor DescriptorOf(Type objType)
{
return _type2DescriptorMap.GetOrAdd(objType, _buildFromTypeAction);
}
ITypeDescriptor BuildFromType(Type type)
{
ITypeDescriptor result;
lock (_buildTypeLock)
{
var buildFromTypeCtx = new BuildFromTypeCtx(this, _type2DescriptorMap);
buildFromTypeCtx.Create(type);
buildFromTypeCtx.MergeTypesByShape();
buildFromTypeCtx.SetNewDescriptors();
result = buildFromTypeCtx.GetFinalDescriptor(type);
}
return result;
}
class BuildFromTypeCtx : ITypeDescriptorFactory
{
readonly TypeSerializers _typeSerializers;
readonly ConcurrentDictionary<Type, ITypeDescriptor> _type2DescriptorMap;
readonly Dictionary<Type, ITypeDescriptor> _temporaryMap = new Dictionary<Type, ITypeDescriptor>();
readonly Dictionary<ITypeDescriptor, ITypeDescriptor> _remap = new Dictionary<ITypeDescriptor, ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
public BuildFromTypeCtx(TypeSerializers typeSerializers, ConcurrentDictionary<Type, ITypeDescriptor> type2DescriptorMap)
{
_typeSerializers = typeSerializers;
_type2DescriptorMap = type2DescriptorMap;
}
public ITypeDescriptor Create(Type type)
{
ITypeDescriptor result;
if (_type2DescriptorMap.TryGetValue(type, out result)) return result;
if (_temporaryMap.TryGetValue(type, out result)) return result;
if (!type.IsSubclassOf(typeof(Delegate)))
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition().InheritsOrImplements(typeof(IList<>)))
{
result = new ListTypeDescriptor(_typeSerializers, type);
}
else if (type.GetGenericTypeDefinition().InheritsOrImplements(typeof(IDictionary<,>)))
{
result = new DictionaryTypeDescriptor(_typeSerializers, type);
}
}
else if (type.IsArray)
{
result = new ListTypeDescriptor(_typeSerializers, type);
}
else if (type.IsEnum)
{
result = new EnumTypeDescriptor(_typeSerializers, type);
}
else
{
result = new ObjectTypeDescriptor(_typeSerializers, type);
}
}
_temporaryMap[type] = result;
if (result != null)
result.FinishBuildFromType(this);
return result;
}
public void MergeTypesByShape()
{
foreach (var typeDescriptor in _temporaryMap)
{
var d = typeDescriptor.Value;
foreach (var existingTypeDescriptor in _type2DescriptorMap)
{
if (d.Equals(existingTypeDescriptor.Value))
{
_remap[d] = existingTypeDescriptor.Value;
break;
}
}
}
foreach (var typeDescriptor in _temporaryMap)
{
var d = typeDescriptor.Value;
d.MapNestedTypes(desc =>
{
ITypeDescriptor res;
if (_remap.TryGetValue(desc, out res)) return res;
return desc;
});
}
}
public ITypeDescriptor GetFinalDescriptor(Type type)
{
ITypeDescriptor result;
if (_temporaryMap.TryGetValue(type, out result))
{
ITypeDescriptor result2;
if (_remap.TryGetValue(result, out result2)) return result2;
return result;
}
throw new InvalidOperationException();
}
public void SetNewDescriptors()
{
foreach (var typeDescriptor in _temporaryMap)
{
var d = typeDescriptor.Value;
ITypeDescriptor result;
if (_remap.TryGetValue(d, out result)) continue;
_type2DescriptorMap.TryAdd(d.GetPreferedType(), d);
}
}
}
public void ForgotAllTypesAndSerializers()
{
_loaders.Clear();
_newDescriptorSavers.Clear();
foreach (var p in _descriptorSet)
{
p.Key.ClearMappingToType();
}
_type2DescriptorMap = new ConcurrentDictionary<Type, ITypeDescriptor>(EnumDefaultTypes(), ReferenceEqualityComparer<Type>.Instance);
}
static IEnumerable<KeyValuePair<Type, ITypeDescriptor>> EnumDefaultTypes()
{
foreach (var predefinedType in BasicSerializersFactory.TypeDescriptors)
{
yield return new KeyValuePair<Type, ITypeDescriptor>(predefinedType.GetPreferedType(), predefinedType);
var descriptorMultipleNativeTypes = predefinedType as ITypeDescriptorMultipleNativeTypes;
if (descriptorMultipleNativeTypes == null) continue;
foreach (var type in descriptorMultipleNativeTypes.GetNativeTypes())
{
yield return new KeyValuePair<Type, ITypeDescriptor>(type, predefinedType);
}
}
}
public Func<AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object> GetLoader(ITypeDescriptor descriptor)
{
return _loaders.GetOrAdd(descriptor, _loaderFactoryAction);
}
Func<AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object> LoaderFactory(ITypeDescriptor descriptor)
{
var loadAsType = LoadAsType(descriptor);
var methodBuilder = ILBuilder.Instance.NewMethod<Func<AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object>>("DeserializerFor" + descriptor.Name);
var il = methodBuilder.Generator;
if (descriptor.AnyOpNeedsCtx())
{
var localCtx = il.DeclareLocal(typeof(ITypeBinaryDeserializerContext), "ctx");
var haveCtx = il.DefineLabel();
il
.Ldarg(1)
.Dup()
.Stloc(localCtx)
.Brtrue(haveCtx)
.Ldarg(0)
.Ldarg(2)
.Newobj(() => new DeserializerCtx(null, null))
.Castclass(typeof(ITypeBinaryDeserializerContext))
.Stloc(localCtx)
.Mark(haveCtx);
descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldloc(localCtx), ilGen => ilGen.Ldarg(3), loadAsType);
}
else
{
descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1), ilGen => ilGen.Ldarg(3), loadAsType);
}
if (loadAsType.IsValueType)
{
il.Box(loadAsType);
}
else if (loadAsType != typeof(object))
{
il.Castclass(typeof(object));
}
il.Ret();
return methodBuilder.Create();
}
public Type LoadAsType(ITypeDescriptor descriptor)
{
return descriptor.GetPreferedType() ?? NameToType(descriptor.Name) ?? typeof(object);
}
class DeserializerCtx : ITypeBinaryDeserializerContext
{
readonly AbstractBufferedReader _reader;
readonly ITypeSerializersId2LoaderMapping _mapping;
readonly List<object> _backRefs = new List<object>();
public DeserializerCtx(AbstractBufferedReader reader, ITypeSerializersId2LoaderMapping mapping)
{
_reader = reader;
_mapping = mapping;
}
public object LoadObject()
{
var typeId = _reader.ReadVUInt32();
if (typeId == 0)
{
return null;
}
if (typeId == 1)
{
var backRefId = _reader.ReadVUInt32();
return _backRefs[(int)backRefId];
}
return _mapping.Load(typeId, _reader, this);
}
public void AddBackRef(object obj)
{
_backRefs.Add(obj);
}
public void SkipObject()
{
var typeId = _reader.ReadVUInt32();
if (typeId == 0)
{
return;
}
if (typeId == 1)
{
var backRefId = _reader.ReadVUInt32();
if (backRefId > _backRefs.Count) throw new InvalidDataException();
return;
}
_mapping.Load(typeId, _reader, this);
}
}
public Action<AbstractBufferedWriter, object> GetSimpleSaver(ITypeDescriptor descriptor)
{
return _simpleSavers.GetOrAdd(descriptor, _newSimpleSaverAction);
}
Action<AbstractBufferedWriter, object> NewSimpleSaver(ITypeDescriptor descriptor)
{
if (descriptor.AnyOpNeedsCtx()) return null;
var method = ILBuilder.Instance.NewMethod<Action<AbstractBufferedWriter, object>>(descriptor.Name + "SimpleSaver");
var il = method.Generator;
descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), null, ilgen =>
{
ilgen.Ldarg(1);
var type = descriptor.GetPreferedType();
if (type != typeof(object))
{
ilgen.UnboxAny(type);
}
}, descriptor.GetPreferedType());
il.Ret();
return method.Create();
}
public Action<AbstractBufferedWriter, ITypeBinarySerializerContext, object> GetComplexSaver(ITypeDescriptor descriptor)
{
return _complexSavers.GetOrAdd(descriptor, _newComplexSaverAction);
}
Action<AbstractBufferedWriter, ITypeBinarySerializerContext, object> NewComplexSaver(ITypeDescriptor descriptor)
{
var method = ILBuilder.Instance.NewMethod<Action<AbstractBufferedWriter, ITypeBinarySerializerContext, object>>(descriptor.Name + "ComplexSaver");
var il = method.Generator;
descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1), ilgen =>
{
ilgen.Ldarg(2);
var type = descriptor.GetPreferedType();
if (type != typeof(object))
{
ilgen.UnboxAny(type);
}
}, descriptor.GetPreferedType());
il.Ret();
return method.Create();
}
public Action<object, IDescriptorSerializerLiteContext> GetNewDescriptorSaver(ITypeDescriptor descriptor)
{
return _newDescriptorSavers.GetOrAdd(descriptor, _newDescriptorSaverFactoryAction);
}
Action<object, IDescriptorSerializerLiteContext> NewDescriptorSaverFactory(ITypeDescriptor descriptor)
{
var gen = descriptor.BuildNewDescriptorGenerator();
if (gen == null)
{
return null;
}
var method = ILBuilder.Instance.NewMethod<Action<object, IDescriptorSerializerLiteContext>>("GatherAllObjectsForTypeExtraction_" + descriptor.Name);
var il = method.Generator;
gen.GenerateTypeIterator(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1));
il.Ret();
return method.Create();
}
public ITypeSerializersMapping CreateMapping()
{
return new TypeSerializersMapping(this);
}
public void StoreDescriptor(ITypeDescriptor descriptor, AbstractBufferedWriter writer, Func<ITypeDescriptor, uint> descriptor2Id)
{
if (descriptor is ListTypeDescriptor)
{
writer.WriteUInt8((byte)TypeCategory.List);
}
else if (descriptor is DictionaryTypeDescriptor)
{
writer.WriteUInt8((byte)TypeCategory.Dictionary);
}
else if (descriptor is ObjectTypeDescriptor)
{
writer.WriteUInt8((byte)TypeCategory.Class);
}
else if (descriptor is EnumTypeDescriptor)
{
writer.WriteUInt8((byte)TypeCategory.Enum);
}
else
{
throw new ArgumentOutOfRangeException();
}
var p = descriptor as IPersistTypeDescriptor;
p.Persist(writer, (w, d) => w.WriteVUInt32(descriptor2Id(d)));
}
public ITypeDescriptor MergeDescriptor(ITypeDescriptor descriptor)
{
foreach (var existingTypeDescriptor in _type2DescriptorMap)
{
if (descriptor.Equals(existingTypeDescriptor.Value))
{
return existingTypeDescriptor.Value;
}
}
return descriptor;
}
public string TypeToName(Type type)
{
return _typeNameMapper.ToName(type);
}
Type NameToType(string name)
{
return _typeNameMapper.ToType(name);
}
}
}
| |
using OAuth;
using QuickBooks.Net.Exceptions;
using System.Linq;
using System.Threading.Tasks;
using QuickBooks.Net.Controllers;
using Flurl.Http;
using QuickBooks.Net.Data.Models;
using QuickBooks.Net.Data.Models.Authorization;
using QuickBooks.Net.Utilities;
namespace QuickBooks.Net
{
public class QuickBooksClient : IQuickBooksClient
{
#region URL Constants
private const string AuthorizeUrl = "https://appcenter.intuit.com/Connect/Begin";
private const string RequestTokenUrl = "https://oauth.intuit.com/oauth/v1/get_request_token";
private const string AccessTokenUrl = "https://oauth.intuit.com/oauth/v1/get_access_token";
private const string CurrentUserUrl = "https://appcenter.intuit.com/api/v1/user/current";
private const string DisconnectUrl = "https://appcenter.intuit.com/api/v1/connection/disconnect";
private const string ReconnectUrl = "https://appcenter.intuit.com/api/v1/connection/reconnect";
#endregion
private const string OAuthVersion = "1.0";
public string ConsumerKey { get; set; }
public string ConsumerSecret { get; set; }
public string AccessToken { get; set; }
public string AccessTokenSecret { get; set; }
public string CallbackUrl { get; set; }
public bool SandboxMode { get; set; } = true;
public string RealmId { get; set; }
public string MinorVersion { get; set; } = "4";
public string AcceptType { get; set; } = "application/json";
public ICustomerController Customers { get; }
public ICompanyInfoController CompanyInfo { get; }
public IInvoiceController Invoices { get; }
public IPaymentController Payments { get; }
public IDepositController Deposits { get; }
public ISalesReceiptController SalesReceipts { get; }
public IClassController Classes { get; }
public QuickBooksClient()
{
Customers = new CustomerController(this, OAuthVersion);
CompanyInfo = new CompanyInfoController(this, OAuthVersion);
Invoices = new InvoiceController(this, OAuthVersion);
Payments = new PaymentController(this, OAuthVersion);
Deposits = new DepositController(this, OAuthVersion);
SalesReceipts = new SalesReceiptController(this, OAuthVersion);
Classes = new ClassController(this, OAuthVersion);
}
public QuickBooksClient(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret,
string callbackUrl, bool sandboxMode, string realmId, string minorVersion) : this()
{
ConsumerKey = consumerKey;
ConsumerSecret = consumerSecret;
AccessToken = accessToken;
AccessTokenSecret = accessTokenSecret;
CallbackUrl = callbackUrl;
SandboxMode = sandboxMode;
RealmId = realmId;
MinorVersion = minorVersion;
}
public async Task<QuickBooksUser> GetCurrentUser()
{
var authRequest = new OAuthRequest
{
Method = "GET",
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
Token = AccessToken,
TokenSecret = AccessTokenSecret,
RequestUrl = CurrentUserUrl,
Version = OAuthVersion
};
var client = CurrentUserUrl.WithHeaders(new
{
Accept = AcceptType,
Authorization = authRequest.GetAuthorizationHeader()
});
try
{
var response = await client.GetAsync();
var xml = XmlHelper.ParseXmlString(response.Content.ReadAsStringAsync().Result);
return new QuickBooksUser
{
FirstName = xml["FirstName"],
LastName = xml["LastName"],
EmailAddress = xml["EmailAddress"],
ScreenName = xml["ScreenName"],
IsVerified = bool.Parse(xml["IsVerified"])
};
}
catch (FlurlHttpException ex)
{
throw new QuickBooksException("Unable to retrieve current user.", ex.Message);
}
}
// Haven't actually tested this out yet
public async Task DisconnectAccount()
{
var authRequest = new OAuthRequest
{
Method = "GET",
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
Token = AccessToken,
TokenSecret = AccessTokenSecret,
RequestUrl = DisconnectUrl,
Version = OAuthVersion
};
var client = DisconnectUrl.WithHeaders(new
{
Accept = AcceptType,
Authorization = authRequest.GetAuthorizationHeader()
});
try
{
await client.GetAsync();
}
catch (FlurlHttpException ex)
{
throw new QuickBooksException("Unable to disconnect account.", ex.Message);
}
}
// Haven't actually tested this out yet
public async Task ReconnectAccount()
{
var authRequest = new OAuthRequest
{
Method = "GET",
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
Token = AccessToken,
TokenSecret = AccessTokenSecret,
RequestUrl = ReconnectUrl,
Version = OAuthVersion
};
var client = ReconnectUrl.WithHeaders(new
{
Accept = AcceptType,
Authorization = authRequest.GetAuthorizationHeader()
});
try
{
await client.GetAsync();
}
catch (FlurlHttpException ex)
{
throw new QuickBooksException("Unable to reconnect account.", ex.Message);
}
}
public async Task<AuthTokenInfo> GetAuthTokens()
{
var authRequest = new OAuthRequest
{
Method = "GET",
CallbackUrl = CallbackUrl,
Type = OAuthRequestType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
RequestUrl = RequestTokenUrl,
Version = OAuthVersion
};
try
{
var request = await (authRequest.RequestUrl + "?" + authRequest.GetAuthorizationQuery()).GetAsync();
var result = await request.Content.ReadAsStringAsync();
var tokens = result.Split('&').Select(x => x.Split('=')).ToDictionary(split => split[0], split => split[1]);
return new AuthTokenInfo(AuthorizeUrl) { OAuthToken = tokens["oauth_token"], OAuthTokenSecret = tokens["oauth_token_secret"] };
}
catch (FlurlHttpException ex)
{
throw new UnauthorizedQuickBooksClientException(
"QuickBooks returned with an unauthorized response. Be sure your consumer key and consumer secret are correct.",
ex.InnerException);
}
}
public async Task<AccessTokenInfo> RequestAccessTokens(string authToken, string authTokenSecret, string oauthVerifier)
{
var oauthRequest = OAuthRequest.ForAccessToken(
ConsumerKey,
ConsumerSecret,
authToken,
authTokenSecret,
oauthVerifier
);
oauthRequest.RequestUrl = AccessTokenUrl;
oauthRequest.Version = OAuthVersion;
try
{
var request = await (oauthRequest.RequestUrl + "?" + oauthRequest.GetAuthorizationQuery()).GetAsync();
var result = await request.Content.ReadAsStringAsync();
var accessTokens = result.Split('&').Select(x => x.Split('=')).ToDictionary(split => split[0], split => split[1]);
return new AccessTokenInfo { AccessToken = accessTokens["oauth_token"], AccessTokenSecret = accessTokens["oauth_token_secret"] };
}
catch (FlurlHttpException ex)
{
throw new UnauthorizedQuickBooksClientException(
"Unable to get access tokens.",
ex.InnerException);
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.Fakeables;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory factory = new LogFactory();
private static IAppDomain currentAppDomain;
private static ICollection<Assembly> _hiddenAssemblies;
private static readonly object lockObject = new object();
/// <summary>
/// Delegate used to set/get the culture in use.
/// </summary>
[Obsolete]
public delegate CultureInfo GetCultureInfo();
#if !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
SetupTerminationEvents();
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Gets the default <see cref="NLog.LogFactory" /> instance.
/// </summary>
internal static LogFactory LogFactory
{
get { return factory; }
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { factory.ConfigurationChanged += value; }
remove { factory.ConfigurationChanged -= value; }
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { factory.ConfigurationReloaded += value; }
remove { factory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return factory.ThrowExceptions; }
set { factory.ThrowExceptions = value; }
}
/// <summary>
/// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>
/// This option is for backwards-compatiblity.
/// By default exceptions are not thrown under any circumstances.
///
/// </remarks>
public static bool? ThrowConfigExceptions
{
get { return factory.ThrowConfigExceptions; }
set { factory.ThrowConfigExceptions = value; }
}
internal static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set
{
#if !SILVERLIGHT && !MONO
currentAppDomain.DomainUnload -= TurnOffLogging;
currentAppDomain.ProcessExit -= TurnOffLogging;
#endif
currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets the current logging configuration.
/// <see cref="NLog.LogFactory.Configuration" />
/// </summary>
public static LoggingConfiguration Configuration
{
get { return factory.Configuration; }
set { factory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return factory.GlobalThreshold; }
set { factory.GlobalThreshold = value; }
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
[Obsolete("Use Configuration.DefaultCultureInfo property instead")]
public static GetCultureInfo DefaultCultureInfo
{
get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; }
set { throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); }
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
return factory.GetLogger(GetClassFullName());
}
internal static bool IsHiddenAssembly(Assembly assembly)
{
return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly);
}
/// <summary>
/// Adds the given assembly which will be skipped
/// when NLog is trying to find the calling method on stack trace.
/// </summary>
/// <param name="assembly">The assembly to skip.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHiddenAssembly(Assembly assembly)
{
lock (lockObject)
{
if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly))
return;
_hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>())
{
assembly
};
}
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
return factory.GetLogger(GetClassFullName(), loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
[CLSCompliant(false)]
public static Logger CreateNullLogger()
{
return factory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name)
{
return factory.GetLogger(name);
}
/// <summary>
/// Gets the specified named custom logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
/// <remarks>The generic way for this method is <see cref="NLog.LogFactory{loggerType}.GetLogger(string)"/></remarks>
[CLSCompliant(false)]
public static Logger GetLogger(string name, Type loggerType)
{
return factory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
factory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
factory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
factory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
factory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
factory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
factory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
factory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that implements IDisposable whose Dispose() method reenables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return factory.SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
factory.ResumeLogging();
}
/// <summary>
/// Checks if logging is currently enabled.
/// </summary>
/// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/>
/// otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return factory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
foreach (var target in Configuration.AllTargets)
{
target.Dispose();
}
}
#if !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
try
{
CurrentAppDomain.ProcessExit += TurnOffLogging;
CurrentAppDomain.DomainUnload += TurnOffLogging;
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Error setting up termination events.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
#endif
/// <summary>
/// Gets the fully qualified name of the class invoking the LogManager, including the
/// namespace but not the assembly.
/// </summary>
private static string GetClassFullName()
{
string className;
Type declaringType;
int framesToSkip = 2;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
MethodBase method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
className = method.Name;
break;
}
framesToSkip++;
className = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return className;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// Reset logging configuration to null; this causes old configuration (if any) to be
// closed.
InternalLogger.Info("Shutting down logging...");
Configuration = null;
InternalLogger.Info("Logger has been shut down.");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using XamarinRepairApp.Model;
using Android.Graphics;
namespace XamarinRepairApp.Utils
{
public class ListHelper
{
public static async Task<int> GetPropertyIdByIncidentId()
{
int propertyId = 0;
try
{
string select = "sl_propertyIDId";
string filter = string.Format("ID eq {0} and sl_propertyIDId gt 0 and sl_inspectionIDId gt 0 and sl_roomIDId gt 0", App.IncidentId);
string orderBy = "sl_date desc";
List<ListItem> listItems = await ListClient.GetListItems("Incidents", select, string.Empty, 1, filter, orderBy);
if (listItems != null && listItems.Any())
{
propertyId = Helper.GetInt(listItems[0].mData["sl_propertyIDId"]);
}
}
catch (Exception)
{
propertyId = 0;
}
return propertyId;
}
public static async Task<int> GetAvailableIncidentId()
{
List<IncidentModel> incidents = new List<IncidentModel>();
string select = "ID";
string orderBy = "ID desc";
List<ListItem> listItems = await ListClient.GetListItems("Incidents", select, "", 0, "", orderBy);
if (listItems.Count > 0) {
return Helper.GetInt (listItems [0].mData ["ID"]);
}
return -1;
}
public static async Task<List<IncidentModel>> GetIncidents()
{
List<IncidentModel> incidents = new List<IncidentModel>();
string select = "ID,Title,sl_inspectorIncidentComments,sl_dispatcherComments,sl_repairComments,sl_status,sl_type,sl_date,sl_repairCompleted,sl_propertyIDId,sl_inspectionIDId,sl_roomIDId,sl_taskId,sl_inspectionID/ID,sl_inspectionID/sl_datetime,sl_inspectionID/sl_finalized,sl_inspectionID/sl_inspector,sl_inspectionID/sl_emailaddress,sl_propertyID/ID,sl_propertyID/Title,sl_propertyID/sl_emailaddress,sl_propertyID/sl_owner,sl_propertyID/sl_address1,sl_propertyID/sl_address2,sl_propertyID/sl_city,sl_propertyID/sl_state,sl_propertyID/sl_postalCode,sl_propertyID/sl_group,sl_roomID/ID,sl_roomID/Title";
string expand = "sl_inspectionID,sl_propertyID,sl_roomID";
string filter = string.Format("sl_propertyIDId eq {0} and sl_inspectionIDId gt 0 and sl_roomIDId gt 0", App.PropertyId);
string orderBy = "sl_date desc";
List<ListItem> listItems = await ListClient.GetListItems("Incidents", select, expand, 0, filter, orderBy);
foreach (ListItem item in listItems)
{
incidents.Add(new IncidentModel(item.mData));
}
return incidents;
}
public static async Task<Bitmap> GetPropertyPhoto(int propertyId)
{
Bitmap bitmap = null;
try
{
string select = "Id";
string filter = string.Format("sl_propertyIDId eq {0}", propertyId);
string orderBy = "Modified desc";
List<ListItem> listItems = await ListClient.GetListItems("Property%20Photos", select, string.Empty, 1, filter, orderBy);
if (listItems != null && listItems.Any())
{
int photoId = Helper.GetInt(listItems[0].mData["Id"]);
if (photoId > 0)
{
string fileServerRelativeUrl = await ListClient.GetFileServerRelativeUrl("Property%20Photos", photoId);
if (!string.IsNullOrEmpty(fileServerRelativeUrl))
{
bitmap = await ListClient.GetFile(fileServerRelativeUrl);
}
}
}
}
catch (Exception)
{
bitmap = null;
}
return bitmap;
}
public static async Task<Bitmap> GetIncidentPhoto(int incidentId, int inspectionId, int roomId)
{
Bitmap bitmap = null;
try
{
string select = "Id";
string filter = string.Format("sl_incidentIDId eq {0} and sl_inspectionIDId eq {1} and sl_roomIDId eq {2}", incidentId, inspectionId, roomId);
string orderBy = "Modified desc";
List<ListItem> listItems = await ListClient.GetListItems("Room%20Inspection%20Photos", select, string.Empty, 1, filter, orderBy);
if (listItems != null && listItems.Any())
{
int photoId = Helper.GetInt(listItems[0].mData["Id"]);
if (photoId > 0)
{
string fileServerRelativeUrl = await ListClient.GetFileServerRelativeUrl("Room%20Inspection%20Photos", photoId);
if (!string.IsNullOrEmpty(fileServerRelativeUrl))
{
bitmap = await ListClient.GetFile(fileServerRelativeUrl);
}
}
}
}
catch (Exception)
{
bitmap = null;
}
return bitmap;
}
public static async Task<List<int>> GetPhotoIdCollection(string listName, int incidentId, int inspectionId, int roomId)
{
List<int> idCollection = new List<int>();
try
{
string select = "Id";
string filter = string.Format("sl_incidentIDId eq {0} and sl_inspectionIDId eq {1} and sl_roomIDId eq {2}", incidentId, inspectionId, roomId);
string orderBy = "Modified desc";
List<ListItem> listItems = await ListClient.GetListItems(listName, select, string.Empty, 1000, filter, orderBy);
if (listItems != null && listItems.Any())
{
for (int i = 0; i < listItems.Count; i++)
{
int photoId = Helper.GetInt(listItems[i].mData["Id"]);
if (photoId > 0)
{
idCollection.Add(photoId);
}
}
}
}
catch (Exception)
{
idCollection = new List<int>();
}
return idCollection;
}
public static async Task<Bitmap> GetPhoto(string listName, int photoId)
{
Bitmap bitmap = null;
try
{
string fileServerRelativeUrl = await ListClient.GetFileServerRelativeUrl(listName, photoId);
if (!string.IsNullOrEmpty(fileServerRelativeUrl))
{
bitmap = await ListClient.GetFile(fileServerRelativeUrl);
}
}
catch (Exception)
{
bitmap = null;
}
return bitmap;
}
public static async Task<bool> UploadImage(string listName, string listName2, string imageName, Bitmap bitmap, int incidentId, int inspectionId, int roomId)
{
bool success = false;
try
{
bool uploadSuccess = await ListClient.UploadPhoto(listName, imageName, bitmap);
if (uploadSuccess)
{
int fileId = await ListClient.GetFileId(listName, imageName);
if (fileId > 0)
{
string type = "SP.Data.RepairPhotosItem";
string metadata = string.Format("'sl_incidentIDId':{0},'sl_inspectionIDId':{1},'sl_roomIDId':{2}", incidentId, inspectionId, roomId);
success = await ListClient.UpdateListItem(type, metadata, listName2, fileId);
}
}
}
catch (Exception)
{
success = false;
}
return success;
}
public static async Task<bool> UploadRepairComments(int incidentId, string comments)
{
bool success = false;
try
{
string type = "SP.Data.IncidentsListItem";
string metadata = string.Format("'sl_repairComments':'{0}'", comments);
success = await ListClient.UpdateListItem(type, metadata, "Incidents", incidentId);
}
catch (Exception)
{
success = false;
}
return success;
}
public static async Task<bool> UploadRepairComplete(int incidentId)
{
bool success = false;
try
{
string type = "SP.Data.IncidentsListItem";
string metadata = string.Format("'sl_repairCompleted':'{0}','sl_status':'Repair Pending Approval'", DateTime.Now.ToString("yyyy/MM/dd"));
success = await ListClient.UpdateListItem(type, metadata, "Incidents", incidentId);
}
catch (Exception)
{
success = false;
}
return success;
}
public static async Task<bool> UploadRepairWorkFlowTask(int taskId)
{
bool success = false;
try
{
string type = "SP.Data.Incident_x0020_Workflow_x0020_TasksListItem";
string metadata = "'PercentComplete':1,'Status':'Completed'";
success = await ListClient.UpdateListItem(type, metadata, "Incident%20Workflow%20Tasks", taskId);
}
catch (Exception)
{
success = false;
}
return success;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Mulder.Base;
using Mulder.Base.Commands;
using Mulder.Base.Logging;
namespace Mulder.Tests.Base.Commands
{
public class CreateCommandTests
{
[TestFixture]
public class when_executing_with_wrong_number_of_arguments
{
ILog log;
IDictionary<string, ICommand> subCommands;
CreateCommand createCommand;
[SetUp]
public void SetUp()
{
log = Substitute.For<ILog>();
subCommands = Substitute.For<IDictionary<string, ICommand>>();
createCommand = new CreateCommand(log, subCommands);
}
[Test]
public void should_log_usage_message()
{
createCommand.Execute(new string[] {});
log.Received().ErrorMessage(Arg.Is<string>(s => s == Messages.Usage));
}
[Test]
public void should_return_error_exit_code()
{
ExitCode exitCode = createCommand.Execute(new string[] {});
exitCode.ShouldBe(ExitCode.Error);
}
}
[TestFixture]
public class when_executing_with_invalid_sub_command_argument
{
string invalidArgument;
ILog log;
IDictionary<string, ICommand> subCommands;
CreateCommand createCommand;
[SetUp]
public void SetUp()
{
invalidArgument = "blah";
log = Substitute.For<ILog>();
subCommands = Substitute.For<IDictionary<string, ICommand>>();
subCommands.ContainsKey(invalidArgument).Returns(false);
createCommand = new CreateCommand(log, subCommands);
}
[Test]
public void should_log_usage_message()
{
createCommand.Execute(new string[] { invalidArgument });
log.Received().ErrorMessage(Arg.Is<string>(s => s == Messages.Usage));
}
[Test]
public void should_return_error_exit_code()
{
ExitCode exitCode = createCommand.Execute(new string[] { invalidArgument });
exitCode.ShouldBe(ExitCode.Error);
}
}
[TestFixture]
public class when_executing_with_valid_sub_command_argument
{
string subCommandArgument;
string additionalArgument;
ICommand subCommand;
ILog log;
IDictionary<string, ICommand> subCommands;
CreateCommand createCommand;
[SetUp]
public void SetUp()
{
subCommandArgument = "subCommand";
additionalArgument = "additionalArgument";
subCommand = Substitute.For<ICommand>();
subCommand.Execute(Arg.Any<string[]>()).Returns(ExitCode.Success);
log = Substitute.For<ILog>();
subCommands = Substitute.For<IDictionary<string, ICommand>>();
subCommands.ContainsKey(subCommandArgument).Returns(true);
subCommands[subCommandArgument] = subCommand;
createCommand = new CreateCommand(log, subCommands);
}
[Test]
public void should_call_execute_on_sub_command_with_no_arguments()
{
createCommand.Execute(new string[] { subCommandArgument });
subCommand.Received().Execute(Arg.Is<string[]>(args => args.Length == 0));
}
[Test]
public void should_call_execute_on_sub_command_with_additional_arguments()
{
createCommand.Execute(new string[] { subCommandArgument, additionalArgument });
subCommand.Received().Execute(Arg.Is<string[]>(args => args[0] == additionalArgument));
}
[Test]
public void should_return_sub_command_exit_code()
{
ExitCode exitCode = createCommand.Execute(new string[] { subCommandArgument });
exitCode.ShouldBe(ExitCode.Success);
}
}
[TestFixture]
public class when_showing_help
{
ILog log;
IDictionary<string, ICommand> subCommands;
CreateCommand createCommand;
[SetUp]
public void SetUp()
{
log = Substitute.For<ILog>();
subCommands = Substitute.For<IDictionary<string, ICommand>>();
createCommand = new CreateCommand(log, subCommands);
}
[Test]
public void should_log_help()
{
createCommand.ShowHelp(new string[] {});
log.Received().InfoMessage(Messages.BuildHelpMessage());
}
[Test]
public void should_return_success_exit_code()
{
ExitCode exitCode = createCommand.ShowHelp(new string[] {});
exitCode.ShouldBe(ExitCode.Success);
}
}
[TestFixture]
public class when_showing_help_for_subcommand
{
string subCommandArgument;
ICommand subCommand;
ILog log;
IDictionary<string, ICommand> subCommands;
CreateCommand createCommand;
[SetUp]
public void SetUp()
{
subCommandArgument = "subCommand";
subCommand = Substitute.For<ICommand>();
subCommand.ShowHelp(Arg.Any<string[]>()).Returns(ExitCode.Success);
log = Substitute.For<ILog>();
subCommands = Substitute.For<IDictionary<string, ICommand>>();
subCommands.ContainsKey(subCommandArgument).Returns(true);
subCommands[subCommandArgument] = subCommand;
createCommand = new CreateCommand(log, subCommands);
}
[Test]
public void should_call_show_help_on_subcommand()
{
createCommand.ShowHelp(new string[] { subCommandArgument });
subCommand.Received().ShowHelp(Arg.Any<string[]>());
}
[Test]
public void should_return_sub_command_exit_code()
{
ExitCode exitCode = createCommand.ShowHelp(new string[] { subCommandArgument });
exitCode.ShouldBe(ExitCode.Success);
}
}
[TestFixture]
public class when_requesting_help_with_invalid_subcommand_argument
{
string invalidSubCommandArgument;
ILog log;
IDictionary<string, ICommand> subCommands;
CreateCommand createCommand;
[SetUp]
public void SetUp()
{
invalidSubCommandArgument = "blah";
log = Substitute.For<ILog>();
subCommands = Substitute.For<IDictionary<string, ICommand>>();
subCommands.ContainsKey(invalidSubCommandArgument).Returns(false);
createCommand = new CreateCommand(log, subCommands);
}
[Test]
public void should_log_error_message()
{
createCommand.ShowHelp(new string[] { invalidSubCommandArgument });
log.Received().ErrorMessage(Messages.InvalidCommandMessage, invalidSubCommandArgument);
}
[Test]
public void should_return_error_exit_code()
{
ExitCode exitCode = createCommand.ShowHelp(new string[] { invalidSubCommandArgument });
exitCode.ShouldBe(ExitCode.Error);
}
}
public class Messages
{
public const string Usage = "usage: mulder create <object> [<args>]";
public static string BuildHelpMessage()
{
var sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine("usage: mulder create <object> [<args>]");
sb.AppendLine();
sb.AppendLine("create a mulder object");
sb.AppendLine();
sb.AppendLine(" Create different objects within mulder using this command.");
sb.AppendLine();
sb.AppendLine("objects:");
sb.AppendLine();
return sb.ToString();
}
public const string InvalidCommandMessage = "mulder: unknown command '{0}'. Run 'mulder help' for more info.";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Text;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
internal static class WinHttpResponseParser
{
private const string EncodingNameDeflate = "DEFLATE";
private const string EncodingNameGzip = "GZIP";
private const string HeaderNameContentEncoding = "Content-Encoding";
private const string HeaderNameContentLength = "Content-Length";
private const string HeaderNameSetCookie = "Set-Cookie";
private static readonly string[] s_HttpHeadersSeparator = { "\r\n" };
public static HttpResponseMessage CreateResponseMessage(
WinHttpRequestState state,
bool doManualDecompressionCheck)
{
HttpRequestMessage request = state.RequestMessage;
SafeWinHttpHandle requestHandle = state.RequestHandle;
CookieUsePolicy cookieUsePolicy = state.Handler.CookieUsePolicy;
CookieContainer cookieContainer = state.Handler.CookieContainer;
var response = new HttpResponseMessage();
bool stripEncodingHeaders = false;
// Get HTTP version, status code, reason phrase from the response headers.
string version = GetResponseHeaderStringInfo(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION);
if (string.Compare("HTTP/1.1", version, StringComparison.OrdinalIgnoreCase) == 0)
{
response.Version = HttpVersion.Version11;
}
else if (string.Compare("HTTP/1.0", version, StringComparison.OrdinalIgnoreCase) == 0)
{
response.Version = HttpVersion.Version10;
}
else
{
response.Version = HttpVersion.Unknown;
}
response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE);
response.ReasonPhrase = GetResponseHeaderStringInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT);
// Create response stream and wrap it in a StreamContent object.
var responseStream = new WinHttpResponseStream(state);
Stream decompressedStream = responseStream;
if (doManualDecompressionCheck)
{
string contentEncoding = GetResponseHeaderStringInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING);
if (!string.IsNullOrEmpty(contentEncoding))
{
if (contentEncoding.IndexOf(EncodingNameDeflate, StringComparison.OrdinalIgnoreCase) > -1)
{
decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
else if (contentEncoding.IndexOf(EncodingNameGzip, StringComparison.OrdinalIgnoreCase) > -1)
{
decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
}
}
var content = new StreamContent(decompressedStream);
response.Content = content;
response.RequestMessage = request;
// Parse raw response headers and place them into response message.
ParseResponseHeaders(requestHandle, response, stripEncodingHeaders);
// Store response header cookies into custom CookieContainer.
if (cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
Debug.Assert(cookieContainer != null);
if (response.Headers.Contains(HeaderNameSetCookie))
{
IEnumerable<string> cookieHeaders = response.Headers.GetValues(HeaderNameSetCookie);
foreach (var cookieHeader in cookieHeaders)
{
try
{
cookieContainer.SetCookies(request.RequestUri, cookieHeader);
}
catch (CookieException)
{
// We ignore malformed cookies in the response.
}
}
}
}
return response;
}
public static uint GetResponseHeaderNumberInfo(SafeWinHttpHandle requestHandle, uint infoLevel)
{
uint result = 0;
uint resultSize = sizeof(uint);
if (!Interop.WinHttp.WinHttpQueryHeaders(
requestHandle,
infoLevel | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
ref result,
ref resultSize,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return result;
}
private static string GetResponseHeaderStringInfo(SafeWinHttpHandle requestHandle, uint infoLevel)
{
uint bytesNeeded = 0;
bool results = false;
// Call WinHttpQueryHeaders once to obtain the size of the buffer needed. The size is returned in
// bytes but the API actually returns Unicode characters.
if (!Interop.WinHttp.WinHttpQueryHeaders(
requestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
null,
ref bytesNeeded,
IntPtr.Zero))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
// Allocate space for the buffer.
int charsNeeded = (int)bytesNeeded / 2;
var buffer = new StringBuilder(charsNeeded, charsNeeded);
results = Interop.WinHttp.WinHttpQueryHeaders(
requestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
buffer,
ref bytesNeeded,
IntPtr.Zero);
if (!results)
{
WinHttpException.ThrowExceptionUsingLastError();
}
return buffer.ToString();
}
private static void ParseResponseHeaders(
SafeWinHttpHandle requestHandle,
HttpResponseMessage response,
bool stripEncodingHeaders)
{
string rawResponseHeaders = GetResponseHeaderStringInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF);
string[] responseHeaderArray = rawResponseHeaders.Split(
s_HttpHeadersSeparator,
StringSplitOptions.RemoveEmptyEntries);
// Parse the array of headers and split them between Content headers and Response headers.
// Skip the first line which contains status code, etc. information that we already parsed.
for (int i = 1; i < responseHeaderArray.Length; i++)
{
int colonIndex = responseHeaderArray[i].IndexOf(':');
// Skip malformed header lines that are missing the colon character.
if (colonIndex > 0)
{
string headerName = responseHeaderArray[i].Substring(0, colonIndex);
string headerValue = responseHeaderArray[i].Substring(colonIndex + 1).Trim(); // Normalize header value by trimming white space.
if (!response.Headers.TryAddWithoutValidation(headerName, headerValue))
{
if (stripEncodingHeaders)
{
// Remove Content-Length and Content-Encoding headers if we are
// decompressing the response stream in the handler (due to
// WINHTTP not supporting it in a particular downlevel platform).
// This matches the behavior of WINHTTP when it does decompression iself.
if (string.Equals(
HeaderNameContentLength,
headerName,
StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (string.Equals(
HeaderNameContentEncoding,
headerName,
StringComparison.OrdinalIgnoreCase))
{
continue;
}
}
// TODO: Issue #2165. Should we log if there is an error here?
response.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace App.Web.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);
}
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Globalization
{
// needs to be kept in sync with CalendarDataType in System.Globalization.Native
internal enum CalendarDataType
{
Uninitialized = 0,
NativeName = 1,
MonthDay = 2,
ShortDates = 3,
LongDates = 4,
YearMonths = 5,
DayNames = 6,
AbbrevDayNames = 7,
MonthNames = 8,
AbbrevMonthNames = 9,
SuperShortDayNames = 10,
MonthGenitiveNames = 11,
AbbrevMonthGenitiveNames = 12,
EraNames = 13,
AbbrevEraNames = 14,
}
internal partial class CalendarData
{
private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
{
bool result = true;
result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName);
result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay);
this.sMonthDay = NormalizeDatePattern(this.sMonthDay);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames);
result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames);
result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames);
return result;
}
internal static int GetTwoDigitYearMax(CalendarId calendarId)
{
// There is no user override for this value on Linux or in ICU.
// So just return -1 to use the hard-coded defaults.
return -1;
}
// Call native side to figure out which calendars are allowed
internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars)
{
Debug.Assert(!GlobalizationMode.Invariant);
// NOTE: there are no 'user overrides' on Linux
int count = Interop.GlobalizationInterop.GetCalendars(localeName, calendars, calendars.Length);
// ensure there is at least 1 calendar returned
if (count == 0 && calendars.Length > 0)
{
calendars[0] = CalendarId.GREGORIAN;
count = 1;
}
return count;
}
private static bool SystemSupportsTaiwaneseCalendar()
{
return true;
}
// PAL Layer ends here
private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.CallStringMethod(
(locale, calId, type, stringBuilder) =>
Interop.GlobalizationInterop.GetCalendarInfo(
locale,
calId,
type,
stringBuilder,
stringBuilder.Capacity),
localeName,
calendarId,
dataType,
out calendarString);
}
private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns)
{
datePatterns = null;
CallbackContext callbackContext = new CallbackContext();
callbackContext.DisallowDuplicates = true;
bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
if (result)
{
List<string> datePatternsList = callbackContext.Results;
datePatterns = new string[datePatternsList.Count];
for (int i = 0; i < datePatternsList.Count; i++)
{
datePatterns[i] = NormalizeDatePattern(datePatternsList[i]);
}
}
return result;
}
/// <summary>
/// The ICU date format characters are not exactly the same as the .NET date format characters.
/// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern.
/// </summary>
/// <remarks>
/// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// </remarks>
private static string NormalizeDatePattern(string input)
{
StringBuilder destination = StringBuilderCache.Acquire(input.Length);
int index = 0;
while (index < input.Length)
{
switch (input[index])
{
case '\'':
// single quotes escape characters, like 'de' in es-SP
// so read verbatim until the next single quote
destination.Append(input[index++]);
while (index < input.Length)
{
char current = input[index++];
destination.Append(current);
if (current == '\'')
{
break;
}
}
break;
case 'E':
case 'e':
case 'c':
// 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
// 'e' in ICU is the local day of the week, which has no representation in .NET, but
// maps closest to 3 or 4 'd's in .NET
// 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
// maps closest to 3 or 4 'd's in .NET
NormalizeDayOfWeek(input, destination, ref index);
break;
case 'L':
case 'M':
// 'L' in ICU is the stand-alone name of the month,
// which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
// 'M' in both ICU and .NET is the month,
// but ICU supports 5 'M's, which is the super short month name
int occurrences = CountOccurrences(input, input[index], ref index);
if (occurrences > 4)
{
// 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
occurrences = 3;
}
destination.Append('M', occurrences);
break;
case 'G':
// 'G' in ICU is the era, which maps to 'g' in .NET
occurrences = CountOccurrences(input, 'G', ref index);
// it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
// have the same meaning
destination.Append('g');
break;
case 'y':
// a single 'y' in ICU is the year with no padding or trimming.
// a single 'y' in .NET is the year with 1 or 2 digits
// so convert any single 'y' to 'yyyy'
occurrences = CountOccurrences(input, 'y', ref index);
if (occurrences == 1)
{
occurrences = 4;
}
destination.Append('y', occurrences);
break;
default:
const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
string.Format(CultureInfo.InvariantCulture,
"Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
input[index]));
destination.Append(input[index++]);
break;
}
}
return StringBuilderCache.GetStringAndRelease(destination);
}
private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index)
{
char dayChar = input[index];
int occurrences = CountOccurrences(input, dayChar, ref index);
occurrences = Math.Max(occurrences, 3);
if (occurrences > 4)
{
// 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET
occurrences = 3;
}
destination.Append('d', occurrences);
}
private static int CountOccurrences(string input, char value, ref int index)
{
int startIndex = index;
while (index < input.Length && input[index] == value)
{
index++;
}
return index - startIndex;
}
private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames)
{
monthNames = null;
CallbackContext callbackContext = new CallbackContext();
bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
if (result)
{
// the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an
// extra empty string to fill the array.
if (callbackContext.Results.Count == 12)
{
callbackContext.Results.Add(string.Empty);
}
monthNames = callbackContext.Results.ToArray();
}
return result;
}
private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames)
{
bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames);
// .NET expects that only the Japanese calendars have more than 1 era.
// So for other calendars, only return the latest era.
if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0)
{
string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] };
eraNames = latestEraName;
}
return result;
}
internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData)
{
calendarData = null;
CallbackContext callbackContext = new CallbackContext();
bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
if (result)
{
calendarData = callbackContext.Results.ToArray();
}
return result;
}
private static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, CallbackContext callbackContext)
{
GCHandle context = GCHandle.Alloc(callbackContext);
try
{
return Interop.GlobalizationInterop.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)context);
}
finally
{
context.Free();
}
}
private static void EnumCalendarInfoCallback(string calendarString, IntPtr context)
{
try
{
CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target;
if (callbackContext.DisallowDuplicates)
{
foreach (string existingResult in callbackContext.Results)
{
if (string.Equals(calendarString, existingResult, StringComparison.Ordinal))
{
// the value is already in the results, so don't add it again
return;
}
}
}
callbackContext.Results.Add(calendarString);
}
catch (Exception e)
{
Debug.Assert(false, e.ToString());
// we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code.
// If we don't ignore the exception here that can cause the runtime to fail fast.
}
}
private class CallbackContext
{
private List<string> _results = new List<string>();
public CallbackContext()
{
}
public List<string> Results { get { return _results; } }
public bool DisallowDuplicates { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: A representation of a 32 bit 2's complement
** integer.
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Int32 : IComparable, IFormattable, IConvertible
, IComparable<Int32>, IEquatable<Int32>
{
internal int m_value;
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int32, this method throws an ArgumentException.
//
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (value is Int32) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt32"));
}
public int CompareTo(int value) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj) {
if (!(obj is Int32)) {
return false;
}
return m_value == ((Int32)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Int32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode() {
return m_value;
}
[Pure]
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public static int Parse(String s) {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static int Parse(String s, NumberStyles style) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, IFormatProvider provider) {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, out Int32 result) {
return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// Parses an integer from a String in the given style. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode() {
return TypeCode.Int32;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int32", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System
{
// A place holder class for signed bytes.
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct SByte : IComparable, IFormattable, IComparable<SByte>, IEquatable<SByte>, IConvertible
{
private sbyte _value;
// The maximum value that a Byte may represent: 127.
public const sbyte MaxValue = (sbyte)0x7F;
// The minimum value that a Byte may represent: -128.
public const sbyte MinValue = unchecked((sbyte)0x80);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type SByte, this method throws an ArgumentException.
//
public int CompareTo(Object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is SByte))
{
throw new ArgumentException(SR.Arg_MustBeSByte);
}
return _value - ((SByte)obj)._value;
}
public int CompareTo(SByte value)
{
return _value - value;
}
// Determines whether two Byte objects are equal.
public override bool Equals(Object obj)
{
if (!(obj is SByte))
{
return false;
}
return _value == ((SByte)obj)._value;
}
[NonVersionable]
public bool Equals(SByte obj)
{
return _value == obj;
}
// Gets a hash code for this instance.
public override int GetHashCode()
{
return ((int)_value ^ (int)_value << 8);
}
// Provides a string representation of a byte.
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt32(_value, null, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatInt32(_value, null, provider);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, null);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
if (_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(_value & 0x000000FF);
return FormatProvider.FormatUInt32(temp, format, provider);
}
return FormatProvider.FormatInt32(_value, format, provider);
}
[CLSCompliant(false)]
public static sbyte Parse(String s)
{
return Parse(s, NumberStyles.Integer, null);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style)
{
UInt32.ValidateParseStyleInteger(style);
return Parse(s, style, null);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, provider);
}
// Parses a signed byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider)
{
UInt32.ValidateParseStyleInteger(style);
int i = 0;
try
{
i = FormatProvider.ParseInt32(s, style, provider);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_SByte, e);
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > Byte.MaxValue)
{
throw new OverflowException(SR.Overflow_SByte);
}
return (sbyte)i;
}
if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)i;
}
[CLSCompliant(false)]
public static bool TryParse(String s, out SByte result)
{
return TryParse(s, NumberStyles.Integer, null, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result)
{
UInt32.ValidateParseStyleInteger(style);
result = 0;
int i;
if (!FormatProvider.TryParseInt32(s, style, provider, out i))
{
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > Byte.MaxValue)
{
return false;
}
result = (sbyte)i;
return true;
}
if (i < MinValue || i > MaxValue)
{
return false;
}
result = (sbyte)i;
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.SByte;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return _value;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return _value;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "SByte", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: class to sort arrays
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
namespace System.Collections.Generic
{
#region ArraySortHelper for single arrays
internal interface IArraySortHelper<TKey>
{
void Sort(TKey[] keys, int index, int length, IComparer<TKey> comparer);
int BinarySearch(TKey[] keys, int index, int length, TKey value, IComparer<TKey> comparer);
}
internal static class IntrospectiveSortUtilities
{
// This is the threshold where Introspective sort switches to Insertion sort.
// Imperically, 16 seems to speed up most cases without slowing down others, at least for integers.
// Large value types may benefit from a smaller number.
internal const int IntrosortSizeThreshold = 16;
internal static int FloorLog2(int n)
{
int result = 0;
while (n >= 1)
{
result++;
n = n / 2;
}
return result;
}
internal static void ThrowOrIgnoreBadComparer(Object comparer)
{
throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer));
}
}
[TypeDependencyAttribute("System.Collections.Generic.GenericArraySortHelper`1")]
internal class ArraySortHelper<T>
: IArraySortHelper<T>
{
private static volatile IArraySortHelper<T> defaultArraySortHelper;
public static IArraySortHelper<T> Default
{
get
{
IArraySortHelper<T> sorter = defaultArraySortHelper;
if (sorter == null)
sorter = CreateArraySortHelper();
return sorter;
}
}
private static IArraySortHelper<T> CreateArraySortHelper()
{
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
{
defaultArraySortHelper = (IArraySortHelper<T>)RuntimeTypeHandle.Allocate(typeof(GenericArraySortHelper<string>).TypeHandle.Instantiate(new Type[] { typeof(T) }));
}
else
{
defaultArraySortHelper = new ArraySortHelper<T>();
}
return defaultArraySortHelper;
}
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
IntrospectiveSort(keys, index, length, comparer.Compare);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
try
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
return InternalBinarySearch(array, index, length, value, comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
Debug.Assert(comparer != null, "Check the arguments in the caller!");
// Add a try block here to detect bogus comparisons
try
{
IntrospectiveSort(keys, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Contract.Requires(array != null, "Check the arguments in the caller!");
Contract.Requires(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order = comparer.Compare(array[i], value);
if (order == 0) return i;
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreater(T[] keys, Comparison<T> comparer, int a, int b)
{
if (a != b)
{
if (comparer(keys[a], keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(left >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length <= keys.Length);
Contract.Requires(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length), comparer);
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreater(keys, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreater(keys, comparer, lo, hi - 1);
SwapIfGreater(keys, comparer, lo, hi);
SwapIfGreater(keys, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
Contract.Ensures(Contract.Result<int>() >= lo && Contract.Result<int>() <= hi);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point
SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high
SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer(keys[++left], pivot) < 0) ;
while (comparer(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi >= lo);
Contract.Requires(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && comparer(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
[Serializable()]
internal class GenericArraySortHelper<T>
: IArraySortHelper<T>
where T : IComparable<T>
{
// Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
try
{
if (comparer == null || comparer == Comparer<T>.Default)
{
IntrospectiveSort(keys, index, length);
}
else
{
ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer.Compare);
}
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Debug.Assert(array != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
try
{
if (comparer == null || comparer == Comparer<T>.Default)
{
return BinarySearch(array, index, length, value);
}
else
{
return ArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer);
}
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
// This function is called when the user doesn't specify any comparer.
// Since T is constrained here, we can call IComparable<T>.CompareTo here.
// We can avoid boxing for value type and casting for reference types.
private static int BinarySearch(T[] array, int index, int length, T value)
{
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order;
if (array[i] == null)
{
order = (value == null) ? 0 : -1;
}
else
{
order = array[i].CompareTo(value);
}
if (order == 0)
{
return i;
}
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreaterWithItems(T[] keys, int a, int b)
{
Contract.Requires(keys != null);
Contract.Requires(0 <= a && a < keys.Length);
Contract.Requires(0 <= b && b < keys.Length);
if (a != b)
{
if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length)
{
Contract.Requires(keys != null);
Contract.Requires(left >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length <= keys.Length);
Contract.Requires(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length));
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, lo, hi - 1);
SwapIfGreaterWithItems(keys, lo, hi);
SwapIfGreaterWithItems(keys, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
Contract.Ensures(Contract.Result<int>() >= lo && Contract.Result<int>() <= hi);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
while (right > lo && keys[--right] != null) ;
}
else
{
while (pivot.CompareTo(keys[++left]) > 0) ;
while (pivot.CompareTo(keys[--right]) < 0) ;
}
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0))
{
child++;
}
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi >= lo);
Contract.Requires(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
#endregion
#region ArraySortHelper for paired key and value arrays
internal interface IArraySortHelper<TKey, TValue>
{
void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer);
}
[TypeDependencyAttribute("System.Collections.Generic.GenericArraySortHelper`2")]
internal class ArraySortHelper<TKey, TValue>
: IArraySortHelper<TKey, TValue>
{
private static volatile IArraySortHelper<TKey, TValue> defaultArraySortHelper;
public static IArraySortHelper<TKey, TValue> Default
{
get
{
IArraySortHelper<TKey, TValue> sorter = defaultArraySortHelper;
if (sorter == null)
sorter = CreateArraySortHelper();
return sorter;
}
}
private static IArraySortHelper<TKey, TValue> CreateArraySortHelper()
{
if (typeof(IComparable<TKey>).IsAssignableFrom(typeof(TKey)))
{
defaultArraySortHelper = (IArraySortHelper<TKey, TValue>)RuntimeTypeHandle.Allocate(typeof(GenericArraySortHelper<string, string>).TypeHandle.Instantiate(new Type[] { typeof(TKey), typeof(TValue) }));
}
else
{
defaultArraySortHelper = new ArraySortHelper<TKey, TValue>();
}
return defaultArraySortHelper;
}
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
comparer = Comparer<TKey>.Default;
}
IntrospectiveSort(keys, values, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer<TKey> comparer, int a, int b)
{
Contract.Requires(keys != null);
Contract.Requires(values == null || values.Length >= keys.Length);
Contract.Requires(comparer != null);
Contract.Requires(0 <= a && a < keys.Length);
Contract.Requires(0 <= b && b < keys.Length);
if (a != b)
{
if (comparer.Compare(keys[a], keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
if (values != null)
{
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
if (values != null)
{
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(left >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length <= keys.Length);
Contract.Requires(length + left <= keys.Length);
Contract.Requires(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length), comparer);
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
Contract.Ensures(Contract.Result<int>() >= lo && Contract.Result<int>() <= hi);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer.Compare(keys[++left], pivot) < 0) ;
while (comparer.Compare(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = (values != null) ? values[lo + i - 1] : default(TValue);
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
if (values != null)
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
if (values != null)
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(comparer != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi >= lo);
Contract.Requires(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = (values != null) ? values[i + 1] : default(TValue);
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
if (values != null)
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
if (values != null)
values[j + 1] = tValue;
}
}
}
internal class GenericArraySortHelper<TKey, TValue>
: IArraySortHelper<TKey, TValue>
where TKey : IComparable<TKey>
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
IntrospectiveSort(keys, values, index, length);
}
else
{
ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
}
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, int a, int b)
{
if (a != b)
{
if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
if (values != null)
{
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
if (values != null)
{
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(left >= 0);
Contract.Requires(length >= 0);
Contract.Requires(length <= keys.Length);
Contract.Requires(length + left <= keys.Length);
Contract.Requires(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2(keys.Length));
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, lo, hi);
SwapIfGreaterWithItems(keys, values, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
Contract.Ensures(Contract.Result<int>() >= lo && Contract.Result<int>() <= hi);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
while (right > lo && keys[--right] != null) ;
}
else
{
while (pivot.CompareTo(keys[++left]) > 0) ;
while (pivot.CompareTo(keys[--right]) < 0) ;
}
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi > lo);
Contract.Requires(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo)
{
Contract.Requires(keys != null);
Contract.Requires(lo >= 0);
Contract.Requires(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = (values != null) ? values[lo + i - 1] : default(TValue);
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0))
{
child++;
}
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
if (values != null)
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
if (values != null)
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi)
{
Contract.Requires(keys != null);
Contract.Requires(values != null);
Contract.Requires(lo >= 0);
Contract.Requires(hi >= lo);
Contract.Requires(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = (values != null) ? values[i + 1] : default(TValue);
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
if (values != null)
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
if (values != null)
values[j + 1] = tValue;
}
}
}
#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.Diagnostics;
using System.IO;
using System.Net.Mime;
using System.Text;
namespace System.Net
{
internal sealed class Base64Stream : DelegatedStream, IEncodableStream
{
private static readonly byte[] s_base64DecodeMap = new byte[] {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1
255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63, // 2
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,255,255,255, // 3
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 4
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255, // 5
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 6
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255, // 7
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // F
};
private static readonly byte[] s_base64EncodeMap = new byte[] {
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99,100,101,102,
103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,
119,120,121,122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47,
61
};
private readonly int _lineLength;
private readonly Base64WriteStateInfo _writeState;
private ReadStateInfo _readState;
//the number of bytes needed to encode three bytes (see algorithm description in Encode method below)
private const int SizeOfBase64EncodedChar = 4;
//bytes with this value in the decode map are invalid
private const byte InvalidBase64Value = 255;
internal Base64Stream(Stream stream, Base64WriteStateInfo writeStateInfo) : base(stream)
{
_writeState = new Base64WriteStateInfo();
_lineLength = writeStateInfo.MaxLineLength;
}
internal Base64Stream(Base64WriteStateInfo writeStateInfo) : base(new MemoryStream())
{
_lineLength = writeStateInfo.MaxLineLength;
_writeState = writeStateInfo;
}
private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo());
internal Base64WriteStateInfo WriteState
{
get
{
Debug.Assert(_writeState != null, "_writeState was null");
return _writeState;
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var result = new ReadAsyncResult(this, buffer, offset, count, callback, state);
result.Read();
return result;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var result = new WriteAsyncResult(this, buffer, offset, count, callback, state);
result.Write();
return result;
}
public override void Close()
{
if (_writeState != null && WriteState.Length > 0)
{
switch (WriteState.Padding)
{
case 1:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits], s_base64EncodeMap[64]);
break;
case 2:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits], s_base64EncodeMap[64], s_base64EncodeMap[64]);
break;
}
WriteState.Padding = 0;
FlushInternal();
}
base.Close();
}
public unsafe int DecodeBytes(byte[] buffer, int offset, int count)
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* source = start;
byte* dest = start;
byte* end = start + count;
while (source < end)
{
//space and tab are ok because folding must include a whitespace char.
if (*source == '\r' || *source == '\n' || *source == '=' || *source == ' ' || *source == '\t')
{
source++;
continue;
}
byte s = s_base64DecodeMap[*source];
if (s == InvalidBase64Value)
{
throw new FormatException(SR.MailBase64InvalidCharacter);
}
switch (ReadState.Pos)
{
case 0:
ReadState.Val = (byte)(s << 2);
ReadState.Pos++;
break;
case 1:
*dest++ = (byte)(ReadState.Val + (s >> 4));
ReadState.Val = unchecked((byte)(s << 4));
ReadState.Pos++;
break;
case 2:
*dest++ = (byte)(ReadState.Val + (s >> 2));
ReadState.Val = unchecked((byte)(s << 6));
ReadState.Pos++;
break;
case 3:
*dest++ = (byte)(ReadState.Val + s);
ReadState.Pos = 0;
break;
}
source++;
}
return (int)(dest - start);
}
}
public int EncodeBytes(byte[] buffer, int offset, int count) =>
EncodeBytes(buffer, offset, count, true, true);
internal int EncodeBytes(byte[] buffer, int offset, int count, bool dontDeferFinalBytes, bool shouldAppendSpaceToCRLF)
{
Debug.Assert(buffer != null, "buffer was null");
Debug.Assert(_writeState != null, "writestate was null");
Debug.Assert(_writeState.Buffer != null, "writestate.buffer was null");
// Add Encoding header, if any. e.g. =?encoding?b?
WriteState.AppendHeader();
int cur = offset;
switch (WriteState.Padding)
{
case 2:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits | ((buffer[cur] & 0xf0) >> 4)]);
if (count == 1)
{
WriteState.LastBits = (byte)((buffer[cur] & 0x0f) << 2);
WriteState.Padding = 1;
cur++;
return cur - offset;
}
WriteState.Append(s_base64EncodeMap[((buffer[cur] & 0x0f) << 2) | ((buffer[cur + 1] & 0xc0) >> 6)]);
WriteState.Append(s_base64EncodeMap[(buffer[cur + 1] & 0x3f)]);
cur += 2;
count -= 2;
WriteState.Padding = 0;
break;
case 1:
WriteState.Append(s_base64EncodeMap[WriteState.LastBits | ((buffer[cur] & 0xc0) >> 6)]);
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0x3f)]);
cur++;
count--;
WriteState.Padding = 0;
break;
}
int calcLength = cur + (count - (count % 3));
// Convert three bytes at a time to base64 notation. This will output 4 chars.
for (; cur < calcLength; cur += 3)
{
if ((_lineLength != -1) && (WriteState.CurrentLineLength + SizeOfBase64EncodedChar + _writeState.FooterLength > _lineLength))
{
WriteState.AppendCRLF(shouldAppendSpaceToCRLF);
}
//how we actually encode: get three bytes in the
//buffer to be encoded. Then, extract six bits at a time and encode each six bit chunk as a base-64 character.
//this means that three bytes of data will be encoded as four base64 characters. It also means that to encode
//a character, we must have three bytes to encode so if the number of bytes is not divisible by three, we
//must pad the buffer (this happens below)
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0xfc) >> 2]);
WriteState.Append(s_base64EncodeMap[((buffer[cur] & 0x03) << 4) | ((buffer[cur + 1] & 0xf0) >> 4)]);
WriteState.Append(s_base64EncodeMap[((buffer[cur + 1] & 0x0f) << 2) | ((buffer[cur + 2] & 0xc0) >> 6)]);
WriteState.Append(s_base64EncodeMap[(buffer[cur + 2] & 0x3f)]);
}
cur = calcLength; //Where we left off before
// See if we need to fold before writing the last section (with possible padding)
if ((count % 3 != 0) && (_lineLength != -1) && (WriteState.CurrentLineLength + SizeOfBase64EncodedChar + _writeState.FooterLength >= _lineLength))
{
WriteState.AppendCRLF(shouldAppendSpaceToCRLF);
}
//now pad this thing if we need to. Since it must be a number of bytes that is evenly divisble by 3,
//if there are extra bytes, pad with '=' until we have a number of bytes divisible by 3
switch (count % 3)
{
case 2: //One character padding needed
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0xFC) >> 2]);
WriteState.Append(s_base64EncodeMap[((buffer[cur] & 0x03) << 4) | ((buffer[cur + 1] & 0xf0) >> 4)]);
if (dontDeferFinalBytes)
{
WriteState.Append(s_base64EncodeMap[((buffer[cur + 1] & 0x0f) << 2)]);
WriteState.Append(s_base64EncodeMap[64]);
WriteState.Padding = 0;
}
else
{
WriteState.LastBits = (byte)((buffer[cur + 1] & 0x0F) << 2);
WriteState.Padding = 1;
}
cur += 2;
break;
case 1: // Two character padding needed
WriteState.Append(s_base64EncodeMap[(buffer[cur] & 0xFC) >> 2]);
if (dontDeferFinalBytes)
{
WriteState.Append(s_base64EncodeMap[(byte)((buffer[cur] & 0x03) << 4)]);
WriteState.Append(s_base64EncodeMap[64]);
WriteState.Append(s_base64EncodeMap[64]);
WriteState.Padding = 0;
}
else
{
WriteState.LastBits = (byte)((buffer[cur] & 0x03) << 4);
WriteState.Padding = 2;
}
cur++;
break;
}
// Write out the last footer, if any. e.g. ?=
WriteState.AppendFooter();
return cur - offset;
}
public Stream GetStream() => this;
public string GetEncodedString() => Encoding.ASCII.GetString(WriteState.Buffer, 0, WriteState.Length);
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
return ReadAsyncResult.End(asyncResult);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
WriteAsyncResult.End(asyncResult);
}
public override void Flush()
{
if (_writeState != null && WriteState.Length > 0)
{
FlushInternal();
}
base.Flush();
}
private void FlushInternal()
{
base.Write(WriteState.Buffer, 0, WriteState.Length);
WriteState.Reset();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(count));
for (;;)
{
// read data from the underlying stream
int read = base.Read(buffer, offset, count);
// if the underlying stream returns 0 then there
// is no more data - ust return 0.
if (read == 0)
{
return 0;
}
// while decoding, we may end up not having
// any bytes to return pending additional data
// from the underlying stream.
read = DecodeBytes(buffer, offset, read);
if (read > 0)
{
return read;
}
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
int written = 0;
// do not append a space when writing from a stream since this means
// it's writing the email body
for (;;)
{
written += EncodeBytes(buffer, offset + written, count - written, false, false);
if (written < count)
{
FlushInternal();
}
else
{
break;
}
}
}
private sealed class ReadAsyncResult : LazyAsyncResult
{
private readonly Base64Stream _parent;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _read;
private static readonly AsyncCallback s_onRead = OnRead;
internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
_offset = offset;
_count = count;
}
private bool CompleteRead(IAsyncResult result)
{
_read = _parent.BaseStream.EndRead(result);
// if the underlying stream returns 0 then there
// is no more data - ust return 0.
if (_read == 0)
{
InvokeCallback();
return true;
}
// while decoding, we may end up not having
// any bytes to return pending additional data
// from the underlying stream.
_read = _parent.DecodeBytes(_buffer, _offset, _read);
if (_read > 0)
{
InvokeCallback();
return true;
}
return false;
}
internal void Read()
{
for (;;)
{
IAsyncResult result = _parent.BaseStream.BeginRead(_buffer, _offset, _count, s_onRead, this);
if (!result.CompletedSynchronously || CompleteRead(result))
{
break;
}
}
}
private static void OnRead(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
try
{
if (!thisPtr.CompleteRead(result))
{
thisPtr.Read();
}
}
catch (Exception e)
{
if (thisPtr.IsCompleted)
{
throw;
}
thisPtr.InvokeCallback(e);
}
}
}
internal static int End(IAsyncResult result)
{
ReadAsyncResult thisPtr = (ReadAsyncResult)result;
thisPtr.InternalWaitForCompletion();
return thisPtr._read;
}
}
private sealed class WriteAsyncResult : LazyAsyncResult
{
private static readonly AsyncCallback s_onWrite = OnWrite;
private readonly Base64Stream _parent;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _written;
internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
_offset = offset;
_count = count;
}
internal void Write()
{
for (;;)
{
// do not append a space when writing from a stream since this means
// it's writing the email body
_written += _parent.EncodeBytes(_buffer, _offset + _written, _count - _written, false, false);
if (_written < _count)
{
IAsyncResult result = _parent.BaseStream.BeginWrite(_parent.WriteState.Buffer, 0, _parent.WriteState.Length, s_onWrite, this);
if (!result.CompletedSynchronously)
{
break;
}
CompleteWrite(result);
}
else
{
InvokeCallback();
break;
}
}
}
private void CompleteWrite(IAsyncResult result)
{
_parent.BaseStream.EndWrite(result);
_parent.WriteState.Reset();
}
private static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
try
{
thisPtr.CompleteWrite(result);
thisPtr.Write();
}
catch (Exception e)
{
if (thisPtr.IsCompleted)
{
throw;
}
thisPtr.InvokeCallback(e);
}
}
}
internal static void End(IAsyncResult result)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result;
thisPtr.InternalWaitForCompletion();
Debug.Assert(thisPtr._written == thisPtr._count);
}
}
private sealed class ReadStateInfo
{
internal byte Val { get; set; }
internal byte Pos { get; set; }
}
}
}
| |
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Portions copyright 2007 ThoughtWorks, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml.XPath;
using IEWrapper;
using mshtml;
using SHDocVw;
using WebDriver.XPath;
namespace WebDriver
{
internal class IeWrapper : WebDriver, IXPathNavigable, IDisposable
{
private InternetExplorer browser;
private bool shouldWait = true;
private int currentFrame = 0;
private InternetExplorerDriver parent;
public IeWrapper(InternetExplorerDriver parent) : this(parent, new InternetExplorer())
{
}
public IeWrapper(InternetExplorerDriver parent, InternetExplorer toWrap)
{
this.parent = parent;
browser = toWrap;
browser.NewWindow2 +=
delegate(ref object ppDisp, ref bool Cancel)
{
InternetExplorer newWindow = new InternetExplorer();
newWindow.Visible = browser.Visible;
ppDisp = newWindow;
parent.AddWrapper(new IeWrapper(parent, newWindow));
};
Visible = false;
}
public string Title
{
get
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
return HtmlDocument.title;
}
}
public bool Visible
{
get { return browser.Visible; }
set { browser.Visible = value; }
}
public string CurrentUrl
{
get
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
return HtmlDocument.url;
}
}
private void Navigate(string url)
{
object flags = null;
object objectTargetFrameName = null;
object postData = null;
object headers = null;
browser.Navigate(url, ref flags, ref objectTargetFrameName, ref postData, ref headers);
}
public void Get(string url)
{
Navigate(url);
WaitForLoadToComplete();
currentFrame = 0;
}
internal void WaitForLoadToComplete()
{
shouldWait = false;
if (browser == null)
{
return;
}
while (browser.Busy)
{
Thread.Sleep(10);
}
while (browser.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE)
{
Thread.Sleep(20);
}
WaitForDocumentToComplete(HtmlDocument);
FramesCollection frames = ((IHTMLDocument2)browser.Document).frames;
if (frames != null)
{
for (int i = 0; i < frames.length; i++)
{
object refIndex = currentFrame;
IHTMLWindow2 frame = (IHTMLWindow2)frames.item(ref refIndex);
WaitForDocumentToComplete(frame.document);
}
}
}
private void WaitForDocumentToComplete(IHTMLDocument2 doc)
{
while (doc.readyState != "complete")
{
Thread.Sleep(20);
}
}
public void DumpBody()
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
// Console.WriteLine(GetDocumentText());
}
public void Close()
{
browser.Quit();
}
public string SelectTextWithXPath(string xpath)
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
XPathNavigator navigator = CreateNavigator();
XPathNodeIterator iterator = navigator.Select(xpath);
if (iterator.Count == 0)
return null;
iterator.MoveNext();
return iterator.Current.Value.Trim();
}
public ArrayList SelectElementsByXPath(string xpath)
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
XPathNavigator navigator = CreateNavigator();
XPathNodeIterator nodes = navigator.Select(xpath);
IEnumerator allNodes = nodes.GetEnumerator();
ArrayList elements = new ArrayList();
while (allNodes.MoveNext())
{
NavigableDocument node = (NavigableDocument) allNodes.Current;
elements.Add(new WrappedWebElement(this, node.UnderlyingObject as IHTMLDOMNode));
}
return elements;
}
public WebElement SelectElement(string selector)
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
if (selector.StartsWith("link="))
{
return SelectLinkWithText(selector);
}
else if (selector.StartsWith("id="))
{
return SelectElementById(selector);
}
else
{
XPathNavigator navigator = CreateNavigator();
NavigableDocument node = navigator.SelectSingleNode(selector) as NavigableDocument;
if (node == null)
throw new NoSuchElementException("Cannot find an element with the expression: " + selector);
return new WrappedWebElement(this, node.UnderlyingObject as IHTMLDOMNode);
}
}
public XPathNavigator CreateNavigator()
{
if (shouldWait)
WaitForDocumentToComplete(HtmlDocument);
return new NavigableDocument(HtmlDocument);
}
public void Dispose()
{
Marshal.ReleaseComObject(browser);
browser = null;
}
private WebElement SelectLinkWithText(String selector)
{
int equalsIndex = selector.IndexOf('=') + 1;
string linkText = selector.Substring(equalsIndex).Trim();
IHTMLElementCollection links = HtmlDocument.links;
IEnumerator enumerator = links.GetEnumerator();
while (enumerator.MoveNext())
{
IHTMLElement element = (IHTMLElement) enumerator.Current;
if (element.innerText == linkText)
{
return new WrappedWebElement(this, (IHTMLDOMNode) element);
}
}
throw new NoSuchElementException("Cannot find link with text: " + linkText);
}
private WebElement SelectElementById(String selector)
{
int equalsIndex = selector.IndexOf('=') + 1;
string id = selector.Substring(equalsIndex).Trim();
IHTMLElement element = ((IHTMLDocument3) HtmlDocument).getElementById(id);
if (element != null)
{
return new WrappedWebElement(this, (IHTMLDOMNode) element);
}
throw new NoSuchElementException("Cannot find element with id: " + selector);
}
private IHTMLDocument2 HtmlDocument
{
get
{
try
{
FramesCollection frames = ((IHTMLDocument2)browser.Document).frames;
if (frames.length == 0)
return browser.Document as IHTMLDocument2;
object refIndex = currentFrame;
IHTMLWindow2 frame = (IHTMLWindow2) frames.item(ref refIndex);
return frame.document;
}
catch (COMException)
{
return null;
}
}
}
private WebDriver SwitchToFrame(int index)
{
FramesCollection frames = ((IHTMLDocument2)browser.Document).frames;
if (!(index < frames.length))
{
throw new IndexOutOfRangeException("There are only " + frames.length +
" frames to use. You index was out of bounds: " + index);
}
currentFrame = index;
return this;
}
public TargetLocator SwitchTo()
{
return new IeWrapperTargetLocator(this);
}
private class IeWrapperTargetLocator : TargetLocator
{
private IeWrapper parent;
public IeWrapperTargetLocator(IeWrapper parent)
{
this.parent = parent;
}
public WebDriver Frame(int index)
{
parent.SwitchToFrame(index);
return parent.parent;
}
public WebDriver Window(int index)
{
return parent.parent.SwitchToWindow(index);
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.Serialization
{
/// <summary>
/// Writes a proto buffer to an XML document or fragment. .NET 3.5 users may also
/// use this class to produce Json by setting the options to support Json and providing
/// an XmlWriter obtained from <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory"/>.
/// </summary>
public class XmlFormatWriter : AbstractTextWriter
{
private static readonly Encoding DefaultEncoding = new UTF8Encoding(false);
public const string DefaultRootElementName = "root";
private readonly XmlWriter _output;
// The default element name used for WriteMessageStart
private string _rootElementName;
// Used to assert matching WriteMessageStart/WriteMessageEnd calls
private int _messageOpenCount;
private static XmlWriterSettings DefaultSettings(Encoding encoding)
{
return new XmlWriterSettings()
{
CheckCharacters = false,
NewLineHandling = NewLineHandling.Entitize,
OmitXmlDeclaration = true,
Encoding = encoding,
};
}
/// <summary>
/// Constructs the XmlFormatWriter to write to the given TextWriter
/// </summary>
public static XmlFormatWriter CreateInstance(TextWriter output)
{
return new XmlFormatWriter(XmlWriter.Create(output, DefaultSettings(output.Encoding)));
}
/// <summary>
/// Constructs the XmlFormatWriter to write to the given stream
/// </summary>
public static XmlFormatWriter CreateInstance(Stream output)
{
return new XmlFormatWriter(XmlWriter.Create(output, DefaultSettings(DefaultEncoding)));
}
/// <summary>
/// Constructs the XmlFormatWriter to write to the given stream
/// </summary>
public static XmlFormatWriter CreateInstance(Stream output, Encoding encoding)
{
return new XmlFormatWriter(XmlWriter.Create(output, DefaultSettings(encoding)));
}
/// <summary>
/// Constructs the XmlFormatWriter to write to the given XmlWriter
/// </summary>
public static XmlFormatWriter CreateInstance(XmlWriter output)
{
return new XmlFormatWriter(output);
}
protected XmlFormatWriter(XmlWriter output)
{
_output = output;
_messageOpenCount = 0;
_rootElementName = DefaultRootElementName;
}
/// <summary>
/// Gets or sets the default element name to use when using the Merge<TBuilder>()
/// </summary>
public string RootElementName
{
get { return _rootElementName; }
set
{
ThrowHelper.ThrowIfNull(value, "RootElementName");
_rootElementName = value;
}
}
/// <summary>
/// Gets or sets the options to use while generating the XML
/// </summary>
public XmlWriterOptions Options { get; set; }
/// <summary>
/// Sets the options to use while generating the XML
/// </summary>
public XmlFormatWriter SetOptions(XmlWriterOptions options)
{
Options = options;
return this;
}
private bool TestOption(XmlWriterOptions option)
{
return (Options & option) != 0;
}
/// <summary>
/// Completes any pending write operations
/// </summary>
public override void Flush()
{
_output.Flush();
base.Flush();
}
/// <summary>
/// Used to write the root-message preamble, in xml this is open element for RootElementName,
/// by default "<root>". After this call you can call IMessageLite.MergeTo(...) and
/// complete the message with a call to WriteMessageEnd().
/// </summary>
public override void WriteMessageStart()
{
WriteMessageStart(_rootElementName);
}
/// <summary>
/// Used to write the root-message preamble, in xml this is open element for elementName.
/// After this call you can call IMessageLite.MergeTo(...) and complete the message with
/// a call to WriteMessageEnd().
/// </summary>
public void WriteMessageStart(string elementName)
{
if (TestOption(XmlWriterOptions.OutputJsonTypes))
{
_output.WriteStartElement("root"); // json requires this is the root-element
_output.WriteAttributeString("type", "object");
}
else
{
_output.WriteStartElement(elementName);
}
_messageOpenCount++;
}
/// <summary>
/// Used to complete a root-message previously started with a call to WriteMessageStart()
/// </summary>
public override void WriteMessageEnd()
{
if (_messageOpenCount <= 0)
{
throw new InvalidOperationException();
}
_output.WriteEndElement();
_output.Flush();
_messageOpenCount--;
}
/// <summary>
/// Writes a message as an element using the name defined in <see cref="RootElementName"/>
/// </summary>
public override void WriteMessage(IMessageLite message)
{
WriteMessage(_rootElementName, message);
}
/// <summary>
/// Writes a message as an element with the given name
/// </summary>
public void WriteMessage(string elementName, IMessageLite message)
{
WriteMessageStart(elementName);
message.WriteTo(this);
WriteMessageEnd();
}
/// <summary>
/// Writes a message
/// </summary>
protected override void WriteMessageOrGroup(string field, IMessageLite message)
{
_output.WriteStartElement(field);
if (TestOption(XmlWriterOptions.OutputJsonTypes))
{
_output.WriteAttributeString("type", "object");
}
message.WriteTo(this);
_output.WriteEndElement();
}
/// <summary>
/// Writes a String value
/// </summary>
protected override void WriteAsText(string field, string textValue, object typedValue)
{
_output.WriteStartElement(field);
if (TestOption(XmlWriterOptions.OutputJsonTypes))
{
if (typedValue is int || typedValue is uint || typedValue is long || typedValue is ulong ||
typedValue is double || typedValue is float)
{
_output.WriteAttributeString("type", "number");
}
else if (typedValue is bool)
{
_output.WriteAttributeString("type", "boolean");
}
}
_output.WriteString(textValue);
//Empty strings should not be written as empty elements '<item/>', rather as '<item></item>'
if (_output.WriteState == WriteState.Element)
{
_output.WriteRaw("");
}
_output.WriteEndElement();
}
/// <summary>
/// Writes an array of field values
/// </summary>
protected override void WriteArray(FieldType fieldType, string field, IEnumerable items)
{
//see if it's empty
IEnumerator eitems = items.GetEnumerator();
try
{
if (!eitems.MoveNext())
{
return;
}
}
finally
{
if (eitems is IDisposable)
{
((IDisposable) eitems).Dispose();
}
}
if (TestOption(XmlWriterOptions.OutputNestedArrays | XmlWriterOptions.OutputJsonTypes))
{
_output.WriteStartElement(field);
if (TestOption(XmlWriterOptions.OutputJsonTypes))
{
_output.WriteAttributeString("type", "array");
}
base.WriteArray(fieldType, "item", items);
_output.WriteEndElement();
}
else
{
base.WriteArray(fieldType, field, items);
}
}
/// <summary>
/// Writes a System.Enum by the numeric and textual value
/// </summary>
protected override void WriteEnum(string field, int number, string name)
{
_output.WriteStartElement(field);
if (!TestOption(XmlWriterOptions.OutputJsonTypes) && TestOption(XmlWriterOptions.OutputEnumValues))
{
_output.WriteAttributeString("value", XmlConvert.ToString(number));
}
_output.WriteString(name);
_output.WriteEndElement();
}
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG 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.
// -------------------------------------------------------------------------
//
// Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com)
//
// newtelligence is a registered trademark of newtelligence Aktiengesellschaft.
//
// For portions of this software, the some additional copyright notices may apply
// which can either be found in the license.txt file included in the source distribution
// or following this notice.
//
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;
namespace newtelligence.DasBlog.Web
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public partial class CrosspostReferrersBox : StatisticsListBase
{
protected SiteConfig siteConfig = SiteConfig.GetSiteConfig();
protected void Page_Load(object sender, EventArgs e)
{
}
#region Web Form Designer generated code
protected override void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
this.PreRender += new EventHandler(this.CrosspostReferrersBox_PreRender);
}
#endregion
private void BuildCrosspostReferrersRow(TableRow row, StatisticsItem item, object objDataService)
{
IBlogDataService dataService = objDataService as IBlogDataService;
HyperLink link = new HyperLink();
string text = SiteUtilities.ClipString(item.identifier, 80);
if (item.identifier != null && item.identifier.Length > 0)
{
int idx;
string id;
// urls in the log have been written using URL Rewriting
if (item.identifier.IndexOf("guid,") > -1)
{
string guid = item.identifier.Substring(0, item.identifier.Length - 5);
idx = guid.IndexOf("guid,");
id = guid.Substring(idx + 5);
}
else
{
idx = item.identifier.IndexOf("guid=");
id = item.identifier.Substring(idx + 5);
}
Entry entry = dataService.GetEntry(id);
if (entry != null && entry.Title != null && entry.Title.Length > 0)
{
text = SiteUtilities.ClipString(entry.Title, 80);
}
}
link.Text = text;
link.NavigateUrl = item.identifier.ToString();
row.Cells[0].Controls.Add(link);
row.Cells[1].Text = item.count.ToString();
}
private void CrosspostReferrersBox_PreRender(object sender, EventArgs e)
{
Control root = contentPlaceHolder;
ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
string siteRoot = siteConfig.Root.ToUpper();
Dictionary<string, int> CrosspostReferrerUrls = new Dictionary<string, int>();
Dictionary<string, int> userAgents = new Dictionary<string, int>();
Dictionary<string, int> referrerUrls = new Dictionary<string, int>();
Dictionary<string, int> userDomains = new Dictionary<string, int>();
// get the user's local time
DateTime utcTime = DateTime.UtcNow;
DateTime localTime = siteConfig.GetConfiguredTimeZone().ToLocalTime(utcTime);
if (Request.QueryString["date"] != null)
{
try
{
DateTime popUpTime = DateTime.ParseExact(Request.QueryString["date"], "yyyy-MM-dd", CultureInfo.InvariantCulture);
utcTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, utcTime.Hour, utcTime.Minute, utcTime.Second);
localTime = new DateTime(popUpTime.Year, popUpTime.Month, popUpTime.Day, localTime.Hour, localTime.Minute, localTime.Second);
}
catch (FormatException ex)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
}
}
LogDataItemCollection logItems = new LogDataItemCollection();
logItems.AddRange(logService.GetCrosspostReferrersForDay(localTime));
if (siteConfig.AdjustDisplayTimeZone)
{
newtelligence.DasBlog.Util.WindowsTimeZone tz = siteConfig.GetConfiguredTimeZone();
TimeSpan ts = tz.GetUtcOffset(DateTime.UtcNow);
int offset = ts.Hours;
if (offset < 0)
{
logItems.AddRange(logService.GetCrosspostReferrersForDay(localTime.AddDays(1)));
}
else
{
logItems.AddRange(logService.GetCrosspostReferrersForDay(localTime.AddDays(-1)));
}
}
foreach (LogDataItem log in logItems)
{
bool exclude = false;
if (log.UrlReferrer != null)
{
exclude = log.UrlReferrer.ToUpper().StartsWith(siteRoot);
}
if (siteConfig.AdjustDisplayTimeZone)
{
if (siteConfig.GetConfiguredTimeZone().ToLocalTime(log.RequestedUtc).Date != localTime.Date)
{
exclude = true;
}
}
if (!exclude)
{
if (!referrerUrls.ContainsKey(log.UrlReferrer))
{
referrerUrls[log.UrlReferrer] = 0;
}
referrerUrls[log.UrlReferrer] = referrerUrls[log.UrlReferrer] + 1;
if (!CrosspostReferrerUrls.ContainsKey(log.UrlRequested))
{
CrosspostReferrerUrls[log.UrlRequested] = 0;
}
CrosspostReferrerUrls[log.UrlRequested] = CrosspostReferrerUrls[log.UrlRequested] + 1;
if (!userAgents.ContainsKey(log.UserAgent))
{
userAgents[log.UserAgent] = 0;
}
userAgents[log.UserAgent] = userAgents[log.UserAgent] + 1;
if(!userDomains.ContainsKey(log.UserDomain))
{
userDomains[log.UserDomain] = 0;
}
userDomains[log.UserDomain] = userDomains[log.UserDomain] + 1;
}
}
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(CrosspostReferrerUrls), resmgr.GetString("text_activity_read_posts"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildCrosspostReferrersRow), dataService));
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(referrerUrls), resmgr.GetString("text_activity_referrer_urls"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildReferrerRow), dataService));
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userDomains), resmgr.GetString("text_activity_user_domains"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildUserDomainRow), dataService));
root.Controls.Add(BuildStatisticsTable(GenerateSortedItemList(userAgents), resmgr.GetString("text_activity_user_agent"), resmgr.GetString("text_activity_hits"), new StatisticsBuilderCallback(this.BuildAgentsRow), dataService));
DataBind();
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// 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
namespace OpenTK.Graphics.ES10
{
using System;
using System.Text;
using System.Runtime.InteropServices;
#pragma warning disable 0649
#pragma warning disable 3019
#pragma warning disable 1591
partial class GL
{
internal static partial class Delegates
{
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ActiveTexture(OpenTK.Graphics.ES10.All texture);
internal static ActiveTexture glActiveTexture;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void AlphaFunc(OpenTK.Graphics.ES10.All func, Single @ref);
internal static AlphaFunc glAlphaFunc;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void AlphaFuncx(OpenTK.Graphics.ES10.All func, int @ref);
internal static AlphaFuncx glAlphaFuncx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void BindTexture(OpenTK.Graphics.ES10.All target, UInt32 texture);
internal static BindTexture glBindTexture;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void BlendFunc(OpenTK.Graphics.ES10.All sfactor, OpenTK.Graphics.ES10.All dfactor);
internal static BlendFunc glBlendFunc;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Clear(UInt32 mask);
internal static Clear glClear;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ClearColor(Single red, Single green, Single blue, Single alpha);
internal static ClearColor glClearColor;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ClearColorx(int red, int green, int blue, int alpha);
internal static ClearColorx glClearColorx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ClearDepthf(Single depth);
internal static ClearDepthf glClearDepthf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ClearDepthx(int depth);
internal static ClearDepthx glClearDepthx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ClearStencil(Int32 s);
internal static ClearStencil glClearStencil;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ClientActiveTexture(OpenTK.Graphics.ES10.All texture);
internal static ClientActiveTexture glClientActiveTexture;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Color4f(Single red, Single green, Single blue, Single alpha);
internal static Color4f glColor4f;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Color4x(int red, int green, int blue, int alpha);
internal static Color4x glColor4x;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ColorMask(bool red, bool green, bool blue, bool alpha);
internal static ColorMask glColorMask;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ColorPointer(Int32 size, OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
internal static ColorPointer glColorPointer;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void CompressedTexImage2D(OpenTK.Graphics.ES10.All target, Int32 level, OpenTK.Graphics.ES10.All internalformat, Int32 width, Int32 height, Int32 border, Int32 imageSize, IntPtr data);
internal static CompressedTexImage2D glCompressedTexImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void CompressedTexSubImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, OpenTK.Graphics.ES10.All format, Int32 imageSize, IntPtr data);
internal static CompressedTexSubImage2D glCompressedTexSubImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void CopyTexImage2D(OpenTK.Graphics.ES10.All target, Int32 level, OpenTK.Graphics.ES10.All internalformat, Int32 x, Int32 y, Int32 width, Int32 height, Int32 border);
internal static CopyTexImage2D glCopyTexImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void CopyTexSubImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 x, Int32 y, Int32 width, Int32 height);
internal static CopyTexSubImage2D glCopyTexSubImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void CullFace(OpenTK.Graphics.ES10.All mode);
internal static CullFace glCullFace;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void DeleteTextures(Int32 n, UInt32* textures);
internal unsafe static DeleteTextures glDeleteTextures;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DepthFunc(OpenTK.Graphics.ES10.All func);
internal static DepthFunc glDepthFunc;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DepthMask(bool flag);
internal static DepthMask glDepthMask;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DepthRangef(Single zNear, Single zFar);
internal static DepthRangef glDepthRangef;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DepthRangex(int zNear, int zFar);
internal static DepthRangex glDepthRangex;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Disable(OpenTK.Graphics.ES10.All cap);
internal static Disable glDisable;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DisableClientState(OpenTK.Graphics.ES10.All array);
internal static DisableClientState glDisableClientState;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DrawArrays(OpenTK.Graphics.ES10.All mode, Int32 first, Int32 count);
internal static DrawArrays glDrawArrays;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void DrawElements(OpenTK.Graphics.ES10.All mode, Int32 count, OpenTK.Graphics.ES10.All type, IntPtr indices);
internal static DrawElements glDrawElements;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Enable(OpenTK.Graphics.ES10.All cap);
internal static Enable glEnable;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void EnableClientState(OpenTK.Graphics.ES10.All array);
internal static EnableClientState glEnableClientState;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Finish();
internal static Finish glFinish;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Flush();
internal static Flush glFlush;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Fogf(OpenTK.Graphics.ES10.All pname, Single param);
internal static Fogf glFogf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void Fogfv(OpenTK.Graphics.ES10.All pname, Single* @params);
internal unsafe static Fogfv glFogfv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Fogx(OpenTK.Graphics.ES10.All pname, int param);
internal static Fogx glFogx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void Fogxv(OpenTK.Graphics.ES10.All pname, int* @params);
internal unsafe static Fogxv glFogxv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void FrontFace(OpenTK.Graphics.ES10.All mode);
internal static FrontFace glFrontFace;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Frustumf(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar);
internal static Frustumf glFrustumf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Frustumx(int left, int right, int bottom, int top, int zNear, int zFar);
internal static Frustumx glFrustumx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void GenTextures(Int32 n, UInt32* textures);
internal unsafe static GenTextures glGenTextures;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate OpenTK.Graphics.ES10.All GetError();
internal static GetError glGetError;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void GetIntegerv(OpenTK.Graphics.ES10.All pname, Int32* @params);
internal unsafe static GetIntegerv glGetIntegerv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate System.IntPtr GetString(OpenTK.Graphics.ES10.All name);
internal unsafe static GetString glGetString;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Hint(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All mode);
internal static Hint glHint;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Lightf(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, Single param);
internal static Lightf glLightf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void Lightfv(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, Single* @params);
internal unsafe static Lightfv glLightfv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void LightModelf(OpenTK.Graphics.ES10.All pname, Single param);
internal static LightModelf glLightModelf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void LightModelfv(OpenTK.Graphics.ES10.All pname, Single* @params);
internal unsafe static LightModelfv glLightModelfv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void LightModelx(OpenTK.Graphics.ES10.All pname, int param);
internal static LightModelx glLightModelx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void LightModelxv(OpenTK.Graphics.ES10.All pname, int* @params);
internal unsafe static LightModelxv glLightModelxv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Lightx(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, int param);
internal static Lightx glLightx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void Lightxv(OpenTK.Graphics.ES10.All light, OpenTK.Graphics.ES10.All pname, int* @params);
internal unsafe static Lightxv glLightxv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void LineWidth(Single width);
internal static LineWidth glLineWidth;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void LineWidthx(int width);
internal static LineWidthx glLineWidthx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void LoadIdentity();
internal static LoadIdentity glLoadIdentity;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void LoadMatrixf(Single* m);
internal unsafe static LoadMatrixf glLoadMatrixf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void LoadMatrixx(int* m);
internal unsafe static LoadMatrixx glLoadMatrixx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void LogicOp(OpenTK.Graphics.ES10.All opcode);
internal static LogicOp glLogicOp;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Materialf(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, Single param);
internal static Materialf glMaterialf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void Materialfv(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, Single* @params);
internal unsafe static Materialfv glMaterialfv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Materialx(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, int param);
internal static Materialx glMaterialx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void Materialxv(OpenTK.Graphics.ES10.All face, OpenTK.Graphics.ES10.All pname, int* @params);
internal unsafe static Materialxv glMaterialxv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void MatrixMode(OpenTK.Graphics.ES10.All mode);
internal static MatrixMode glMatrixMode;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void MultiTexCoord4f(OpenTK.Graphics.ES10.All target, Single s, Single t, Single r, Single q);
internal static MultiTexCoord4f glMultiTexCoord4f;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void MultiTexCoord4x(OpenTK.Graphics.ES10.All target, int s, int t, int r, int q);
internal static MultiTexCoord4x glMultiTexCoord4x;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void MultMatrixf(Single* m);
internal unsafe static MultMatrixf glMultMatrixf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void MultMatrixx(int* m);
internal unsafe static MultMatrixx glMultMatrixx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Normal3f(Single nx, Single ny, Single nz);
internal static Normal3f glNormal3f;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Normal3x(int nx, int ny, int nz);
internal static Normal3x glNormal3x;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void NormalPointer(OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
internal static NormalPointer glNormalPointer;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Orthof(Single left, Single right, Single bottom, Single top, Single zNear, Single zFar);
internal static Orthof glOrthof;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Orthox(int left, int right, int bottom, int top, int zNear, int zFar);
internal static Orthox glOrthox;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PixelStorei(OpenTK.Graphics.ES10.All pname, Int32 param);
internal static PixelStorei glPixelStorei;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PointSize(Single size);
internal static PointSize glPointSize;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PointSizex(int size);
internal static PointSizex glPointSizex;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PolygonOffset(Single factor, Single units);
internal static PolygonOffset glPolygonOffset;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PolygonOffsetx(int factor, int units);
internal static PolygonOffsetx glPolygonOffsetx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PopMatrix();
internal static PopMatrix glPopMatrix;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void PushMatrix();
internal static PushMatrix glPushMatrix;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ReadPixels(Int32 x, Int32 y, Int32 width, Int32 height, OpenTK.Graphics.ES10.All format, OpenTK.Graphics.ES10.All type, IntPtr pixels);
internal static ReadPixels glReadPixels;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Rotatef(Single angle, Single x, Single y, Single z);
internal static Rotatef glRotatef;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Rotatex(int angle, int x, int y, int z);
internal static Rotatex glRotatex;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void SampleCoverage(Single value, bool invert);
internal static SampleCoverage glSampleCoverage;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void SampleCoveragex(int value, bool invert);
internal static SampleCoveragex glSampleCoveragex;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Scalef(Single x, Single y, Single z);
internal static Scalef glScalef;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Scalex(int x, int y, int z);
internal static Scalex glScalex;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Scissor(Int32 x, Int32 y, Int32 width, Int32 height);
internal static Scissor glScissor;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void ShadeModel(OpenTK.Graphics.ES10.All mode);
internal static ShadeModel glShadeModel;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void StencilFunc(OpenTK.Graphics.ES10.All func, Int32 @ref, UInt32 mask);
internal static StencilFunc glStencilFunc;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void StencilMask(UInt32 mask);
internal static StencilMask glStencilMask;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void StencilOp(OpenTK.Graphics.ES10.All fail, OpenTK.Graphics.ES10.All zfail, OpenTK.Graphics.ES10.All zpass);
internal static StencilOp glStencilOp;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexCoordPointer(Int32 size, OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
internal static TexCoordPointer glTexCoordPointer;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexEnvf(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, Single param);
internal static TexEnvf glTexEnvf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void TexEnvfv(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, Single* @params);
internal unsafe static TexEnvfv glTexEnvfv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexEnvx(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, int param);
internal static TexEnvx glTexEnvx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal unsafe delegate void TexEnvxv(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, int* @params);
internal unsafe static TexEnvxv glTexEnvxv;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 internalformat, Int32 width, Int32 height, Int32 border, OpenTK.Graphics.ES10.All format, OpenTK.Graphics.ES10.All type, IntPtr pixels);
internal static TexImage2D glTexImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexParameterf(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, Single param);
internal static TexParameterf glTexParameterf;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexParameterx(OpenTK.Graphics.ES10.All target, OpenTK.Graphics.ES10.All pname, int param);
internal static TexParameterx glTexParameterx;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void TexSubImage2D(OpenTK.Graphics.ES10.All target, Int32 level, Int32 xoffset, Int32 yoffset, Int32 width, Int32 height, OpenTK.Graphics.ES10.All format, OpenTK.Graphics.ES10.All type, IntPtr pixels);
internal static TexSubImage2D glTexSubImage2D;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Translatef(Single x, Single y, Single z);
internal static Translatef glTranslatef;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Translatex(int x, int y, int z);
internal static Translatex glTranslatex;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void VertexPointer(Int32 size, OpenTK.Graphics.ES10.All type, Int32 stride, IntPtr pointer);
internal static VertexPointer glVertexPointer;
[System.Security.SuppressUnmanagedCodeSecurity()]
internal delegate void Viewport(Int32 x, Int32 y, Int32 width, Int32 height);
internal static Viewport glViewport;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// General Ledger
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class GL : EduHubEntity
{
#region Navigation Property Cache
private KGLT Cache_GL_TYPE_KGLT;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<AKC> Cache_CODE_AKC_GLCODE_ASS;
private IReadOnlyList<AKC> Cache_CODE_AKC_GLCODE_PRV;
private IReadOnlyList<AKC> Cache_CODE_AKC_GLCODE_EXP;
private IReadOnlyList<AKC> Cache_CODE_AKC_GL_REVALS_BS;
private IReadOnlyList<AKC> Cache_CODE_AKC_GL_REVALS_PL;
private IReadOnlyList<AKC> Cache_CODE_AKC_GL_REVALS_ASS;
private IReadOnlyList<AKC> Cache_CODE_AKC_GL_DISP_PROF;
private IReadOnlyList<AKC> Cache_CODE_AKC_GL_DISP_PROC;
private IReadOnlyList<AKC> Cache_CODE_AKC_APTE_GLCODE;
private IReadOnlyList<AR> Cache_CODE_AR_PTE_GLCODE;
private IReadOnlyList<GLBUDG> Cache_CODE_GLBUDG_CODE;
private IReadOnlyList<GLCF> Cache_CODE_GLCF_CODE;
private IReadOnlyList<GLF> Cache_CODE_GLF_CODE;
private IReadOnlyList<KGST> Cache_CODE_KGST_GLGST_CODE;
private IReadOnlyList<KUPC> Cache_CODE_KUPC_GL_CODE;
private IReadOnlyList<PC> Cache_CODE_PC_GLCODE;
private IReadOnlyList<PD> Cache_CODE_PD_GLCODE;
private IReadOnlyList<PD> Cache_CODE_PD_GLBANK;
private IReadOnlyList<PD> Cache_CODE_PD_GLTAX;
private IReadOnlyList<PF> Cache_CODE_PF_GLCODE;
private IReadOnlyList<PGLI> Cache_CODE_PGLI_CODE;
private IReadOnlyList<PI> Cache_CODE_PI_CLR_GLCODE;
private IReadOnlyList<PN> Cache_CODE_PN_GLCODE;
private IReadOnlyList<PN> Cache_CODE_PN_GLBANK;
private IReadOnlyList<PN> Cache_CODE_PN_GLTAX;
private IReadOnlyList<RQGL> Cache_CODE_RQGL_GLCODE;
private IReadOnlyList<SA> Cache_CODE_SA_GLCODE;
private IReadOnlyList<SDFC> Cache_CODE_SDFC_GLCODE;
private IReadOnlyList<SGFC> Cache_CODE_SGFC_GLCODE;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// General Ledger code (Prime Key)
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string CODE { get; internal set; }
/// <summary>
/// Account title
/// [Alphanumeric (30)]
/// </summary>
public string TITLE { get; internal set; }
/// <summary>
/// Opening balance
/// </summary>
public decimal? OPBAL { get; internal set; }
/// <summary>
/// Last year opening balance
/// </summary>
public decimal? LYROPBAL { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR01 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR02 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR03 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR04 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR05 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR06 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR07 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR08 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR09 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR10 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR11 { get; internal set; }
/// <summary>
/// OLDNAME=LAST;* Last year monthly balances
/// </summary>
public decimal? LASTYR12 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR01 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR02 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR03 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR04 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR05 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR06 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR07 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR08 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR09 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR10 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR11 { get; internal set; }
/// <summary>
/// This year monthly balances
/// </summary>
public decimal? CURR12 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG01 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG02 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG03 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG04 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG05 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG06 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG07 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG08 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG09 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG10 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG11 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG12 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG01 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG02 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG03 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG04 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG05 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG06 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG07 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG08 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG09 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG10 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG11 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG12 { get; internal set; }
/// <summary>
/// Annual budget this year
/// </summary>
public decimal? ANNUALBUDG { get; internal set; }
/// <summary>
/// Annual budget next year
/// </summary>
public decimal? NEXT_ANN_BUDG { get; internal set; }
/// <summary>
/// Revised annual budget this year
/// </summary>
public decimal? REV_ANN_BUDG { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG01 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG02 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG03 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG04 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG05 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG06 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG07 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG08 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG09 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG10 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG11 { get; internal set; }
/// <summary>
/// Monthly revised budgets this year
/// </summary>
public decimal? REV_BUDG12 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG01 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG02 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG03 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG04 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG05 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG06 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG07 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG08 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG09 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG10 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG11 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG12 { get; internal set; }
/// <summary>
/// Annual budget last year
/// </summary>
public decimal? LAST_ANN_BUDG { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT01 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT02 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT03 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT04 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT05 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT06 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT07 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT08 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT09 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT10 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT11 { get; internal set; }
/// <summary>
/// Orders committed against this code
/// </summary>
public decimal? COMMITMENT12 { get; internal set; }
/// <summary>
/// Highest transaction date
/// </summary>
public DateTime? HIDATE { get; internal set; }
/// <summary>
/// Income/expense/Liabitiy etc
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string GL_TYPE { get; internal set; }
/// <summary>
/// Allow account to be used(Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string ACTIVE { get; internal set; }
/// <summary>
/// Allow editing of description by users
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string USER_DEFINABLE { get; internal set; }
/// <summary>
/// Potential FBT liability when this code is used Y/N
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string FBT { get; internal set; }
/// <summary>
/// Allow account to be processed (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string BATCHABLE { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// KGLT (General Ledger Account Types) related entity by [GL.GL_TYPE]->[KGLT.GL_TYPE]
/// Income/expense/Liabitiy etc
/// </summary>
public KGLT GL_TYPE_KGLT
{
get
{
if (GL_TYPE == null)
{
return null;
}
if (Cache_GL_TYPE_KGLT == null)
{
Cache_GL_TYPE_KGLT = Context.KGLT.FindByGL_TYPE(GL_TYPE);
}
return Cache_GL_TYPE_KGLT;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GLCODE_ASS]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GLCODE_ASS
{
get
{
if (Cache_CODE_AKC_GLCODE_ASS == null &&
!Context.AKC.TryFindByGLCODE_ASS(CODE, out Cache_CODE_AKC_GLCODE_ASS))
{
Cache_CODE_AKC_GLCODE_ASS = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GLCODE_ASS;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GLCODE_PRV]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GLCODE_PRV
{
get
{
if (Cache_CODE_AKC_GLCODE_PRV == null &&
!Context.AKC.TryFindByGLCODE_PRV(CODE, out Cache_CODE_AKC_GLCODE_PRV))
{
Cache_CODE_AKC_GLCODE_PRV = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GLCODE_PRV;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GLCODE_EXP]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GLCODE_EXP
{
get
{
if (Cache_CODE_AKC_GLCODE_EXP == null &&
!Context.AKC.TryFindByGLCODE_EXP(CODE, out Cache_CODE_AKC_GLCODE_EXP))
{
Cache_CODE_AKC_GLCODE_EXP = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GLCODE_EXP;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GL_REVALS_BS]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GL_REVALS_BS
{
get
{
if (Cache_CODE_AKC_GL_REVALS_BS == null &&
!Context.AKC.TryFindByGL_REVALS_BS(CODE, out Cache_CODE_AKC_GL_REVALS_BS))
{
Cache_CODE_AKC_GL_REVALS_BS = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GL_REVALS_BS;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GL_REVALS_PL]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GL_REVALS_PL
{
get
{
if (Cache_CODE_AKC_GL_REVALS_PL == null &&
!Context.AKC.TryFindByGL_REVALS_PL(CODE, out Cache_CODE_AKC_GL_REVALS_PL))
{
Cache_CODE_AKC_GL_REVALS_PL = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GL_REVALS_PL;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GL_REVALS_ASS]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GL_REVALS_ASS
{
get
{
if (Cache_CODE_AKC_GL_REVALS_ASS == null &&
!Context.AKC.TryFindByGL_REVALS_ASS(CODE, out Cache_CODE_AKC_GL_REVALS_ASS))
{
Cache_CODE_AKC_GL_REVALS_ASS = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GL_REVALS_ASS;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GL_DISP_PROF]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GL_DISP_PROF
{
get
{
if (Cache_CODE_AKC_GL_DISP_PROF == null &&
!Context.AKC.TryFindByGL_DISP_PROF(CODE, out Cache_CODE_AKC_GL_DISP_PROF))
{
Cache_CODE_AKC_GL_DISP_PROF = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GL_DISP_PROF;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.GL_DISP_PROC]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_GL_DISP_PROC
{
get
{
if (Cache_CODE_AKC_GL_DISP_PROC == null &&
!Context.AKC.TryFindByGL_DISP_PROC(CODE, out Cache_CODE_AKC_GL_DISP_PROC))
{
Cache_CODE_AKC_GL_DISP_PROC = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_GL_DISP_PROC;
}
}
/// <summary>
/// AKC (Assets - Categories) related entities by [GL.CODE]->[AKC.APTE_GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AKC> CODE_AKC_APTE_GLCODE
{
get
{
if (Cache_CODE_AKC_APTE_GLCODE == null &&
!Context.AKC.TryFindByAPTE_GLCODE(CODE, out Cache_CODE_AKC_APTE_GLCODE))
{
Cache_CODE_AKC_APTE_GLCODE = new List<AKC>().AsReadOnly();
}
return Cache_CODE_AKC_APTE_GLCODE;
}
}
/// <summary>
/// AR (Assets) related entities by [GL.CODE]->[AR.PTE_GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<AR> CODE_AR_PTE_GLCODE
{
get
{
if (Cache_CODE_AR_PTE_GLCODE == null &&
!Context.AR.TryFindByPTE_GLCODE(CODE, out Cache_CODE_AR_PTE_GLCODE))
{
Cache_CODE_AR_PTE_GLCODE = new List<AR>().AsReadOnly();
}
return Cache_CODE_AR_PTE_GLCODE;
}
}
/// <summary>
/// GLBUDG (General Ledger Budgets) related entities by [GL.CODE]->[GLBUDG.CODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<GLBUDG> CODE_GLBUDG_CODE
{
get
{
if (Cache_CODE_GLBUDG_CODE == null &&
!Context.GLBUDG.TryFindByCODE(CODE, out Cache_CODE_GLBUDG_CODE))
{
Cache_CODE_GLBUDG_CODE = new List<GLBUDG>().AsReadOnly();
}
return Cache_CODE_GLBUDG_CODE;
}
}
/// <summary>
/// GLCF (GL Combined Financial Trans) related entities by [GL.CODE]->[GLCF.CODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<GLCF> CODE_GLCF_CODE
{
get
{
if (Cache_CODE_GLCF_CODE == null &&
!Context.GLCF.TryFindByCODE(CODE, out Cache_CODE_GLCF_CODE))
{
Cache_CODE_GLCF_CODE = new List<GLCF>().AsReadOnly();
}
return Cache_CODE_GLCF_CODE;
}
}
/// <summary>
/// GLF (General Ledger Transactions) related entities by [GL.CODE]->[GLF.CODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<GLF> CODE_GLF_CODE
{
get
{
if (Cache_CODE_GLF_CODE == null &&
!Context.GLF.TryFindByCODE(CODE, out Cache_CODE_GLF_CODE))
{
Cache_CODE_GLF_CODE = new List<GLF>().AsReadOnly();
}
return Cache_CODE_GLF_CODE;
}
}
/// <summary>
/// KGST (GST Percentages) related entities by [GL.CODE]->[KGST.GLGST_CODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<KGST> CODE_KGST_GLGST_CODE
{
get
{
if (Cache_CODE_KGST_GLGST_CODE == null &&
!Context.KGST.TryFindByGLGST_CODE(CODE, out Cache_CODE_KGST_GLGST_CODE))
{
Cache_CODE_KGST_GLGST_CODE = new List<KGST>().AsReadOnly();
}
return Cache_CODE_KGST_GLGST_CODE;
}
}
/// <summary>
/// KUPC (User Program Codes) related entities by [GL.CODE]->[KUPC.GL_CODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<KUPC> CODE_KUPC_GL_CODE
{
get
{
if (Cache_CODE_KUPC_GL_CODE == null &&
!Context.KUPC.TryFindByGL_CODE(CODE, out Cache_CODE_KUPC_GL_CODE))
{
Cache_CODE_KUPC_GL_CODE = new List<KUPC>().AsReadOnly();
}
return Cache_CODE_KUPC_GL_CODE;
}
}
/// <summary>
/// PC (Cost Centres) related entities by [GL.CODE]->[PC.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PC> CODE_PC_GLCODE
{
get
{
if (Cache_CODE_PC_GLCODE == null &&
!Context.PC.TryFindByGLCODE(CODE, out Cache_CODE_PC_GLCODE))
{
Cache_CODE_PC_GLCODE = new List<PC>().AsReadOnly();
}
return Cache_CODE_PC_GLCODE;
}
}
/// <summary>
/// PD (Departments) related entities by [GL.CODE]->[PD.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PD> CODE_PD_GLCODE
{
get
{
if (Cache_CODE_PD_GLCODE == null &&
!Context.PD.TryFindByGLCODE(CODE, out Cache_CODE_PD_GLCODE))
{
Cache_CODE_PD_GLCODE = new List<PD>().AsReadOnly();
}
return Cache_CODE_PD_GLCODE;
}
}
/// <summary>
/// PD (Departments) related entities by [GL.CODE]->[PD.GLBANK]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PD> CODE_PD_GLBANK
{
get
{
if (Cache_CODE_PD_GLBANK == null &&
!Context.PD.TryFindByGLBANK(CODE, out Cache_CODE_PD_GLBANK))
{
Cache_CODE_PD_GLBANK = new List<PD>().AsReadOnly();
}
return Cache_CODE_PD_GLBANK;
}
}
/// <summary>
/// PD (Departments) related entities by [GL.CODE]->[PD.GLTAX]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PD> CODE_PD_GLTAX
{
get
{
if (Cache_CODE_PD_GLTAX == null &&
!Context.PD.TryFindByGLTAX(CODE, out Cache_CODE_PD_GLTAX))
{
Cache_CODE_PD_GLTAX = new List<PD>().AsReadOnly();
}
return Cache_CODE_PD_GLTAX;
}
}
/// <summary>
/// PF (Superannuation Funds) related entities by [GL.CODE]->[PF.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PF> CODE_PF_GLCODE
{
get
{
if (Cache_CODE_PF_GLCODE == null &&
!Context.PF.TryFindByGLCODE(CODE, out Cache_CODE_PF_GLCODE))
{
Cache_CODE_PF_GLCODE = new List<PF>().AsReadOnly();
}
return Cache_CODE_PF_GLCODE;
}
}
/// <summary>
/// PGLI (General Ledger Import) related entities by [GL.CODE]->[PGLI.CODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PGLI> CODE_PGLI_CODE
{
get
{
if (Cache_CODE_PGLI_CODE == null &&
!Context.PGLI.TryFindByCODE(CODE, out Cache_CODE_PGLI_CODE))
{
Cache_CODE_PGLI_CODE = new List<PGLI>().AsReadOnly();
}
return Cache_CODE_PGLI_CODE;
}
}
/// <summary>
/// PI (Pay Items) related entities by [GL.CODE]->[PI.CLR_GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PI> CODE_PI_CLR_GLCODE
{
get
{
if (Cache_CODE_PI_CLR_GLCODE == null &&
!Context.PI.TryFindByCLR_GLCODE(CODE, out Cache_CODE_PI_CLR_GLCODE))
{
Cache_CODE_PI_CLR_GLCODE = new List<PI>().AsReadOnly();
}
return Cache_CODE_PI_CLR_GLCODE;
}
}
/// <summary>
/// PN (Payroll Groups) related entities by [GL.CODE]->[PN.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PN> CODE_PN_GLCODE
{
get
{
if (Cache_CODE_PN_GLCODE == null &&
!Context.PN.TryFindByGLCODE(CODE, out Cache_CODE_PN_GLCODE))
{
Cache_CODE_PN_GLCODE = new List<PN>().AsReadOnly();
}
return Cache_CODE_PN_GLCODE;
}
}
/// <summary>
/// PN (Payroll Groups) related entities by [GL.CODE]->[PN.GLBANK]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PN> CODE_PN_GLBANK
{
get
{
if (Cache_CODE_PN_GLBANK == null &&
!Context.PN.TryFindByGLBANK(CODE, out Cache_CODE_PN_GLBANK))
{
Cache_CODE_PN_GLBANK = new List<PN>().AsReadOnly();
}
return Cache_CODE_PN_GLBANK;
}
}
/// <summary>
/// PN (Payroll Groups) related entities by [GL.CODE]->[PN.GLTAX]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<PN> CODE_PN_GLTAX
{
get
{
if (Cache_CODE_PN_GLTAX == null &&
!Context.PN.TryFindByGLTAX(CODE, out Cache_CODE_PN_GLTAX))
{
Cache_CODE_PN_GLTAX = new List<PN>().AsReadOnly();
}
return Cache_CODE_PN_GLTAX;
}
}
/// <summary>
/// RQGL (Purchasing Group GL Codes) related entities by [GL.CODE]->[RQGL.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<RQGL> CODE_RQGL_GLCODE
{
get
{
if (Cache_CODE_RQGL_GLCODE == null &&
!Context.RQGL.TryFindByGLCODE(CODE, out Cache_CODE_RQGL_GLCODE))
{
Cache_CODE_RQGL_GLCODE = new List<RQGL>().AsReadOnly();
}
return Cache_CODE_RQGL_GLCODE;
}
}
/// <summary>
/// SA (Fees) related entities by [GL.CODE]->[SA.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<SA> CODE_SA_GLCODE
{
get
{
if (Cache_CODE_SA_GLCODE == null &&
!Context.SA.TryFindByGLCODE(CODE, out Cache_CODE_SA_GLCODE))
{
Cache_CODE_SA_GLCODE = new List<SA>().AsReadOnly();
}
return Cache_CODE_SA_GLCODE;
}
}
/// <summary>
/// SDFC (Sundry Debtor Fees) related entities by [GL.CODE]->[SDFC.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<SDFC> CODE_SDFC_GLCODE
{
get
{
if (Cache_CODE_SDFC_GLCODE == null &&
!Context.SDFC.TryFindByGLCODE(CODE, out Cache_CODE_SDFC_GLCODE))
{
Cache_CODE_SDFC_GLCODE = new List<SDFC>().AsReadOnly();
}
return Cache_CODE_SDFC_GLCODE;
}
}
/// <summary>
/// SGFC (General Ledger Fees) related entities by [GL.CODE]->[SGFC.GLCODE]
/// General Ledger code (Prime Key)
/// </summary>
public IReadOnlyList<SGFC> CODE_SGFC_GLCODE
{
get
{
if (Cache_CODE_SGFC_GLCODE == null &&
!Context.SGFC.TryFindByGLCODE(CODE, out Cache_CODE_SGFC_GLCODE))
{
Cache_CODE_SGFC_GLCODE = new List<SGFC>().AsReadOnly();
}
return Cache_CODE_SGFC_GLCODE;
}
}
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedTestSuite
{
using System.Collections.Generic;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.SharedAdapter;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// A class which contains test cases used to capture the requirements related with QueryAccess operation.
/// </summary>
[TestClass]
public abstract class S11_QueryAccess : SharedTestSuiteBase
{
#region Test Suite Initialization and clean up
/// <summary>
/// A method used to initialize this class.
/// </summary>
/// <param name="testContext">A parameter represents the context of the test suite.</param>
[ClassInitialize]
public static new void ClassInitialize(TestContext testContext)
{
SharedTestSuiteBase.ClassInitialize(testContext);
}
/// <summary>
/// A method used to clean up the test environment.
/// </summary>
[ClassCleanup]
public static new void ClassCleanup()
{
SharedTestSuiteBase.ClassCleanup();
}
#endregion
#region Test Case Initialization
/// <summary>
/// A method used to initialize the test class.
/// </summary>
[TestInitialize]
public void S11_QueryAccessInitialization()
{
// Initialize the default file URL, for this scenario, the target file URL should not need unique for each test case, just using the preparing one.
this.DefaultFileUrl = Common.GetConfigurationPropertyValue("NormalFile", this.Site);
}
#endregion
#region Test Case
/// <summary>
/// A method used to verify QueryAccess when the user has read/write permission.
/// </summary>
[TestCategory("SHAREDTESTCASE"), TestMethod()]
public void TestCase_S11_TC01_QueryAccessReadWrite()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Query changes from the protocol server
CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID());
CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange });
CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site);
this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site), "The operation QueryChanges should succeed.");
FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site);
ExGuid storageIndex = fsshttpbResponse.CellSubResponses[0].GetSubResponseData<QueryChangesSubResponseData>().StorageIndexExtendedGUID;
// Create a putChanges cellSubRequest
FsshttpbCellRequest cellRequest = SharedTestSuiteHelper.CreateFsshttpbCellRequest();
ExGuid storageIndexExGuid;
List<DataElement> dataElements = DataElementUtils.BuildDataElements(System.Text.Encoding.Unicode.GetBytes("bad"), out storageIndexExGuid);
PutChangesCellSubRequest putChange = new PutChangesCellSubRequest(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), storageIndexExGuid);
putChange.ExpectedStorageIndexExtendedGUID = storageIndex;
dataElements.AddRange(fsshttpbResponse.DataElementPackage.DataElements);
cellRequest.AddSubRequest(putChange, dataElements);
CellSubRequestType putChangesSubRequest = SharedTestSuiteHelper.CreateCellSubRequest(SequenceNumberGenerator.GetCurrentToken(), cellRequest.ToBase64());
// Put changes to the protocol server
CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { putChangesSubRequest });
CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site);
// Expect the Put changes operation succeeds
this.Site.Assert.AreEqual(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "The PutChanges operation should succeed.");
SharedTestSuiteHelper.ExpectMsfsshttpbSubResponseSucceed(SharedTestSuiteHelper.ExtractFsshttpbResponse(cellSubResponse, this.Site), this.Site);
// Call QueryAccess.
CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryAccess(0);
CellStorageResponse cellStorageResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest });
CellSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(cellStorageResponse, 0, 0, this.Site);
FsshttpbResponse queryAccessResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(subResponse, this.Site);
// Get readAccessResponse and writeAccessResponse Data.
HRESULTError dataRead = queryAccessResponse.CellSubResponses[0]
.GetSubResponseData<QueryAccessSubResponseData>()
.ReadAccessResponse.ReadResponseError
.GetErrorData<HRESULTError>();
this.Site.Assert.AreEqual<int>(
0,
dataRead.ErrorCode,
"Test case cannot continue unless the read HRESULTError code equals 0 when the user have read/write permission.");
HRESULTError dataWrite = queryAccessResponse.CellSubResponses[0]
.GetSubResponseData<QueryAccessSubResponseData>()
.WriteAccessResponse.WriteResponseError
.GetErrorData<HRESULTError>();
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error type is HRESULTError, then capture R946.
Site.CaptureRequirementIfIsNotNull(
dataWrite,
"MS-FSSHTTPB",
946,
@"[In Query Access] Response Error (variable): If the Put Changes operation will succeed, the response error will have an error type of HRESULT error.");
// If the error type is HRESULTError and error code equals 0, then capture R2229.
Site.CaptureRequirementIfAreEqual<int>(
0,
dataWrite.ErrorCode,
"MS-FSSHTTPB",
2229,
@"[In Query Access] Response Error (variable): [If the Put Changes operation will succeed, ]the HRESULT error code will be zero.");
// If error code equals 0, then capture R2231.
Site.CaptureRequirementIfAreEqual<int>(
0,
dataWrite.ErrorCode,
"MS-FSSHTTPB",
2231,
@"[In HRESULT Error] Error Code (4 bytes): Zero means that no error occurred.");
}
else
{
Site.Assert.IsNotNull(
dataWrite,
@"[In Query Access] Response Error (variable): If the Put Changes operation will succeed, the response error will have an error type of HRESULT error.");
Site.Assert.AreEqual<int>(
0,
dataWrite.ErrorCode,
@"[In Query Access] Response Error (variable): [If the Put Changes operation will succeed, ]the HRESULT error code will be zero.");
}
}
/// <summary>
/// A method used to verify QueryAccess when the user has read permission.
/// </summary>
[TestCategory("SHAREDTESTCASE"), TestMethod()]
public void TestCase_S11_TC02_QueryAccessRead()
{
string readOnlyUser = Common.GetConfigurationPropertyValue("ReadOnlyUser", this.Site);
string readOnlyUserPassword = Common.GetConfigurationPropertyValue("ReadOnlyUserPwd", this.Site);
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, readOnlyUser, readOnlyUserPassword, this.Domain);
// Query changes from the protocol server
CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID());
CellStorageResponse queryResponse = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { queryChange });
CellSubResponseType querySubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(queryResponse, 0, 0, this.Site);
FsshttpbResponse fsshttpbResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(querySubResponse, this.Site);
this.Site.Assert.AreEqual(
ErrorCodeType.Success,
SharedTestSuiteHelper.ConvertToErrorCodeType(querySubResponse.ErrorCode, this.Site),
"The operation QueryChanges should succeed when the user {0} only has ViewOnly permission.",
readOnlyUser);
this.Site.Assert.IsFalse(
fsshttpbResponse.CellSubResponses[0].Status,
"The operation QueryChanges should succeed when the user {0} only has ViewOnly permission.",
readOnlyUser);
// Call QueryAccess
CellSubRequestType cellSubRequest = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryAccess(0);
CellStorageResponse cellStorageResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { cellSubRequest });
CellSubResponseType subResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(cellStorageResponse, 0, 0, this.Site);
FsshttpbResponse queryAccessResponse = SharedTestSuiteHelper.ExtractFsshttpbResponse(subResponse, this.Site);
// Get readAccessResponse and writeAccessResponse Data.
HRESULTError dataRead = queryAccessResponse.CellSubResponses[0]
.GetSubResponseData<QueryAccessSubResponseData>()
.ReadAccessResponse.ReadResponseError
.GetErrorData<HRESULTError>();
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// If the error type is HRESULTError, then capture R944.
Site.CaptureRequirementIfIsNotNull(
dataRead,
"MS-FSSHTTPB",
944,
@"[In Query Access] Response Error (variable): If read operations will succeed, the Response Error will have an error type of HRESULT error.");
// If HResult is 0,MS-FSSHTTPB_R2228 should be covered.
Site.CaptureRequirementIfAreEqual<int>(
0,
dataRead.ErrorCode,
"MS-FSSHTTPB",
2228,
@"[In Query Access] Response Error (variable): [If read operations will succeed, ]the HRESULT error code will be zero.");
}
else
{
Site.Assert.IsNotNull(
dataRead,
@"[In Query Access] Response Error (variable): If read operations will succeed, the response error will have an error type of HRESULT error.");
Site.Assert.AreEqual<int>(
0,
dataRead.ErrorCode,
@"[In Query Access] Response Error (variable): [If read operations will succeed, ]the HRESULT error code will be zero.");
}
HRESULTError dataWrite = queryAccessResponse.CellSubResponses[0]
.GetSubResponseData<QueryAccessSubResponseData>()
.WriteAccessResponse.WriteResponseError
.GetErrorData<HRESULTError>();
this.Site.Assert.AreNotEqual<int>(
0,
dataWrite.ErrorCode,
"Test case cannot continue unless the write HRESULTError code not equals 0 when the user have read permission.");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.InteropServices
{
public static class __UCOMITypeInfo
{
public static IObservable<System.IntPtr> GetTypeAttr(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue)
{
return Observable.Select(UCOMITypeInfoValue, (UCOMITypeInfoValueLambda) =>
{
System.IntPtr ppTypeAttrOutput = default(System.IntPtr);
UCOMITypeInfoValueLambda.GetTypeAttr(out ppTypeAttrOutput);
return ppTypeAttrOutput;
});
}
public static IObservable<System.Runtime.InteropServices.UCOMITypeComp> GetTypeComp(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue)
{
return Observable.Select(UCOMITypeInfoValue, (UCOMITypeInfoValueLambda) =>
{
System.Runtime.InteropServices.UCOMITypeComp ppTCompOutput =
default(System.Runtime.InteropServices.UCOMITypeComp);
UCOMITypeInfoValueLambda.GetTypeComp(out ppTCompOutput);
return ppTCompOutput;
});
}
public static IObservable<System.IntPtr> GetFuncDesc(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> index)
{
return Observable.Zip(UCOMITypeInfoValue, index, (UCOMITypeInfoValueLambda, indexLambda) =>
{
System.IntPtr ppFuncDescOutput = default(System.IntPtr);
UCOMITypeInfoValueLambda.GetFuncDesc(indexLambda, out ppFuncDescOutput);
return ppFuncDescOutput;
});
}
public static IObservable<System.IntPtr> GetVarDesc(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> index)
{
return Observable.Zip(UCOMITypeInfoValue, index, (UCOMITypeInfoValueLambda, indexLambda) =>
{
System.IntPtr ppVarDescOutput = default(System.IntPtr);
UCOMITypeInfoValueLambda.GetVarDesc(indexLambda, out ppVarDescOutput);
return ppVarDescOutput;
});
}
public static IObservable<int> GetNames(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> memid, IObservable<System.String[]> rgBstrNames,
IObservable<System.Int32> cMaxNames)
{
return Observable.Zip(UCOMITypeInfoValue, memid, rgBstrNames, cMaxNames,
(UCOMITypeInfoValueLambda, memidLambda, rgBstrNamesLambda, cMaxNamesLambda) =>
{
System.Int32 pcNamesOutput = default(System.Int32);
UCOMITypeInfoValueLambda.GetNames(memidLambda, rgBstrNamesLambda, cMaxNamesLambda, out pcNamesOutput);
return pcNamesOutput;
});
}
public static IObservable<System.Int32> GetRefTypeOfImplType(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> index)
{
return Observable.Zip(UCOMITypeInfoValue, index, (UCOMITypeInfoValueLambda, indexLambda) =>
{
System.Int32 hrefOutput = default(System.Int32);
UCOMITypeInfoValueLambda.GetRefTypeOfImplType(indexLambda, out hrefOutput);
return hrefOutput;
});
}
public static IObservable<System.Int32> GetImplTypeFlags(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> index)
{
return Observable.Zip(UCOMITypeInfoValue, index, (UCOMITypeInfoValueLambda, indexLambda) =>
{
System.Int32 pImplTypeFlagsOutput = default(System.Int32);
UCOMITypeInfoValueLambda.GetImplTypeFlags(indexLambda, out pImplTypeFlagsOutput);
return pImplTypeFlagsOutput;
});
}
public static IObservable<Unit> GetIDsOfNames(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.String[]> rgszNames, IObservable<System.Int32> cNames, IObservable<System.Int32[]> pMemId)
{
return ObservableExt.ZipExecute(UCOMITypeInfoValue, rgszNames, cNames, pMemId,
(UCOMITypeInfoValueLambda, rgszNamesLambda, cNamesLambda, pMemIdLambda) =>
UCOMITypeInfoValueLambda.GetIDsOfNames(rgszNamesLambda, cNamesLambda, pMemIdLambda));
}
public static
IObservable
<
Tuple
<System.Runtime.InteropServices.DISPPARAMS, System.Object,
System.Runtime.InteropServices.EXCEPINFO, System.Int32>> Invoke(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Object> pvInstance, IObservable<System.Int32> memid, IObservable<System.Int16> wFlags,
IObservable<System.Runtime.InteropServices.DISPPARAMS> pDispParams)
{
return Observable.Zip(UCOMITypeInfoValue, pvInstance, memid, wFlags, pDispParams,
(UCOMITypeInfoValueLambda, pvInstanceLambda, memidLambda, wFlagsLambda, pDispParamsLambda) =>
{
System.Object pVarResultOutput = default(System.Object);
System.Runtime.InteropServices.EXCEPINFO pExcepInfoOutput =
default(System.Runtime.InteropServices.EXCEPINFO);
System.Int32 puArgErrOutput = default(System.Int32);
UCOMITypeInfoValueLambda.Invoke(pvInstanceLambda, memidLambda, wFlagsLambda, ref pDispParamsLambda,
out pVarResultOutput, out pExcepInfoOutput, out puArgErrOutput);
return Tuple.Create(pDispParamsLambda, pVarResultOutput, pExcepInfoOutput, puArgErrOutput);
});
}
public static IObservable<Tuple<System.String, System.String, System.Int32, System.String>> GetDocumentation(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> index)
{
return Observable.Zip(UCOMITypeInfoValue, index, (UCOMITypeInfoValueLambda, indexLambda) =>
{
System.String strNameOutput = default(System.String);
System.String strDocStringOutput = default(System.String);
System.Int32 dwHelpContextOutput = default(System.Int32);
System.String strHelpFileOutput = default(System.String);
UCOMITypeInfoValueLambda.GetDocumentation(indexLambda, out strNameOutput, out strDocStringOutput,
out dwHelpContextOutput, out strHelpFileOutput);
return Tuple.Create(strNameOutput, strDocStringOutput, dwHelpContextOutput, strHelpFileOutput);
});
}
public static IObservable<Tuple<System.String, System.String, System.Int16>> GetDllEntry(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> memid, IObservable<System.Runtime.InteropServices.INVOKEKIND> invKind)
{
return Observable.Zip(UCOMITypeInfoValue, memid, invKind,
(UCOMITypeInfoValueLambda, memidLambda, invKindLambda) =>
{
System.String pBstrDllNameOutput = default(System.String);
System.String pBstrNameOutput = default(System.String);
System.Int16 pwOrdinalOutput = default(System.Int16);
UCOMITypeInfoValueLambda.GetDllEntry(memidLambda, invKindLambda, out pBstrDllNameOutput,
out pBstrNameOutput, out pwOrdinalOutput);
return Tuple.Create(pBstrDllNameOutput, pBstrNameOutput, pwOrdinalOutput);
});
}
public static IObservable<System.Runtime.InteropServices.UCOMITypeInfo> GetRefTypeInfo(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> hRef)
{
return Observable.Zip(UCOMITypeInfoValue, hRef, (UCOMITypeInfoValueLambda, hRefLambda) =>
{
System.Runtime.InteropServices.UCOMITypeInfo ppTIOutput =
default(System.Runtime.InteropServices.UCOMITypeInfo);
UCOMITypeInfoValueLambda.GetRefTypeInfo(hRefLambda, out ppTIOutput);
return ppTIOutput;
});
}
public static IObservable<System.IntPtr> AddressOfMember(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> memid, IObservable<System.Runtime.InteropServices.INVOKEKIND> invKind)
{
return Observable.Zip(UCOMITypeInfoValue, memid, invKind,
(UCOMITypeInfoValueLambda, memidLambda, invKindLambda) =>
{
System.IntPtr ppvOutput = default(System.IntPtr);
UCOMITypeInfoValueLambda.AddressOfMember(memidLambda, invKindLambda, out ppvOutput);
return ppvOutput;
});
}
public static IObservable<Tuple<System.Guid, System.Object>> CreateInstance(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Object> pUnkOuter, IObservable<System.Guid> riid)
{
return Observable.Zip(UCOMITypeInfoValue, pUnkOuter, riid,
(UCOMITypeInfoValueLambda, pUnkOuterLambda, riidLambda) =>
{
System.Object ppvObjOutput = default(System.Object);
UCOMITypeInfoValueLambda.CreateInstance(pUnkOuterLambda, ref riidLambda, out ppvObjOutput);
return Tuple.Create(riidLambda, ppvObjOutput);
});
}
public static IObservable<System.String> GetMops(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.Int32> memid)
{
return Observable.Zip(UCOMITypeInfoValue, memid, (UCOMITypeInfoValueLambda, memidLambda) =>
{
System.String pBstrMopsOutput = default(System.String);
UCOMITypeInfoValueLambda.GetMops(memidLambda, out pBstrMopsOutput);
return pBstrMopsOutput;
});
}
public static IObservable<Tuple<System.Runtime.InteropServices.UCOMITypeLib, System.Int32>> GetContainingTypeLib
(this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue)
{
return Observable.Select(UCOMITypeInfoValue, (UCOMITypeInfoValueLambda) =>
{
System.Runtime.InteropServices.UCOMITypeLib ppTLBOutput =
default(System.Runtime.InteropServices.UCOMITypeLib);
System.Int32 pIndexOutput = default(System.Int32);
UCOMITypeInfoValueLambda.GetContainingTypeLib(out ppTLBOutput, out pIndexOutput);
return Tuple.Create(ppTLBOutput, pIndexOutput);
});
}
public static IObservable<System.Reactive.Unit> ReleaseTypeAttr(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.IntPtr> pTypeAttr)
{
return ObservableExt.ZipExecute(UCOMITypeInfoValue, pTypeAttr,
(UCOMITypeInfoValueLambda, pTypeAttrLambda) => UCOMITypeInfoValueLambda.ReleaseTypeAttr(pTypeAttrLambda));
}
public static IObservable<System.Reactive.Unit> ReleaseFuncDesc(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.IntPtr> pFuncDesc)
{
return ObservableExt.ZipExecute(UCOMITypeInfoValue, pFuncDesc,
(UCOMITypeInfoValueLambda, pFuncDescLambda) => UCOMITypeInfoValueLambda.ReleaseFuncDesc(pFuncDescLambda));
}
public static IObservable<System.Reactive.Unit> ReleaseVarDesc(
this IObservable<System.Runtime.InteropServices.UCOMITypeInfo> UCOMITypeInfoValue,
IObservable<System.IntPtr> pVarDesc)
{
return ObservableExt.ZipExecute(UCOMITypeInfoValue, pVarDesc,
(UCOMITypeInfoValueLambda, pVarDescLambda) => UCOMITypeInfoValueLambda.ReleaseVarDesc(pVarDescLambda));
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
using ZXing.Common.ReedSolomon;
namespace ZXing.QrCode.Internal
{
/// <summary>
/// </summary>
/// <author>satorux@google.com (Satoru Takabayashi) - creator</author>
/// <author>dswitkin@google.com (Daniel Switkin) - ported from C++</author>
public static class Encoder
{
// The original table is defined in the table 5 of JISX0510:2004 (p.19).
private static readonly int[] ALPHANUMERIC_TABLE = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f
};
internal static String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
// The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
// Basically it applies four rules and summate all penalties.
private static int calculateMaskPenalty(ByteMatrix matrix)
{
return MaskUtil.applyMaskPenaltyRule1(matrix)
+ MaskUtil.applyMaskPenaltyRule2(matrix)
+ MaskUtil.applyMaskPenaltyRule3(matrix)
+ MaskUtil.applyMaskPenaltyRule4(matrix);
}
/// <summary>
/// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen
/// internally by chooseMode(). On success, store the result in "qrCode".
/// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for
/// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very
/// strong error correction for this purpose.
/// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode()
/// with which clients can specify the encoding mode. For now, we don't need the functionality.
/// </summary>
/// <param name="content">text to encode</param>
/// <param name="ecLevel">error correction level to use</param>
/// <returns><see cref="QRCode"/> representing the encoded QR code</returns>
public static QRCode encode(String content, ErrorCorrectionLevel ecLevel)
{
return encode(content, ecLevel, null);
}
/// <summary>
/// Encodes the specified content.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="ecLevel">The ec level.</param>
/// <param name="hints">The hints.</param>
/// <returns></returns>
public static QRCode encode(String content,
ErrorCorrectionLevel ecLevel,
IDictionary<EncodeHintType, object> hints)
{
// Determine what character encoding has been specified by the caller, if any
#if !SILVERLIGHT || WINDOWS_PHONE
String encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET];
if (encoding == null)
{
encoding = DEFAULT_BYTE_MODE_ENCODING;
}
bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding);
#else
// Silverlight supports only UTF-8 and UTF-16 out-of-the-box
const string encoding = "UTF-8";
// caller of the method can only control if the ECI segment should be written
// character set is fixed to UTF-8; but some scanners doesn't like the ECI segment
bool generateECI = (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET));
#endif
// Pick an encoding mode appropriate for the content. Note that this will not attempt to use
// multiple modes / segments even if that were more efficient. Twould be nice.
Mode mode = chooseMode(content, encoding);
// This will store the header information, like mode and
// length, as well as "header" segments like an ECI segment.
BitArray headerBits = new BitArray();
// Append ECI segment if applicable
if (mode == Mode.BYTE && generateECI)
{
CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding);
if (eci != null)
{
var eciIsExplicitDisabled = (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) && hints[EncodeHintType.DISABLE_ECI] != null && Convert.ToBoolean(hints[EncodeHintType.DISABLE_ECI].ToString()));
if (!eciIsExplicitDisabled)
{
appendECI(eci, headerBits);
}
}
}
// (With ECI in place,) Write the mode marker
appendModeInfo(mode, headerBits);
// Collect data within the main segment, separately, to count its size if needed. Don't add it to
// main payload yet.
BitArray dataBits = new BitArray();
appendBytes(content, mode, dataBits, encoding);
// Hard part: need to know version to know how many bits length takes. But need to know how many
// bits it takes to know version. First we take a guess at version by assuming version will be
// the minimum, 1:
int provisionalBitsNeeded = headerBits.Size
+ mode.getCharacterCountBits(Version.getVersionForNumber(1))
+ dataBits.Size;
Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel);
// Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
int bitsNeeded = headerBits.Size
+ mode.getCharacterCountBits(provisionalVersion)
+ dataBits.Size;
Version version = chooseVersion(bitsNeeded, ecLevel);
BitArray headerAndDataBits = new BitArray();
headerAndDataBits.appendBitArray(headerBits);
// Find "length" of main segment and write it
int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length;
appendLengthInfo(numLetters, version, mode, headerAndDataBits);
// Put data together into the overall payload
headerAndDataBits.appendBitArray(dataBits);
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords;
// Terminate the bits properly.
terminateBits(numDataBytes, headerAndDataBits);
// Interleave data bits with error correction code.
BitArray finalBits = interleaveWithECBytes(headerAndDataBits,
version.TotalCodewords,
numDataBytes,
ecBlocks.NumBlocks);
QRCode qrCode = new QRCode
{
ECLevel = ecLevel,
Mode = mode,
Version = version
};
// Choose the mask pattern and set to "qrCode".
int dimension = version.DimensionForVersion;
ByteMatrix matrix = new ByteMatrix(dimension, dimension);
int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix);
qrCode.MaskPattern = maskPattern;
// Build the matrix and set it to "qrCode".
MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
qrCode.Matrix = matrix;
return qrCode;
}
/// <summary>
/// Gets the alphanumeric code.
/// </summary>
/// <param name="code">The code.</param>
/// <returns>the code point of the table used in alphanumeric mode or
/// -1 if there is no corresponding code in the table.</returns>
internal static int getAlphanumericCode(int code)
{
if (code < ALPHANUMERIC_TABLE.Length)
{
return ALPHANUMERIC_TABLE[code];
}
return -1;
}
/// <summary>
/// Chooses the mode.
/// </summary>
/// <param name="content">The content.</param>
/// <returns></returns>
public static Mode chooseMode(String content)
{
return chooseMode(content, null);
}
/// <summary>
/// Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
/// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="encoding">The encoding.</param>
/// <returns></returns>
private static Mode chooseMode(String content, String encoding)
{
if ("Shift_JIS".Equals(encoding) && isOnlyDoubleByteKanji(content))
{
// Choose Kanji mode if all input are double-byte characters
return Mode.KANJI;
}
bool hasNumeric = false;
bool hasAlphanumeric = false;
for (int i = 0; i < content.Length; ++i)
{
char c = content[i];
if (c >= '0' && c <= '9')
{
hasNumeric = true;
}
else if (getAlphanumericCode(c) != -1)
{
hasAlphanumeric = true;
}
else
{
return Mode.BYTE;
}
}
if (hasAlphanumeric)
{
return Mode.ALPHANUMERIC;
}
if (hasNumeric)
{
return Mode.NUMERIC;
}
return Mode.BYTE;
}
private static bool isOnlyDoubleByteKanji(String content)
{
byte[] bytes;
try
{
bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content);
}
catch (Exception )
{
return false;
}
int length = bytes.Length;
if (length % 2 != 0)
{
return false;
}
for (int i = 0; i < length; i += 2)
{
int byte1 = bytes[i] & 0xFF;
if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB))
{
return false;
}
}
return true;
}
private static int chooseMaskPattern(BitArray bits,
ErrorCorrectionLevel ecLevel,
Version version,
ByteMatrix matrix)
{
int minPenalty = Int32.MaxValue; // Lower penalty is better.
int bestMaskPattern = -1;
// We try all mask patterns to choose the best one.
for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++)
{
MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
int penalty = calculateMaskPenalty(matrix);
if (penalty < minPenalty)
{
minPenalty = penalty;
bestMaskPattern = maskPattern;
}
}
return bestMaskPattern;
}
private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel)
{
// In the following comments, we use numbers of Version 7-H.
for (int versionNum = 1; versionNum <= 40; versionNum++)
{
Version version = Version.getVersionForNumber(versionNum);
// numBytes = 196
int numBytes = version.TotalCodewords;
// getNumECBytes = 130
Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel);
int numEcBytes = ecBlocks.TotalECCodewords;
// getNumDataBytes = 196 - 130 = 66
int numDataBytes = numBytes - numEcBytes;
int totalInputBytes = (numInputBits + 7) / 8;
if (numDataBytes >= totalInputBytes)
{
return version;
}
}
throw new WriterException("Data too big");
}
/// <summary>
/// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
/// </summary>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="bits">The bits.</param>
internal static void terminateBits(int numDataBytes, BitArray bits)
{
int capacity = numDataBytes << 3;
if (bits.Size > capacity)
{
throw new WriterException("data bits cannot fit in the QR Code" + bits.Size + " > " +
capacity);
}
for (int i = 0; i < 4 && bits.Size < capacity; ++i)
{
bits.appendBit(false);
}
// Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
// If the last byte isn't 8-bit aligned, we'll add padding bits.
int numBitsInLastByte = bits.Size & 0x07;
if (numBitsInLastByte > 0)
{
for (int i = numBitsInLastByte; i < 8; i++)
{
bits.appendBit(false);
}
}
// If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
int numPaddingBytes = numDataBytes - bits.SizeInBytes;
for (int i = 0; i < numPaddingBytes; ++i)
{
bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8);
}
if (bits.Size != capacity)
{
throw new WriterException("Bits size does not equal capacity");
}
}
/// <summary>
/// Get number of data bytes and number of error correction bytes for block id "blockID". Store
/// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
/// JISX0510:2004 (p.30)
/// </summary>
/// <param name="numTotalBytes">The num total bytes.</param>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="numRSBlocks">The num RS blocks.</param>
/// <param name="blockID">The block ID.</param>
/// <param name="numDataBytesInBlock">The num data bytes in block.</param>
/// <param name="numECBytesInBlock">The num EC bytes in block.</param>
internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes,
int numDataBytes,
int numRSBlocks,
int blockID,
int[] numDataBytesInBlock,
int[] numECBytesInBlock)
{
if (blockID >= numRSBlocks)
{
throw new WriterException("Block ID too large");
}
// numRsBlocksInGroup2 = 196 % 5 = 1
int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
// numRsBlocksInGroup1 = 5 - 1 = 4
int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
// numTotalBytesInGroup1 = 196 / 5 = 39
int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
// numTotalBytesInGroup2 = 39 + 1 = 40
int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
// numDataBytesInGroup1 = 66 / 5 = 13
int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
// numDataBytesInGroup2 = 13 + 1 = 14
int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
// numEcBytesInGroup1 = 39 - 13 = 26
int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
// numEcBytesInGroup2 = 40 - 14 = 26
int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
// Sanity checks.
// 26 = 26
if (numEcBytesInGroup1 != numEcBytesInGroup2)
{
throw new WriterException("EC bytes mismatch");
}
// 5 = 4 + 1.
if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2)
{
throw new WriterException("RS blocks mismatch");
}
// 196 = (13 + 26) * 4 + (14 + 26) * 1
if (numTotalBytes !=
((numDataBytesInGroup1 + numEcBytesInGroup1) *
numRsBlocksInGroup1) +
((numDataBytesInGroup2 + numEcBytesInGroup2) *
numRsBlocksInGroup2))
{
throw new WriterException("Total bytes mismatch");
}
if (blockID < numRsBlocksInGroup1)
{
numDataBytesInBlock[0] = numDataBytesInGroup1;
numECBytesInBlock[0] = numEcBytesInGroup1;
}
else
{
numDataBytesInBlock[0] = numDataBytesInGroup2;
numECBytesInBlock[0] = numEcBytesInGroup2;
}
}
/// <summary>
/// Interleave "bits" with corresponding error correction bytes. On success, store the result in
/// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="numTotalBytes">The num total bytes.</param>
/// <param name="numDataBytes">The num data bytes.</param>
/// <param name="numRSBlocks">The num RS blocks.</param>
/// <returns></returns>
internal static BitArray interleaveWithECBytes(BitArray bits,
int numTotalBytes,
int numDataBytes,
int numRSBlocks)
{
// "bits" must have "getNumDataBytes" bytes of data.
if (bits.SizeInBytes != numDataBytes)
{
throw new WriterException("Number of bits and data bytes does not match");
}
// Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
// store the divided data bytes blocks and error correction bytes blocks into "blocks".
int dataBytesOffset = 0;
int maxNumDataBytes = 0;
int maxNumEcBytes = 0;
// Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
var blocks = new List<BlockPair>(numRSBlocks);
for (int i = 0; i < numRSBlocks; ++i)
{
int[] numDataBytesInBlock = new int[1];
int[] numEcBytesInBlock = new int[1];
getNumDataBytesAndNumECBytesForBlockID(
numTotalBytes, numDataBytes, numRSBlocks, i,
numDataBytesInBlock, numEcBytesInBlock);
int size = numDataBytesInBlock[0];
byte[] dataBytes = new byte[size];
bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size);
byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
blocks.Add(new BlockPair(dataBytes, ecBytes));
maxNumDataBytes = Math.Max(maxNumDataBytes, size);
maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.Length);
dataBytesOffset += numDataBytesInBlock[0];
}
if (numDataBytes != dataBytesOffset)
{
throw new WriterException("Data bytes does not match offset");
}
BitArray result = new BitArray();
// First, place data blocks.
for (int i = 0; i < maxNumDataBytes; ++i)
{
foreach (BlockPair block in blocks)
{
byte[] dataBytes = block.DataBytes;
if (i < dataBytes.Length)
{
result.appendBits(dataBytes[i], 8);
}
}
}
// Then, place error correction blocks.
for (int i = 0; i < maxNumEcBytes; ++i)
{
foreach (BlockPair block in blocks)
{
byte[] ecBytes = block.ErrorCorrectionBytes;
if (i < ecBytes.Length)
{
result.appendBits(ecBytes[i], 8);
}
}
}
if (numTotalBytes != result.SizeInBytes)
{ // Should be same.
throw new WriterException("Interleaving error: " + numTotalBytes + " and " +
result.SizeInBytes + " differ.");
}
return result;
}
internal static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock)
{
int numDataBytes = dataBytes.Length;
int[] toEncode = new int[numDataBytes + numEcBytesInBlock];
for (int i = 0; i < numDataBytes; i++)
{
toEncode[i] = dataBytes[i] & 0xFF;
}
new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock);
byte[] ecBytes = new byte[numEcBytesInBlock];
for (int i = 0; i < numEcBytesInBlock; i++)
{
ecBytes[i] = (byte)toEncode[numDataBytes + i];
}
return ecBytes;
}
/// <summary>
/// Append mode info. On success, store the result in "bits".
/// </summary>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
internal static void appendModeInfo(Mode mode, BitArray bits)
{
bits.appendBits(mode.Bits, 4);
}
/// <summary>
/// Append length info. On success, store the result in "bits".
/// </summary>
/// <param name="numLetters">The num letters.</param>
/// <param name="version">The version.</param>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
internal static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits)
{
int numBits = mode.getCharacterCountBits(version);
if (numLetters >= (1 << numBits))
{
throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1));
}
bits.appendBits(numLetters, numBits);
}
/// <summary>
/// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
/// </summary>
/// <param name="content">The content.</param>
/// <param name="mode">The mode.</param>
/// <param name="bits">The bits.</param>
/// <param name="encoding">The encoding.</param>
internal static void appendBytes(String content,
Mode mode,
BitArray bits,
String encoding)
{
if (mode.Equals(Mode.NUMERIC))
appendNumericBytes(content, bits);
else
if (mode.Equals(Mode.ALPHANUMERIC))
appendAlphanumericBytes(content, bits);
else
if (mode.Equals(Mode.BYTE))
append8BitBytes(content, bits, encoding);
else
if (mode.Equals(Mode.KANJI))
appendKanjiBytes(content, bits);
else
throw new WriterException("Invalid mode: " + mode);
}
internal static void appendNumericBytes(String content, BitArray bits)
{
int length = content.Length;
int i = 0;
while (i < length)
{
int num1 = content[i] - '0';
if (i + 2 < length)
{
// Encode three numeric letters in ten bits.
int num2 = content[i + 1] - '0';
int num3 = content[i + 2] - '0';
bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
i += 3;
}
else if (i + 1 < length)
{
// Encode two numeric letters in seven bits.
int num2 = content[i + 1] - '0';
bits.appendBits(num1 * 10 + num2, 7);
i += 2;
}
else
{
// Encode one numeric letter in four bits.
bits.appendBits(num1, 4);
i++;
}
}
}
internal static void appendAlphanumericBytes(String content, BitArray bits)
{
int length = content.Length;
int i = 0;
while (i < length)
{
int code1 = getAlphanumericCode(content[i]);
if (code1 == -1)
{
throw new WriterException();
}
if (i + 1 < length)
{
int code2 = getAlphanumericCode(content[i + 1]);
if (code2 == -1)
{
throw new WriterException();
}
// Encode two alphanumeric letters in 11 bits.
bits.appendBits(code1 * 45 + code2, 11);
i += 2;
}
else
{
// Encode one alphanumeric letter in six bits.
bits.appendBits(code1, 6);
i++;
}
}
}
internal static void append8BitBytes(String content, BitArray bits, String encoding)
{
byte[] bytes;
try
{
bytes = Encoding.GetEncoding(encoding).GetBytes(content);
}
#if WindowsCE
catch (PlatformNotSupportedException)
{
try
{
// WindowsCE doesn't support all encodings. But it is device depended.
// So we try here the some different ones
if (encoding == "ISO-8859-1")
{
bytes = Encoding.GetEncoding(1252).GetBytes(content);
}
else
{
bytes = Encoding.GetEncoding("UTF-8").GetBytes(content);
}
}
catch (Exception uee)
{
throw new WriterException(uee.Message, uee);
}
}
#endif
catch (Exception uee)
{
throw new WriterException(uee.Message, uee);
}
foreach (byte b in bytes)
{
bits.appendBits(b, 8);
}
}
internal static void appendKanjiBytes(String content, BitArray bits)
{
byte[] bytes;
try
{
bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content);
}
catch (Exception uee)
{
throw new WriterException(uee.Message, uee);
}
int length = bytes.Length;
for (int i = 0; i < length; i += 2)
{
int byte1 = bytes[i] & 0xFF;
int byte2 = bytes[i + 1] & 0xFF;
int code = (byte1 << 8) | byte2;
int subtracted = -1;
if (code >= 0x8140 && code <= 0x9ffc)
{
subtracted = code - 0x8140;
}
else if (code >= 0xe040 && code <= 0xebbf)
{
subtracted = code - 0xc140;
}
if (subtracted == -1)
{
throw new WriterException("Invalid byte sequence");
}
int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
bits.appendBits(encoded, 13);
}
}
private static void appendECI(CharacterSetECI eci, BitArray bits)
{
bits.appendBits(Mode.ECI.Bits, 4);
// This is correct for values up to 127, which is all we need now.
bits.appendBits(eci.Value, 8);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract partial class JsonWriter : IDisposable
{
internal enum State
{
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTemplate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
List<State[]> allStates = StateArrayTemplate.ToList();
State[] errorStates = StateArrayTemplate[0];
State[] valueStates = StateArrayTemplate[7];
EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(typeof(JsonToken));
foreach (ulong valueToken in enumValuesAndNames.Values)
{
if (allStates.Count <= (int)valueToken)
{
JsonToken token = (JsonToken)valueToken;
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private List<JsonPosition>? _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the destination should be closed when this writer is closed.
/// </summary>
/// <value>
/// <c>true</c> to close the destination when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the JSON should be auto-completed when this writer is closed.
/// </summary>
/// <value>
/// <c>true</c> to auto-complete the JSON when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool AutoCompleteOnClose { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = _stack?.Count ?? 0;
if (Peek() != JsonContainerType.None)
{
depth++;
}
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None || _stack == null)
{
return string.Empty;
}
return JsonPosition.BuildPath(_stack, null);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack!, current);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string? _dateFormatString;
private CultureInfo? _culture;
/// <summary>
/// Gets or sets a value indicating how JSON text output should be formatted.
/// </summary>
public Formatting Formatting
{
get => _formatting;
set
{
if (value < Formatting.None || value > Formatting.Indented)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_formatting = value;
}
}
/// <summary>
/// Gets or sets how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get => _dateFormatHandling;
set
{
if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateFormatHandling = value;
}
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> time zones are handled when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get => _dateTimeZoneHandling;
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Gets or sets how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get => _stringEscapeHandling;
set
{
if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>,
/// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get => _floatFormatHandling;
set
{
if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatFormatHandling = value;
}
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text.
/// </summary>
public string? DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get => _culture ?? CultureInfo.InvariantCulture;
set => _culture = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriter"/> class.
/// </summary>
protected JsonWriter()
{
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
AutoCompleteOnClose = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
}
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack != null && _stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the destination and also flushes the destination.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this writer.
/// If <see cref="CloseOutput"/> is set to <c>true</c>, the destination is also closed.
/// If <see cref="AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed.
/// </summary>
public virtual void Close()
{
if (AutoCompleteOnClose)
{
AutoCompleteAll();
}
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair of a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair of a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current JSON object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
WriteToken(reader, writeChildren, true, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// <c>null</c> can be passed to the method for tokens that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.
/// </param>
public void WriteToken(JsonToken token, object? value)
{
switch (token)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment(value?.ToString());
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if HAVE_BIG_INTEGER
if (value is BigInteger integer)
{
WriteValue(integer);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is decimal decimalValue)
{
WriteValue(decimalValue);
}
else if (value is double doubleValue)
{
WriteValue(doubleValue);
}
else if (value is float floatValue)
{
WriteValue(floatValue);
}
else
{
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.String:
// Allow for a null string. This matches JTokenReader behavior which can read
// a JsonToken.String with a null value.
WriteValue(value?.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if HAVE_DATE_TIME_OFFSET
if (value is DateTimeOffset dt)
{
WriteValue(dt);
}
else
#endif
{
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Raw:
WriteRawValue(value?.ToString());
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is Guid guid)
{
WriteValue(guid);
}
else
{
WriteValue((byte[])value!);
}
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type.");
}
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteToken(token, null);
}
internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
int initialDepth = CalculateWriteTokenInitialDepth(reader);
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
else
{
if (writeComments || reader.TokenType != JsonToken.Comment)
{
WriteToken(reader.TokenType, reader.Value);
}
}
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
if (IsWriteTokenIncomplete(reader, writeChildren, initialDepth))
{
throw JsonWriterException.Create(this, "Unexpected end when reading token.", null);
}
}
private bool IsWriteTokenIncomplete(JsonReader reader, bool writeChildren, int initialDepth)
{
int finalDepth = CalculateWriteTokenFinalDepth(reader);
return initialDepth < finalDepth ||
(writeChildren && initialDepth == finalDepth && JsonTokenUtils.IsStartToken(reader.TokenType));
}
private int CalculateWriteTokenInitialDepth(JsonReader reader)
{
JsonToken type = reader.TokenType;
if (type == JsonToken.None)
{
return -1;
}
return JsonTokenUtils.IsStartToken(type) ? reader.Depth : reader.Depth + 1;
}
private int CalculateWriteTokenFinalDepth(JsonReader reader)
{
JsonToken type = reader.TokenType;
if (type == JsonToken.None)
{
return -1;
}
return JsonTokenUtils.IsEndToken(type) ? reader.Depth - 1 : reader.Depth;
}
private void WriteConstructorDate(JsonReader reader)
{
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string? errorMessage))
{
throw JsonWriterException.Create(this, errorMessage, null);
}
WriteValue(dateTime);
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
int levelsToComplete = CalculateLevelsToComplete(type);
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
{
WriteNull();
}
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
{
WriteIndent();
}
}
WriteEnd(token);
UpdateCurrentState();
}
}
private int CalculateLevelsToComplete(JsonContainerType type)
{
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack![currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
{
throw JsonWriterException.Create(this, "No token to close.", null);
}
return levelsToComplete;
}
private void UpdateCurrentState()
{
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
{
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
}
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
{
WriteIndentSpace();
}
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
{
WriteIndent();
}
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string? json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string? json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string? value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[]? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Bytes);
}
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri? value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.String);
}
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object? value)
{
if (value == null)
{
WriteNull();
}
else
{
#if HAVE_BIG_INTEGER
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
{
throw CreateUnsupportedTypeException(this, value);
}
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value);
}
}
#endregion
/// <summary>
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string? text)
{
InternalWriteComment();
}
/// <summary>
/// Writes the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
while (true)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
return;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
return;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
return;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
return;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
return;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
return;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
return;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
return;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
return;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
return;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
return;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
return;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
return;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
return;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
return;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
return;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
return;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
return;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
return;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
return;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
return;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
return;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
return;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
return;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
return;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
return;
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
return;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
return;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
return;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
return;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
return;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
return;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
return;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
return;
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
return;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
return;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
return;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
return;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
return;
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
return;
#endif
default:
#if HAVE_ICONVERTIBLE
if (value is IConvertible convertible)
{
ResolveConvertibleValue(convertible, out typeCode, out value);
continue;
}
#endif
// write an unknown null value, fix https://github.com/JamesNK/Newtonsoft.Json/issues/1460
if (value == null)
{
writer.WriteNull();
return;
}
throw CreateUnsupportedTypeException(writer, value);
}
}
}
#if HAVE_ICONVERTIBLE
private static void ResolveConvertibleValue(IConvertible convertible, out PrimitiveTypeCode typeCode, out object value)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertible);
// if convertible has an underlying typecode of Object then attempt to convert it to a string
typeCode = typeInformation.TypeCode == PrimitiveTypeCode.Object ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = typeInformation.TypeCode == PrimitiveTypeCode.Object ? typeof(string) : typeInformation.Type;
value = convertible.ToType(resolvedType, CultureInfo.InvariantCulture);
}
#endif
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the <see cref="JsonWriter"/>.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string s))
{
throw new ArgumentException("A name is required when setting property name state.", nameof(value));
}
InternalWritePropertyName(s);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException(nameof(token));
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
{
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Gaming.Math;
namespace Gaming.Math
{
public struct Vector2D
{
public double x, y;
public Vector2D(double newX, double newY)
{
x = newX;
y = newY;
}
public Vector2D(float newX, float newY)
: this((double)newX, (double)newY)
{
}
public void Set(double inX, double inY)
{
x = inX;
y = inY;
}
//bool operator==(Vector2D B);
//bool operator!=(Vector2D B);
//double operator[](int Index) { return Index == 0 ? x : y; }
//double operator[](int Index) { return Index == 0 ? x : y; }
static public Vector2D operator+(Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D();
temp.x = A.x + B.x;
temp.y = A.y + B.y;
return temp;
}
static public Vector2D operator-(Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D();
temp.x = A.x - B.x;
temp.y = A.y - B.y;
return temp;
}
static public Vector2D operator*(Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D();
temp.x = A.x * B.x;
temp.y = A.y * B.y;
return temp;
}
static public Vector2D operator *(Vector2D A, double B)
{
Vector2D temp = new Vector2D();
temp.x = A.x * B;
temp.y = A.y * B;
return temp;
}
static public Vector2D operator *(double B, Vector2D A)
{
Vector2D temp = new Vector2D();
temp.x = A.x * B;
temp.y = A.y * B;
return temp;
}
static public Vector2D operator *(Vector2D A, float B)
{
Vector2D temp = new Vector2D();
temp.x = A.x * (double)B;
temp.y = A.y * (double)B;
return temp;
}
static public Vector2D operator *(float B, Vector2D A)
{
Vector2D temp = new Vector2D();
temp.x = A.x * (double)B;
temp.y = A.y * (double)B;
return temp;
}
static public Vector2D operator /(Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D();
temp.x = A.x / B.x;
temp.y = A.y / B.y;
return temp;
}
static public Vector2D operator /(Vector2D A, double B)
{
Vector2D temp = new Vector2D();
temp.x = A.x / B;
temp.y = A.y / B;
return temp;
}
static public Vector2D operator /(double B, Vector2D A)
{
Vector2D temp = new Vector2D();
temp.x = A.x / B;
temp.y = A.y / B;
return temp;
}
// are they the same within the error value?
public bool Equals(Vector2D OtherVector, double ErrorValue)
{
if ((x < OtherVector.x + ErrorValue && x > OtherVector.x - ErrorValue) &&
(y < OtherVector.y + ErrorValue && y > OtherVector.y - ErrorValue))
{
return true;
}
return false;
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
Vector2D p = (Vector2D)obj;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
return x.GetHashCode() ^ y.GetHashCode();
}
public static bool operator ==(Vector2D a, Vector2D b)
{
return a.Equals(b);
}
public static bool operator !=(Vector2D a, Vector2D b)
{
return !a.Equals(b);
}
public Vector2D GetPerpendicular()
{
Vector2D temp = new Vector2D(y, -x);
return temp;
}
public Vector2D GetPerpendicularNormal()
{
Vector2D Perpendicular = GetPerpendicular();
Perpendicular.Normalize();
return Perpendicular;
}
public double GetLength()
{
return (double)System.Math.Sqrt((x * x) + (y * y));
}
public double GetLengthSquared()
{
return Dot(this);
}
public static double GetDistanceBetween(Vector2D A, Vector2D B)
{
return (double)System.Math.Sqrt(GetDistanceBetweenSquared(A, B));
}
public static double GetDistanceBetweenSquared(Vector2D A, Vector2D B)
{
return ((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y));
}
public double GetSquaredDistanceTo(Vector2D Other)
{
return ((x - Other.x) * (x - Other.x) + (y - Other.y) * (y - Other.y));
}
static public double Range0To2PI(double Value)
{
if (Value < 0)
{
Value += 2 * (double)System.Math.PI;
}
if (Value >= 2 * (double)System.Math.PI)
{
Value -= 2 * (double)System.Math.PI;
}
if (Value < 0 || Value > 2 * System.Math.PI) throw new Exception("Value >= 0 && Value <= 2 * PI");
return Value;
}
static public double GetDeltaAngle(double StartAngle, double EndAngle)
{
if (StartAngle != Range0To2PI(StartAngle)) throw new Exception("StartAngle == Range0To2PI(StartAngle)");
if (EndAngle != Range0To2PI(EndAngle)) throw new Exception("EndAngle == Range0To2PI(EndAngle)");
double DeltaAngle = EndAngle - StartAngle;
if (DeltaAngle > System.Math.PI)
{
DeltaAngle -= 2 * (double)System.Math.PI;
}
if (DeltaAngle < -System.Math.PI)
{
DeltaAngle += 2 * (double)System.Math.PI;
}
return DeltaAngle;
}
public double GetAngle0To2PI()
{
return (double)Range0To2PI((double)System.Math.Atan2((double)y, (double)x));
}
public double GetDeltaAngle(Vector2D A)
{
return (double)GetDeltaAngle(GetAngle0To2PI(), A.GetAngle0To2PI());
}
public void Normalize()
{
double Length;
Length=GetLength();
if (Length == 0) throw new Exception("Length != 0.f");
if(Length != 0.0f)
{
double InversLength=1.0f / Length;
x *= InversLength;
y *= InversLength;
}
}
public void Normalize(double Length)
{
if (Length == 0) throw new Exception("Length == 0.f");
if(Length != 0.0f)
{
double InversLength=1.0f / Length;
x *= InversLength;
y *= InversLength;
}
}
public double NormalizeAndReturnLength()
{
double Length;
Length=GetLength();
if(Length != 0.0f)
{
double InversLength=1.0f / Length;
x *= InversLength;
y *= InversLength;
}
return Length;
}
public void Rotate(double Radians)
{
Vector2D Temp;
double Cos, Sin;
Cos = (double)System.Math.Cos(Radians);
Sin = (double)System.Math.Sin(Radians);
Temp.x = x * Cos + y * Sin;
Temp.y = y * Cos + x * Sin;
x = Temp.x;
y = Temp.y;
}
public void Zero()
{
x = (double)0;
y = (double)0;
}
public void Negate()
{
x = -x;
y = -y;
}
public double Dot(Vector2D B)
{
return (x*B.x + y*B.y);
}
public double Cross(Vector2D B)
{
return x * B.y - y * B.x;
}
};
}
namespace NUnitGaming
{
[TestFixture]
public class Vector2DTests
{
[Test]
public void ArithmaticOperations()
{
Vector2D Point1 = new Vector2D();
Point1.Set(1, 1);
Vector2D Point2 = new Vector2D();
Point2.Set(2, 2);
Vector2D Point3 = Point1 + Point2;
Assert.IsTrue(Point3 == new Vector2D(3, 3));
Point3 = Point1 - Point2;
Assert.IsTrue(Point3 == new Vector2D(-1, -1));
Point3 += Point1;
Assert.IsTrue(Point3 == new Vector2D(0, 0));
Point3 += Point2;
Assert.IsTrue(Point3 == new Vector2D(2, 2));
Point3 *= 6;
Assert.IsTrue(Point3 == new Vector2D(12, 12));
Vector2D InlineOpLeftSide = new Vector2D(5, -3);
Vector2D InlineOpRightSide = new Vector2D(-5, 4);
Assert.IsTrue(InlineOpLeftSide + InlineOpRightSide == new Vector2D(.0f, 1));
Assert.IsTrue(InlineOpLeftSide - InlineOpRightSide == new Vector2D(10.0f, -7));
}
[Test]
public void GetLengthAndNormalize()
{
Vector2D Point3 = new Vector2D(3, -4);
Assert.IsTrue(Point3.GetLength() > 4.999f && Point3.GetLength() < 5.001f);
Point3.Normalize();
Assert.IsTrue(Point3.GetLength() > 0.99f && Point3.GetLength() < 1.01f);
}
[Test]
public void ScalerOperations()
{
Vector2D ScalarMultiplicationArgument = new Vector2D(5.0f, 4.0f);
Assert.IsTrue(ScalarMultiplicationArgument * -.5 == new Vector2D(-2.5f, -2));
Assert.IsTrue(ScalarMultiplicationArgument / 2 == new Vector2D(2.5f, 2));
Assert.IsTrue(2 / ScalarMultiplicationArgument == new Vector2D(2.5f, 2));
Assert.IsTrue(5 * ScalarMultiplicationArgument == new Vector2D(25, 20));
}
[Test]
public void Rotate()
{
Vector2D TestVector = new Vector2D(1, 0);
TestVector.Rotate((double)System.Math.PI / 2);
Assert.IsTrue(TestVector.Equals(new Vector2D(0, 1), .001f));
}
[Test]
public void CrossProduct()
{
Random Rand = new Random();
Vector2D TestVector2D1 = new Vector2D(Rand.NextDouble() * 1000, Rand.NextDouble() * 1000);
Vector2D TestVector2D2 = new Vector2D(Rand.NextDouble() * 1000, Rand.NextDouble() * 1000);
double Cross2D = TestVector2D1.Cross(TestVector2D2);
Vector3D TestVector3D1 = new Vector3D(TestVector2D1.x, TestVector2D1.y, 0);
Vector3D TestVector3D2 = new Vector3D(TestVector2D2.x, TestVector2D2.y, 0);
Vector3D Cross3D = TestVector3D1.Cross(TestVector3D2);
Assert.IsTrue(Cross3D.z == Cross2D);
}
[Test]
public void DotProduct()
{
Random Rand = new Random();
Vector2D TestVector2D1 = new Vector2D(Rand.NextDouble() * 1000, Rand.NextDouble() * 1000);
Vector2D TestVector2D2 = new Vector2D(Rand.NextDouble() * 1000, Rand.NextDouble() * 1000);
double Cross2D = TestVector2D1.Dot(TestVector2D2);
Vector3D TestVector3D1 = new Vector3D(TestVector2D1.x, TestVector2D1.y, 0);
Vector3D TestVector3D2 = new Vector3D(TestVector2D2.x, TestVector2D2.y, 0);
double Cross3D = TestVector3D1.Dot(TestVector3D2);
Assert.IsTrue(Cross3D == Cross2D);
}
[Test]
public void LengthAndDistance()
{
Random Rand = new Random();
Vector2D Test1 = new Vector2D(Rand.NextDouble() * 1000, Rand.NextDouble() * 1000);
Vector2D Test2 = new Vector2D(Rand.NextDouble() * 1000, Rand.NextDouble() * 1000);
Vector2D Test3 = Test1 + Test2;
double Distance1 = Test2.GetLength();
double Distance2 = Vector2D.GetDistanceBetween(Test1, Test3);
Assert.IsTrue(Distance1 < Distance2 + .001f && Distance1 > Distance2 - .001f);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace LumiSoft.Net.SIP.Message
{
/// <summary>
/// Implements SIP "accept-range" value. Defined in RFC 3261.
/// </summary>
/// <remarks>
/// <code>
/// RFC 3261 Syntax:
/// accept-range = media-range [ accept-params ]
/// media-range = ("*//*" / (m-type SLASH "*") / (m-type SLASH m-subtype)) *(SEMI m-parameter)
/// accept-params = SEMI "q" EQUAL qvalue *(SEMI generic-param)
/// </code>
/// </remarks>
public class SIP_t_AcceptRange : SIP_t_Value
{
private string m_MediaType = "";
private SIP_ParameterCollection m_pMediaParameters = null;
private SIP_ParameterCollection m_pParameters = null;
/// <summary>
/// Default constructor.
/// </summary>
public SIP_t_AcceptRange()
{
m_pMediaParameters = new SIP_ParameterCollection();
m_pParameters = new SIP_ParameterCollection();
}
#region method Parse
/// <summary>
/// Parses "accept-range" from specified value.
/// </summary>
/// <param name="value">SIP "accept-range" value.</param>
/// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception>
/// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
public void Parse(string value)
{
if(value == null){
throw new ArgumentNullException("value");
}
Parse(new StringReader(value));
}
/// <summary>
/// Parses "accept-range" from specified reader.
/// </summary>
/// <param name="reader">Reader from where to parse.</param>
/// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
/// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
public override void Parse(StringReader reader)
{
/*
accept-range = media-range [ accept-params ]
media-range = ("*//*" / (m-type SLASH "*") / (m-type SLASH m-subtype)) *(SEMI m-parameter)
accept-params = SEMI "q" EQUAL qvalue *(SEMI generic-param)
*/
if(reader == null){
throw new ArgumentNullException("reader");
}
// Parse m-type
string word = reader.ReadWord();
if(word == null){
throw new SIP_ParseException("Invalid 'accept-range' value, m-type is missing !");
}
this.MediaType = word;
// Parse media and accept parameters !!! thats confusing part, RFC invalid.
bool media_accept = true;
while(reader.Available > 0){
reader.ReadToFirstChar();
// We have 'next' value, so we are done here.
if(reader.SourceString.StartsWith(",")){
break;
}
// We have parameter
else if(reader.SourceString.StartsWith(";")){
reader.ReadSpecifiedLength(1);
string paramString = reader.QuotedReadToDelimiter(new char[]{';',','},false);
if(paramString != ""){
string[] name_value = paramString.Split(new char[]{'='},2);
string name = name_value[0].Trim();
string value = "";
if(name_value.Length == 2){
value = name_value[1];
}
// If q, then accept parameters begin
if(name.ToLower() == "q"){
media_accept = false;
}
if(media_accept){
this.MediaParameters.Add(name,value);
}
else{
this.Parameters.Add(name,value);
}
}
}
// Unknown data
else{
throw new SIP_ParseException("SIP_t_AcceptRange unexpected prarameter value !");
}
}
}
#endregion
#region method ToStringValue
/// <summary>
/// Converts this to valid "accept-range" value.
/// </summary>
/// <returns>Returns "accept-range" value.</returns>
public override string ToStringValue()
{
/*
Accept = "Accept" HCOLON [ accept-range *(COMMA accept-range) ]
accept-range = media-range [ accept-params ]
media-range = ("*//*" / (m-type SLASH "*") / (m-type SLASH m-subtype)) *(SEMI m-parameter)
accept-params = SEMI "q" EQUAL qvalue *(SEMI generic-param)
*/
StringBuilder retVal = new StringBuilder();
retVal.Append(m_MediaType);
foreach(SIP_Parameter parameter in m_pMediaParameters){
if(parameter.Value != null){
retVal.Append(";" + parameter.Name + "=" + parameter.Value);
}
else{
retVal.Append(";" + parameter.Name);
}
}
foreach(SIP_Parameter parameter in m_pParameters){
if(parameter.Value != null){
retVal.Append(";" + parameter.Name + "=" + parameter.Value);
}
else{
retVal.Append(";" + parameter.Name);
}
}
return retVal.ToString();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets or sets media type. Value *(STAR) means all values. Syntax: mediaType / mediaSubType.
/// Examples: */*,video/*,text/html.
/// </summary>
public string MediaType
{
get{ return m_MediaType; }
set{
if(string.IsNullOrEmpty(value)){
throw new ArgumentException("Property MediaType value can't be null or empty !");
}
if(value.IndexOf('/') == -1){
throw new ArgumentException("Invalid roperty MediaType value, syntax: mediaType / mediaSubType !");
}
m_MediaType = value;
}
}
/// <summary>
/// Gets media parameters collection.
/// </summary>
/// <returns></returns>
public SIP_ParameterCollection MediaParameters
{
get{ return m_pMediaParameters; }
}
/// <summary>
/// Gets accept value parameters.
/// </summary>
public SIP_ParameterCollection Parameters
{
get{ return m_pParameters; }
}
/// <summary>
/// Gets or sets qvalue parameter. Targets are processed from highest qvalue to lowest.
/// This value must be between 0.0 and 1.0. Value -1 means that value not specified.
/// </summary>
public double QValue
{
get{
SIP_Parameter parameter = this.Parameters["qvalue"];
if(parameter != null){
return Convert.ToDouble(parameter.Value);
}
else{
return -1;
}
}
set{
if(value < 0 || value > 1){
throw new ArgumentException("Property QValue value must be between 0.0 and 1.0 !");
}
if(value < 0){
this.Parameters.Remove("qvalue");
}
else{
this.Parameters.Set("qvalue",value.ToString());
}
}
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. 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.Globalization;
using System.Linq;
using System.Xml.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.WebHooks.Metadata;
using Microsoft.AspNetCore.WebHooks.Properties;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.WebHooks.ApplicationModels
{
/// <summary>
/// An <see cref="IApplicationModelProvider"/> implementation that adds model binding information
/// (<see cref="BindingInfo"/> settings similar to <see cref="IBindingSourceMetadata"/> and
/// <see cref="IModelNameProvider"/>) to <see cref="ParameterModel"/>s of WebHook actions.
/// </summary>
public class WebHookBindingInfoProvider : IApplicationModelProvider
{
private readonly ILogger _logger;
/// <summary>
/// Instantiates a new <see cref="WebHookBindingInfoProvider"/> instance with the given
/// <paramref name="loggerFactory"/>.
/// </summary>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
public WebHookBindingInfoProvider(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<WebHookBindingInfoProvider>();
}
/// <summary>
/// Gets the <see cref="IApplicationModelProvider.Order"/> value used in all
/// <see cref="WebHookBindingInfoProvider"/> instances. The WebHook <see cref="IApplicationModelProvider"/>
/// order is
/// <list type="number">
/// <item>
/// Add <see cref="IWebHookMetadata"/> references to the <see cref="ActionModel.Properties"/> collections of
/// WebHook actions and validate those <see cref="IWebHookMetadata"/> attributes and services (in
/// <see cref="WebHookActionModelPropertyProvider"/>).
/// </item>
/// <item>
/// Add routing information (<see cref="SelectorModel"/> settings) to <see cref="ActionModel"/>s of WebHook
/// actions (in <see cref="WebHookSelectorModelProvider"/>).
/// </item>
/// <item>
/// Add filters to the <see cref="ActionModel.Filters"/> collections of WebHook actions (in
/// <see cref="WebHookActionModelFilterProvider"/>).
/// </item>
/// <item>
/// Add model binding information (<see cref="BindingInfo"/> settings) to <see cref="ParameterModel"/>s of
/// WebHook actions (in this provider).
/// </item>
/// </list>
/// </summary>
public static int Order => WebHookActionModelFilterProvider.Order + 10;
/// <inheritdoc />
int IApplicationModelProvider.Order => Order;
/// <inheritdoc />
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
for (var i = 0; i < context.Result.Controllers.Count; i++)
{
var controller = context.Result.Controllers[i];
for (var j = 0; j < controller.Actions.Count; j++)
{
var action = controller.Actions[j];
var attribute = action.Attributes.OfType<WebHookAttribute>().FirstOrDefault();
if (attribute == null)
{
// Not a WebHook handler.
continue;
}
WebHookBodyType? bodyType;
var properties = action.Properties;
var bodyTypeMetadataObject = properties[typeof(IWebHookBodyTypeMetadataService)];
if (bodyTypeMetadataObject is IWebHookBodyTypeMetadataService bodyTypeMetadata)
{
bodyType = bodyTypeMetadata.BodyType;
}
else if (properties.TryGetValue(typeof(IWebHookBodyTypeMetadata), out bodyTypeMetadataObject))
{
// Reachable only in [GeneralWebHook(WebHookBodyType)] cases. That attribute implements
// IWebHookBodyTypeMetadata and WebHookActionModelPropertyProvider passed it along because its
// BodyType is not null.
var actionBodyTypeMetadata = (IWebHookBodyTypeMetadata)bodyTypeMetadataObject;
bodyType = actionBodyTypeMetadata.BodyType;
}
else
{
// Reachable only in [GeneralWebHook] cases. SourceData will warn if a data parameter is found.
bodyType = null;
}
properties.TryGetValue(typeof(IWebHookBindingMetadata), out var bindingMetadata);
for (var k = 0; k < action.Parameters.Count; k++)
{
var parameter = action.Parameters[k];
Apply((IWebHookBindingMetadata)bindingMetadata, bodyType, parameter);
}
}
}
}
/// <inheritdoc />
public void OnProvidersExecuted(ApplicationModelProviderContext context)
{
// No-op
}
private void Apply(
IWebHookBindingMetadata bindingMetadata,
WebHookBodyType? bodyType,
ParameterModel parameter)
{
var bindingInfo = parameter.BindingInfo;
if (bindingInfo?.BinderModelName != null ||
bindingInfo?.BinderType != null ||
bindingInfo?.BindingSource != null)
{
// User was explicit. Nothing to do.
return;
}
if (bindingInfo == null)
{
bindingInfo = parameter.BindingInfo = new BindingInfo();
}
var parameterName = parameter.ParameterName;
var parameterType = parameter.ParameterInfo.ParameterType;
switch (parameterName.ToUpperInvariant())
{
case "ACTION":
case "ACTIONS":
case "ACTIONNAME":
case "ACTIONNAMES":
SourceEvent(bindingInfo, parameterType, parameterName);
break;
case "DATA":
SourceData(bindingInfo, bodyType, parameterName);
break;
case "EVENT":
case "EVENTS":
case "EVENTNAME":
case "EVENTNAMES":
SourceEvent(bindingInfo, parameterType, parameterName);
break;
case "ID":
SourceId(bindingInfo, parameterType, parameterName);
break;
case "RECEIVER":
case "RECEIVERNAME":
SourceReceiver(bindingInfo, parameterType, parameterName);
break;
case "RECEIVERID":
SourceId(bindingInfo, parameterType, parameterName);
break;
case "WEBHOOKRECEIVER":
SourceReceiver(bindingInfo, parameterType, parameterName);
break;
default:
// If additional parameters are configured and match, map them. If not, treat IFormCollection,
// JContainer and XElement parameters as data. IsAssignableFrom(...) looks reversed because this
// check is about model binding system support, not an actual assignment to the parameter.
if (!TrySourceAdditionalParameter(bindingInfo, bindingMetadata, parameterName) &&
(typeof(IFormCollection).IsAssignableFrom(parameterType) ||
typeof(JToken).IsAssignableFrom(parameterType) ||
typeof(XElement).IsAssignableFrom(parameterType)))
{
SourceData(bindingInfo, bodyType, parameterName);
}
break;
}
}
private void SourceData(
BindingInfo bindingInfo,
WebHookBodyType? bodyType,
string parameterName)
{
if (!bodyType.HasValue)
{
_logger.LogWarning(
0,
"Not adding binding information for '{ParameterName}' parameter. WebHookBodyType is not known.",
parameterName);
return;
}
if (bodyType.Value == WebHookBodyType.Form)
{
bindingInfo.BinderModelName = WebHookConstants.ModelStateBodyModelName;
bindingInfo.BindingSource = BindingSource.Form;
return;
}
bindingInfo.BinderModelName = WebHookConstants.ModelStateBodyModelName;
bindingInfo.BindingSource = BindingSource.Body;
}
private void SourceEvent(BindingInfo bindingInfo, Type parameterType, string parameterName)
{
// IsAssignableFrom(...) looks reversed because this check is about model binding system support, not an
// actual assignment to the parameter.
if (typeof(string) != parameterType &&
!typeof(IEnumerable<string>).IsAssignableFrom(parameterType))
{
_logger.LogWarning(
1,
"Not adding binding information for '{ParameterName}' parameter of unsupported type " +
"'{ParameterType}'.",
parameterName,
parameterType);
return;
}
bindingInfo.BinderModelName = WebHookConstants.EventKeyName;
bindingInfo.BindingSource = BindingSource.Path;
}
private void SourceId(BindingInfo bindingInfo, Type parameterType, string parameterName)
{
if (typeof(string) != parameterType)
{
_logger.LogWarning(
2,
"Not adding binding information for '{ParameterName}' parameter of unsupported type " +
"'{ParameterType}'.",
parameterName,
parameterType);
return;
}
bindingInfo.BinderModelName = WebHookConstants.IdKeyName;
bindingInfo.BindingSource = BindingSource.Path;
}
private void SourceReceiver(BindingInfo bindingInfo, Type parameterType, string parameterName)
{
if (typeof(string) != parameterType)
{
_logger.LogWarning(
3,
"Not adding binding information for '{ParameterName}' parameter of unsupported type " +
"'{ParameterType}'.",
parameterName,
parameterType);
return;
}
bindingInfo.BinderModelName = WebHookConstants.ReceiverKeyName;
bindingInfo.BindingSource = BindingSource.Path;
}
private static bool TrySourceAdditionalParameter(
BindingInfo bindingInfo,
IWebHookBindingMetadata bindingMetadata,
string parameterName)
{
var parameter = bindingMetadata?.Parameters
.FirstOrDefault(item => string.Equals(parameterName, item.Name, StringComparison.OrdinalIgnoreCase));
if (parameter == null)
{
return false;
}
bindingInfo.BinderModelName = parameter.SourceName;
switch (parameter.ParameterType)
{
case WebHookParameterType.Header:
bindingInfo.BindingSource = BindingSource.Header;
break;
case WebHookParameterType.RouteValue:
bindingInfo.BindingSource = BindingSource.Path;
break;
case WebHookParameterType.QueryParameter:
bindingInfo.BindingSource = BindingSource.Query;
break;
default:
var message = string.Format(
CultureInfo.CurrentCulture,
Resources.General_InvalidEnumValue,
typeof(WebHookParameterType),
parameter.ParameterType);
throw new InvalidOperationException(message);
}
return true;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using CSharpGuidelinesAnalyzer.Rules.Maintainability;
using CSharpGuidelinesAnalyzer.Test.TestDataBuilders;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace CSharpGuidelinesAnalyzer.Test.Specs.Maintainability
{
public sealed class AvoidConditionWithDoubleNegationSpecs : CSharpGuidelinesAnalysisTestFixture
{
protected override string DiagnosticId => AvoidConditionWithDoubleNegationAnalyzer.DiagnosticId;
[Fact]
internal void When_logical_not_operator_is_applied_on_a_method_with_Not_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsNotVisible()
{
return true;
}
public void M()
{
if ([|!IsNotVisible()|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on method 'IsNotVisible', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_method_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsNoActiveCustomer()
{
return true;
}
public void M()
{
if ([|!IsNoActiveCustomer()|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on method 'IsNoActiveCustomer', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_chained_method_with_No_in_its_name_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(Enumerable).Assembly)
.Using(typeof(Enumerable).Namespace)
.Using(typeof(IEnumerable<>).Namespace)
.InGlobalScope(@"
class C
{
public IEnumerable<string> GetNotActiveCustomerNames()
{
throw new NotImplementedException();
}
public void M()
{
if (!GetNotActiveCustomerNames().Any())
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_normal_method_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsNotVisible()
{
return true;
}
public bool IsHidden() => IsNotVisible();
public void M()
{
if (!IsHidden())
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_local_function_with_Not_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M()
{
bool IsNotVisible()
{
return true;
}
void L()
{
if ([|!IsNotVisible()|])
{
}
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on local function 'IsNotVisible', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_local_function_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M()
{
bool IsNoActiveCustomer()
{
return true;
}
void L()
{
if ([|!IsNoActiveCustomer()|])
{
}
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on local function 'IsNoActiveCustomer', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_chained_local_function_with_No_in_its_name_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.WithReference(typeof(Enumerable).Assembly)
.Using(typeof(Enumerable).Namespace)
.Using(typeof(IEnumerable<>).Namespace)
.InGlobalScope(@"
class C
{
public void M()
{
IEnumerable<string> GetNotActiveCustomerNames()
{
throw new NotImplementedException();
}
void L()
{
if (!GetNotActiveCustomerNames().Any())
{
}
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_normal_local_function_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M()
{
bool IsNotVisible()
{
return true;
}
bool IsHidden() => IsNotVisible();
void L()
{
if (!IsHidden())
{
}
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_property_with_Not_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsNotVisible => true;
public void M()
{
if ([|!IsNotVisible|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on property 'IsNotVisible', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_property_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsNoActiveCustomer => true;
public void M()
{
if ([|!IsNoActiveCustomer|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on property 'IsNoActiveCustomer', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_normal_property_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsNotVisible => true;
public bool IsHidden => IsNotVisible;
public void M()
{
if (!IsHidden)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_field_with_Not_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool isNotVisible;
public void M()
{
if ([|!isNotVisible|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on field 'isNotVisible', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_field_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool isNoActiveCustomer;
public void M()
{
if ([|!isNoActiveCustomer|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on field 'isNoActiveCustomer', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_normal_field_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool isHidden;
public void M()
{
if (!isHidden)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_parameter_with_Not_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M(bool isNotVisible)
{
if ([|!isNotVisible|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on parameter 'isNotVisible', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_parameter_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M(bool isNoActiveCustomer)
{
if ([|!isNoActiveCustomer|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on parameter 'isNoActiveCustomer', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_normal_parameter_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M(bool isHidden)
{
if (!isHidden)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_variable_with_Not_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M()
{
bool isNotVisible = false;
if ([|!isNotVisible|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on variable 'isNotVisible', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_variable_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M()
{
bool isNoActiveCustomer = false;
if ([|!isNoActiveCustomer|])
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on variable 'isNoActiveCustomer', which has a negation in its name");
}
[Fact]
internal void When_logical_not_operator_is_applied_on_a_normal_variable_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public void M()
{
bool isHidden = false;
if (!isHidden)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void
When_logical_not_operator_is_applied_in_a_field_initializer_on_a_variable_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
public bool IsHidden => [|!IsNotVisible()|];
bool IsNotVisible() => throw null;
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on method 'IsNotVisible', which has a negation in its name");
}
[Fact]
internal void
When_logical_not_operator_is_applied_in_a_constructor_initializer_on_a_variable_with_No_in_its_name_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
class C
{
protected C(bool b)
{
}
}
class D : C
{
public D()
: base([|!IsNotVisible()|])
{
}
static bool IsNotVisible() => throw null;
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"Logical not operator is applied on method 'IsNotVisible', which has a negation in its name");
}
protected override DiagnosticAnalyzer CreateAnalyzer()
{
return new AvoidConditionWithDoubleNegationAnalyzer();
}
}
}
| |
//
// 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.
//
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.HDInsight.Job.Models;
namespace Microsoft.Azure.Management.HDInsight.Job
{
/// <summary>
/// Operations for managing jobs against HDInsight clusters.
/// </summary>
public partial class JobOperationsExtensions
{
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Hive job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitHiveJob(this IJobOperations operations, HiveJobSubmissionParameters parameters)
{
return operations.SubmitHiveJob(new JobSubmissionParameters { Content = parameters.GetJobPostRequestContent() });
}
/// <summary>
/// Submits a MapReduce job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitMapReduceJob(this IJobOperations operations, MapReduceJobSubmissionParameters parameters)
{
return operations.SubmitMapReduceJob(new JobSubmissionParameters { Content = parameters.GetJobPostRequestContent() });
}
/// <summary>
/// Submits a MapReduce streaming job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitMapReduceStreamingJob(this IJobOperations operations, MapReduceStreamingJobSubmissionParameters parameters)
{
return operations.SubmitMapReduceStreamingJob(new JobSubmissionParameters { Content = parameters.GetJobPostRequestContent() });
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Pig job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitPigJob(this IJobOperations operations, PigJobSubmissionParameters parameters)
{
return operations.SubmitPigJob(new JobSubmissionParameters { Content = parameters.GetJobPostRequestContent() });
}
/// <summary>
/// Submits an Sqoop job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Sqoop job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitSqoopJob(this IJobOperations operations, SqoopJobSubmissionParameters parameters)
{
return operations.SubmitSqoopJob(new JobSubmissionParameters { Content = parameters.GetJobPostRequestContent() });
}
/// <summary>
/// Gets the output from the execution of an individual jobDetails.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="storageAccess">
/// Required. The storage account object of type IStorageAccess.
/// </param>
/// <returns>
/// The output of an individual jobDetails by jobId.
/// </returns>
public static Stream GetJobOutput(this IJobOperations operations, string jobId, IStorageAccess storageAccess)
{
return Task.Factory.StartNew(
(object s) =>
((IJobOperations)s).GetJobOutputAsync(jobId, storageAccess), operations,
CancellationToken.None,
TaskCreationOptions.None, TaskScheduler.Default)
.Unwrap()
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets the output from the execution of an individual jobDetails.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="storageAccess">
/// Required. The storage account object of type IStorageAccess.
/// </param>
/// <returns>
/// The output of an individual jobDetails by jobId.
/// </returns>
public static Task<Stream> GetJobOutputAsync(this IJobOperations operations, string jobId,
IStorageAccess storageAccess)
{
return operations.GetJobOutputAsync(jobId, storageAccess, CancellationToken.None);
}
/// <summary>
/// Gets the error logs from the execution of an individual jobDetails.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="storageAccess">
/// Required. The storage account object of type IStorageAccess.
/// </param>
/// <returns>
/// The error logs of an individual jobDetails by jobId.
/// </returns>
public static Stream GetJobErrorLogs(this IJobOperations operations, string jobId,
IStorageAccess storageAccess)
{
return Task.Factory.StartNew(
(object s) =>
((IJobOperations)s).GetJobErrorLogsAsync(jobId, storageAccess), operations,
CancellationToken.None,
TaskCreationOptions.None, TaskScheduler.Default)
.Unwrap()
.GetAwaiter()
.GetResult();
}
/// <summary>
/// Gets the error logs from the execution of an individual jobDetails.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name="jobId">
/// Required. The id of the job.
/// </param>
/// <param name="storageAccess">
/// Required. The storage account object of type IStorageAccess.
/// </param>
/// <returns>
/// The error logs of an individual jobDetails by jobId.
/// </returns>
public static Task<Stream> GetJobErrorLogsAsync(this IJobOperations operations, string jobId,
IStorageAccess storageAccess)
{
return operations.GetJobErrorLogsAsync(jobId, storageAccess, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class MeshParser : ParserBase
{
public GameObject go;
private Dictionary<string, GameObject> gos = new Dictionary<string, GameObject>();
private bool _startedParsing = true;
private Vector3[] _vertices;
private Vector2[] _uvs;
private Vector3[] _normals;
private int[] _triangles;
private BoneWeight[] _weights;
private Matrix4x4[] _bindPoses;
private Transform[] _bones;
private BinaryReader br;
private Material mat;
private bool endStream;
private GameObject curGo;
private MeshFilter meshFilter;
private Mesh mesh;
private MeshRenderer mr;
public override bool ProceedParsing()
{
if (this._startedParsing)
{
this.br = new BinaryReader(new MemoryStream(this._data));
this._startedParsing = false;
if (this.br.ReadString() != "model")
{
this.go = new GameObject("EmptyModel");
this.endStream = true;
return true;
}
}
if (this.endStream)
{
return true;
}
string text = this.br.ReadString();
string text2 = text;
switch (text2)
{
case "gameobject":
this.CreateGameObjects();
break;
case "mesh":
this.ParseMesh();
break;
case "vertexs":
this.ParseVertex();
break;
case "uvs":
this.ParseUV();
break;
case "nomals":
this.ParseVertexNormal();
break;
case "triangles":
this.ParseFace();
break;
case "material":
this.ParseMainMaterial();
break;
case "end":
this.endStream = true;
break;
}
return false;
}
private GameObject CreateGameObjects()
{
string name = this.br.ReadString();
string key = this.br.ReadString();
GameObject gameObject = new GameObject();
this.curGo = gameObject;
if (this.go == null)
{
this.go = gameObject;
}
gameObject.name = name;
bool flag = this.br.ReadBoolean();
if (flag)
{
GameObject gameObject2 = this.gos[this.br.ReadString()];
gameObject.transform.parent = gameObject2.transform;
}
Vector3 localPosition = default(Vector3);
localPosition.x = this.br.ReadSingle();
localPosition.y = this.br.ReadSingle();
localPosition.z = this.br.ReadSingle();
Quaternion localRotation = default(Quaternion);
localRotation.x = this.br.ReadSingle();
localRotation.y = this.br.ReadSingle();
localRotation.z = this.br.ReadSingle();
localRotation.w = this.br.ReadSingle();
Vector3 localScale = default(Vector3);
localScale.x = this.br.ReadSingle();
localScale.y = this.br.ReadSingle();
localScale.z = this.br.ReadSingle();
gameObject.transform.localPosition = localPosition;
gameObject.transform.localRotation = localRotation;
gameObject.transform.localScale = localScale;
this.gos.Add(key, gameObject);
return gameObject;
}
public void ParseMesh()
{
this.meshFilter = this.curGo.AddComponent<MeshFilter>();
this.mesh = new Mesh();
this.meshFilter.sharedMesh = this.mesh;
}
public void ParseVertex()
{
int num = this.br.ReadInt32();
this._vertices = new Vector3[num];
for (int i = 0; i < num; i++)
{
Vector3 vector = default(Vector3);
vector.x = this.br.ReadSingle();
vector.y = this.br.ReadSingle();
vector.z = this.br.ReadSingle();
this._vertices[i] = vector;
}
this.mesh.vertices = this._vertices;
}
public void ParseUV()
{
int num = this.br.ReadInt32();
this._uvs = new Vector2[num];
for (int i = 0; i < num; i++)
{
Vector2 vector = default(Vector2);
vector.x = this.br.ReadSingle();
vector.y = this.br.ReadSingle();
this._uvs[i] = vector;
}
this.mesh.uv = this._uvs;
}
public void ParseVertexNormal()
{
this.br.ReadInt32();
}
public void ParseFace()
{
int num = this.br.ReadInt32();
this._triangles = new int[num];
for (int i = 0; i < num; i++)
{
this._triangles[i] = this.br.ReadInt32();
}
this.mesh.triangles = this._triangles;
}
public void ParseMainMaterial()
{
this.mr = this.curGo.AddComponent<MeshRenderer>();
string name = this.br.ReadString();
string name2 = this.br.ReadString();
Material material = new Material(Shader.Find(name2));
material.name = name;
string text = this.br.ReadString();
if (text == "_TintColor")
{
material.SetColor(text, new Color(this.br.ReadSingle(), this.br.ReadSingle(), this.br.ReadSingle(), this.br.ReadSingle()));
}
else if (text == "_Color")
{
material.SetColor(text, new Color(this.br.ReadSingle(), this.br.ReadSingle(), this.br.ReadSingle(), this.br.ReadSingle()));
}
string path = this.br.ReadString();
Texture2D texture2D = AssetLibrary.Load(path, AssetType.Texture2D, LoadType.Type_Resources).texture2D;
material.mainTexture = texture2D;
this.mr.sharedMaterial = material;
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="NumericPagerField.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing.Design;
using System.Globalization;
using System.Web;
using System.Web.Resources;
using System.Web.UI;
namespace System.Web.UI.WebControls {
public class NumericPagerField : DataPagerField {
private int _startRowIndex;
private int _maximumRows;
private int _totalRowCount;
public NumericPagerField() {
}
[
DefaultValue(5),
Category("Appearance"),
ResourceDescription("NumericPagerField_ButtonCount"),
]
public int ButtonCount {
get {
object o = ViewState["ButtonCount"];
if (o != null) {
return (int)o;
}
return 5;
}
set {
if (value < 1) {
throw new ArgumentOutOfRangeException("value");
}
if (value != ButtonCount) {
ViewState["ButtonCount"] = value;
OnFieldChanged();
}
}
}
/// <devdoc>
/// <para>Indicates the button type for the field.</para>
/// </devdoc>
[
Category("Appearance"),
DefaultValue(ButtonType.Link),
ResourceDescription("NumericPagerField_ButtonType"),
]
public ButtonType ButtonType {
get {
object o = ViewState["ButtonType"];
if (o != null)
return(ButtonType)o;
return ButtonType.Link;
}
set {
if (value < ButtonType.Button || value > ButtonType.Link) {
throw new ArgumentOutOfRangeException("value");
}
if (value != ButtonType) {
ViewState["ButtonType"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
DefaultValue(""),
ResourceDescription("NumericPagerField_CurrentPageLabelCssClass"),
CssClassPropertyAttribute
]
public string CurrentPageLabelCssClass {
get {
object o = ViewState["CurrentPageLabelCssClass"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
if (value != CurrentPageLabelCssClass) {
ViewState["CurrentPageLabelCssClass"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
DefaultValue(""),
Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor)),
ResourceDescription("NumericPagerField_NextPageImageUrl"),
SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings",
Justification = "Required by ASP.NET parser."),
UrlProperty()
]
public string NextPageImageUrl {
get {
object o = ViewState["NextPageImageUrl"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
if (value != NextPageImageUrl) {
ViewState["NextPageImageUrl"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
Localizable(true),
ResourceDefaultValue("NumericPagerField_DefaultNextPageText"),
ResourceDescription("NumericPagerField_NextPageText")
]
public string NextPageText {
get {
object o = ViewState["NextPageText"];
if (o != null) {
return (string)o;
}
return AtlasWeb.NumericPagerField_DefaultNextPageText;
}
set {
if (value != NextPageText) {
ViewState["NextPageText"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
DefaultValue(""),
ResourceDescription("NumericPagerField_NextPreviousButtonCssClass"),
CssClassPropertyAttribute
]
public string NextPreviousButtonCssClass {
get {
object o = ViewState["NextPreviousButtonCssClass"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
if (value != NextPreviousButtonCssClass) {
ViewState["NextPreviousButtonCssClass"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
DefaultValue(""),
ResourceDescription("NumericPagerField_NumericButtonCssClass"),
CssClassPropertyAttribute
]
public string NumericButtonCssClass {
get {
object o = ViewState["NumericButtonCssClass"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
if (value != NumericButtonCssClass) {
ViewState["NumericButtonCssClass"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
DefaultValue(""),
Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor)),
ResourceDescription("NumericPagerField_PreviousPageImageUrl"),
SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings",
Justification = "Required by ASP.NET parser."),
UrlProperty()
]
public string PreviousPageImageUrl {
get {
object o = ViewState["PreviousPageImageUrl"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
if (value != PreviousPageImageUrl) {
ViewState["PreviousPageImageUrl"] = value;
OnFieldChanged();
}
}
}
[
Category("Appearance"),
Localizable(true),
ResourceDefaultValue("NumericPagerField_DefaultPreviousPageText"),
ResourceDescription("NumericPagerField_PreviousPageText")
]
public string PreviousPageText {
get {
object o = ViewState["PreviousPageText"];
if (o != null) {
return (string)o;
}
return AtlasWeb.NumericPagerField_DefaultPreviousPageText;
}
set {
if (value != PreviousPageText) {
ViewState["PreviousPageText"] = value;
OnFieldChanged();
}
}
}
[
DefaultValue(true),
Category("Behavior"),
ResourceDescription("NumericPagerField_RenderNonBreakingSpacesBetweenControls"),
]
public bool RenderNonBreakingSpacesBetweenControls {
get {
object o = ViewState["RenderNonBreakingSpacesBetweenControls"];
if (o != null) {
return (bool)o;
}
return true;
}
set {
if (value != RenderNonBreakingSpacesBetweenControls) {
ViewState["RenderNonBreakingSpacesBetweenControls"] = value;
OnFieldChanged();
}
}
}
[
SuppressMessage("Microsoft.Usage", "CA2204:LiteralsShouldBeSpelledCorrectly", MessageId = "nbsp",
Justification = "Literal is HTML escape sequence."),
SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters",
MessageId = "System.Web.UI.LiteralControl.#ctor(System.String)",
Justification = "Literal is HTML escape sequence.")
]
private void AddNonBreakingSpace(DataPagerFieldItem container) {
if (RenderNonBreakingSpacesBetweenControls) {
container.Controls.Add(new LiteralControl(" "));
}
}
protected override void CopyProperties(DataPagerField newField) {
((NumericPagerField)newField).ButtonCount = ButtonCount;
((NumericPagerField)newField).ButtonType = ButtonType;
((NumericPagerField)newField).CurrentPageLabelCssClass = CurrentPageLabelCssClass;
((NumericPagerField)newField).NextPageImageUrl = NextPageImageUrl;
((NumericPagerField)newField).NextPageText = NextPageText;
((NumericPagerField)newField).NextPreviousButtonCssClass = NextPreviousButtonCssClass;
((NumericPagerField)newField).NumericButtonCssClass = NumericButtonCssClass;
((NumericPagerField)newField).PreviousPageImageUrl = PreviousPageImageUrl;
((NumericPagerField)newField).PreviousPageText = PreviousPageText;
base.CopyProperties(newField);
}
protected override DataPagerField CreateField() {
return new NumericPagerField();
}
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
public override void HandleEvent(CommandEventArgs e) {
if (String.IsNullOrEmpty(DataPager.QueryStringField)) {
int newStartRowIndex = -1;
int currentPageIndex = _startRowIndex / DataPager.PageSize;
int firstButtonIndex = (_startRowIndex / (ButtonCount * DataPager.PageSize)) * ButtonCount;
int lastButtonIndex = firstButtonIndex + ButtonCount - 1;
int lastRecordIndex = ((lastButtonIndex + 1) * DataPager.PageSize) - 1;
if (String.Equals(e.CommandName, DataControlCommands.PreviousPageCommandArgument)) {
newStartRowIndex = (firstButtonIndex - 1) * DataPager.PageSize;
if (newStartRowIndex < 0) {
newStartRowIndex = 0;
}
}
else if (String.Equals(e.CommandName, DataControlCommands.NextPageCommandArgument)) {
newStartRowIndex = lastRecordIndex + 1;
if (newStartRowIndex > _totalRowCount) {
newStartRowIndex = _totalRowCount - DataPager.PageSize;
}
}
else {
int pageIndex = Convert.ToInt32(e.CommandName, CultureInfo.InvariantCulture);
newStartRowIndex = pageIndex * DataPager.PageSize;
}
if (newStartRowIndex != -1) {
DataPager.SetPageProperties(newStartRowIndex, DataPager.PageSize, true);
}
}
}
private Control CreateNumericButton(string buttonText, string commandArgument, string commandName) {
IButtonControl button;
switch (ButtonType) {
case ButtonType.Button:
button = new Button();
break;
case ButtonType.Link:
default:
button = new LinkButton();
break;
}
button.Text = buttonText;
button.CausesValidation = false;
button.CommandName = commandName;
button.CommandArgument = commandArgument;
WebControl webControl = button as WebControl;
if (webControl != null && !String.IsNullOrEmpty(NumericButtonCssClass)) {
webControl.CssClass = NumericButtonCssClass;
}
return button as Control;
}
private HyperLink CreateNumericLink(int pageIndex) {
int pageNumber = pageIndex + 1;
HyperLink link = new HyperLink();
link.Text = pageNumber.ToString(CultureInfo.InvariantCulture);
link.NavigateUrl = GetQueryStringNavigateUrl(pageNumber);
if (!String.IsNullOrEmpty(NumericButtonCssClass)) {
link.CssClass = NumericButtonCssClass;
}
return link;
}
private Control CreateNextPrevButton(string buttonText, string commandName, string commandArgument, string imageUrl) {
IButtonControl button;
switch (ButtonType) {
case ButtonType.Link:
button = new LinkButton();
break;
case ButtonType.Button:
button = new Button();
break;
case ButtonType.Image:
default:
button = new ImageButton();
((ImageButton)button).ImageUrl = imageUrl;
((ImageButton)button).AlternateText = HttpUtility.HtmlDecode(buttonText);
break;
}
button.Text = buttonText;
button.CausesValidation = false;
button.CommandName = commandName;
button.CommandArgument = commandArgument;
WebControl webControl = button as WebControl;
if (webControl != null && !String.IsNullOrEmpty(NextPreviousButtonCssClass)) {
webControl.CssClass = NextPreviousButtonCssClass;
}
return button as Control;
}
private HyperLink CreateNextPrevLink(string buttonText, int pageIndex, string imageUrl) {
int pageNumber = pageIndex + 1;
HyperLink link = new HyperLink();
link.Text = buttonText;
link.NavigateUrl = GetQueryStringNavigateUrl(pageNumber);
link.ImageUrl = imageUrl;
if (!String.IsNullOrEmpty(NextPreviousButtonCssClass)) {
link.CssClass = NextPreviousButtonCssClass;
}
return link;
}
public override void CreateDataPagers(DataPagerFieldItem container, int startRowIndex, int maximumRows, int totalRowCount, int fieldIndex) {
_startRowIndex = startRowIndex;
_maximumRows = maximumRows;
_totalRowCount = totalRowCount;
if (String.IsNullOrEmpty(DataPager.QueryStringField)) {
CreateDataPagersForCommand(container, fieldIndex);
}
else {
CreateDataPagersForQueryString(container, fieldIndex);
}
}
private void CreateDataPagersForCommand(DataPagerFieldItem container, int fieldIndex) {
int currentPageIndex = _startRowIndex / _maximumRows;
int firstButtonIndex = (_startRowIndex / (ButtonCount * _maximumRows)) * ButtonCount;
int lastButtonIndex = firstButtonIndex + ButtonCount - 1;
int lastRecordIndex = ((lastButtonIndex + 1) * _maximumRows) - 1;
if (firstButtonIndex != 0) {
container.Controls.Add(CreateNextPrevButton(PreviousPageText, DataControlCommands.PreviousPageCommandArgument, fieldIndex.ToString(CultureInfo.InvariantCulture), PreviousPageImageUrl));
AddNonBreakingSpace(container);
}
for (int i = 0; i < ButtonCount && _totalRowCount > ((i + firstButtonIndex) * _maximumRows); i++) {
if (i + firstButtonIndex == currentPageIndex) {
Label pageNumber = new Label();
pageNumber.Text = (i + firstButtonIndex + 1).ToString(CultureInfo.InvariantCulture);
if (!String.IsNullOrEmpty(CurrentPageLabelCssClass)) {
pageNumber.CssClass = CurrentPageLabelCssClass;
}
container.Controls.Add(pageNumber);
}
else {
container.Controls.Add(CreateNumericButton((i + firstButtonIndex + 1).ToString(CultureInfo.InvariantCulture), fieldIndex.ToString(CultureInfo.InvariantCulture), (i + firstButtonIndex).ToString(CultureInfo.InvariantCulture)));
}
AddNonBreakingSpace(container);
}
if (lastRecordIndex < _totalRowCount - 1) {
AddNonBreakingSpace(container);
container.Controls.Add(CreateNextPrevButton(NextPageText, DataControlCommands.NextPageCommandArgument, fieldIndex.ToString(CultureInfo.InvariantCulture), NextPageImageUrl));
AddNonBreakingSpace(container);
}
}
private void CreateDataPagersForQueryString(DataPagerFieldItem container, int fieldIndex) {
int currentPageIndex = _startRowIndex / _maximumRows;
QueryStringHandled = true;
int firstButtonIndex = (_startRowIndex / (ButtonCount * _maximumRows)) * ButtonCount;
int lastButtonIndex = firstButtonIndex + ButtonCount - 1;
int lastRecordIndex = ((lastButtonIndex + 1) * _maximumRows) - 1;
if (firstButtonIndex != 0) {
container.Controls.Add(CreateNextPrevLink(PreviousPageText, firstButtonIndex - 1, PreviousPageImageUrl));
AddNonBreakingSpace(container);
}
for (int i = 0; i < ButtonCount && _totalRowCount > ((i + firstButtonIndex) * _maximumRows); i++) {
if (i + firstButtonIndex == currentPageIndex) {
Label pageNumber = new Label();
pageNumber.Text = (i + firstButtonIndex + 1).ToString(CultureInfo.InvariantCulture);
if (!String.IsNullOrEmpty(CurrentPageLabelCssClass)) {
pageNumber.CssClass = CurrentPageLabelCssClass;
}
container.Controls.Add(pageNumber);
}
else {
container.Controls.Add(CreateNumericLink(i + firstButtonIndex));
}
AddNonBreakingSpace(container);
}
if (lastRecordIndex < _totalRowCount - 1) {
AddNonBreakingSpace(container);
container.Controls.Add(CreateNextPrevLink(NextPageText, firstButtonIndex + ButtonCount, NextPageImageUrl));
AddNonBreakingSpace(container);
}
}
// Required for design-time support (DesignerPagerStyle)
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
public override bool Equals(object o) {
NumericPagerField field = o as NumericPagerField;
if (field != null) {
if (String.Equals(field.ButtonCount, this.ButtonCount) &&
field.ButtonType == this.ButtonType &&
String.Equals(field.CurrentPageLabelCssClass, this.CurrentPageLabelCssClass) &&
String.Equals(field.NextPageImageUrl, this.NextPageImageUrl) &&
String.Equals(field.NextPageText, this.NextPageText) &&
String.Equals(field.NextPreviousButtonCssClass, this.NextPreviousButtonCssClass) &&
String.Equals(field.NumericButtonCssClass, this.NumericButtonCssClass) &&
String.Equals(field.PreviousPageImageUrl, this.PreviousPageImageUrl) &&
String.Equals(field.PreviousPageText, this.PreviousPageText)) {
return true;
}
}
return false;
}
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
public override int GetHashCode() {
return
this.ButtonCount.GetHashCode() |
this.ButtonType.GetHashCode() |
this.CurrentPageLabelCssClass.GetHashCode() |
this.NextPageImageUrl.GetHashCode() |
this.NextPageText.GetHashCode() |
this.NextPreviousButtonCssClass.GetHashCode() |
this.NumericButtonCssClass.GetHashCode() |
this.PreviousPageImageUrl.GetHashCode() |
this.PreviousPageText.GetHashCode();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using BTDB.Buffer;
using BTDB.Collections;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
using Extensions = BTDB.FieldHandler.Extensions;
namespace BTDB.ODBLayer;
delegate void RelationLoader(IInternalObjectDBTransaction transaction, ref SpanReader reader, object value);
delegate object RelationLoaderFunc(IInternalObjectDBTransaction transaction, ref SpanReader reader);
delegate void RelationSaver(IInternalObjectDBTransaction transaction, ref SpanWriter writer, object value);
public class RelationInfo
{
public readonly uint _id;
public readonly string _name;
readonly IRelationInfoResolver _relationInfoResolver;
public readonly Type _interfaceType;
public readonly Type _clientType;
readonly object _defaultClientObject;
RelationVersionInfo?[] _relationVersions = Array.Empty<RelationVersionInfo?>();
RelationSaver _primaryKeysSaver;
RelationSaver _valueSaver;
internal StructList<ItemLoaderInfo> ItemLoaderInfos;
public class ItemLoaderInfo
{
readonly RelationInfo _owner;
readonly Type _itemType;
public ItemLoaderInfo(RelationInfo owner, Type itemType)
{
_owner = owner;
_itemType = itemType;
_valueLoaders = new RelationLoader?[_owner._relationVersions.Length];
_primaryKeysLoader = CreatePkLoader(itemType, _owner.ClientRelationVersionInfo.PrimaryKeyFields.Span,
$"RelationKeyLoader_{_owner.Name}_{itemType.ToSimpleName()}", out _primaryKeyIsEnough);
}
internal object CreateInstance(IInternalObjectDBTransaction tr, in ReadOnlySpan<byte> keyBytes)
{
var reader = new SpanReader(keyBytes);
reader.SkipInt8(); // 3
reader.SkipVUInt64(); // RelationId
var obj = _primaryKeysLoader(tr, ref reader);
if (_primaryKeyIsEnough) return obj;
var valueBytes = tr.KeyValueDBTransaction.GetValue();
reader = new(valueBytes);
var version = reader.ReadVUInt32();
GetValueLoader(version)(tr, ref reader, obj);
return obj;
}
internal readonly RelationLoaderFunc _primaryKeysLoader;
internal readonly bool _primaryKeyIsEnough;
readonly RelationLoader?[] _valueLoaders;
internal RelationLoader GetValueLoader(uint version)
{
RelationLoader? res;
do
{
res = _valueLoaders[version];
if (res != null) return res;
res = CreateLoader(_itemType,
_owner._relationVersions[version]!.Fields.Span,
$"RelationValueLoader_{_owner.Name}_{version}_{_itemType.ToSimpleName()}");
} while (Interlocked.CompareExchange(ref _valueLoaders[version], res, null) != null);
return res;
}
RelationLoaderFunc CreatePkLoader(Type instanceType, ReadOnlySpan<TableFieldInfo> fields, string loaderName,
out bool primaryKeyIsEnough)
{
var thatType = typeof(Func<>).MakeGenericType(instanceType);
var method = ILBuilder.Instance.NewMethod(
loaderName, typeof(RelationLoaderFunc), typeof(Func<object>));
var ilGenerator = method.Generator;
var container = _owner._relationInfoResolver.Container;
object that = null;
if (container != null)
{
that = container.ResolveOptional(thatType);
}
ilGenerator.DeclareLocal(instanceType);
if (that == null)
{
var defaultConstructor = instanceType.GetDefaultConstructor();
if (defaultConstructor == null)
{
ilGenerator
.Ldtoken(instanceType)
.Call(() => Type.GetTypeFromHandle(new()))
.Call(() => RuntimeHelpers.GetUninitializedObject(null));
}
else
{
ilGenerator
.Newobj(defaultConstructor);
}
}
else
{
ilGenerator
.Ldarg(0)
.Callvirt(thatType.GetMethod(nameof(Func<object>.Invoke))!);
}
ilGenerator
.Stloc(0);
var loadInstructions = new StructList<(IFieldHandler, Action<IILGen>?, MethodInfo?)>();
var props = instanceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance).Where(pi =>
pi.GetCustomAttribute<NotStoredAttribute>(true) == null &&
pi.GetIndexParameters().Length == 0).ToList();
var usedFields = 0;
foreach (var srcFieldInfo in fields)
{
var fieldInfo = props.FirstOrDefault(p => GetPersistentName(p) == srcFieldInfo.Name);
if (fieldInfo != null)
{
usedFields++;
var setterMethod = fieldInfo.GetAnySetMethod();
var fieldType = setterMethod!.GetParameters()[0].ParameterType;
var specializedSrcHandler =
srcFieldInfo.Handler!.SpecializeLoadForType(fieldType, null,
_owner._relationInfoResolver.FieldHandlerLogger);
var willLoad = specializedSrcHandler.HandledType();
var converterGenerator =
_owner._relationInfoResolver.TypeConvertorGenerator
.GenerateConversion(willLoad!, fieldType);
if (converterGenerator != null)
{
loadInstructions.Add((specializedSrcHandler, converterGenerator, setterMethod));
continue;
}
}
loadInstructions.Add((srcFieldInfo.Handler!, null, null));
}
primaryKeyIsEnough = props.Count == usedFields;
// Remove useless skips from end
while (loadInstructions.Count > 0 && loadInstructions.Last.Item2 == null)
{
loadInstructions.RemoveAt(^1);
}
var anyNeedsCtx = false;
for (var i = 0; i < loadInstructions.Count; i++)
{
if (!loadInstructions[i].Item1.NeedsCtx()) continue;
anyNeedsCtx = true;
break;
}
if (anyNeedsCtx)
{
ilGenerator.DeclareLocal(typeof(IReaderCtx));
ilGenerator
.Ldarg(1)
.Newobj(() => new DBReaderCtx(null))
.Stloc(1);
}
for (var i = 0; i < loadInstructions.Count; i++)
{
ref var loadInstruction = ref loadInstructions[i];
var readerOrCtx = loadInstruction.Item1.NeedsCtx() ? (Action<IILGen>?)(il => il.Ldloc(1)) : null;
if (loadInstruction.Item2 != null)
{
ilGenerator.Ldloc(0);
loadInstruction.Item1.Load(ilGenerator, il => il.Ldarg(2), readerOrCtx);
loadInstruction.Item2(ilGenerator);
ilGenerator.Call(loadInstruction.Item3!);
continue;
}
loadInstruction.Item1.Skip(ilGenerator, il => il.Ldarg(2), readerOrCtx);
}
ilGenerator.Ldloc(0).Ret();
return (RelationLoaderFunc)method.Create(that);
}
RelationLoader CreateLoader(Type instanceType,
ReadOnlySpan<TableFieldInfo> fields, string loaderName)
{
var method = ILBuilder.Instance.NewMethod<RelationLoader>(loaderName);
var ilGenerator = method.Generator;
ilGenerator.DeclareLocal(instanceType);
ilGenerator
.Ldarg(2)
.Castclass(instanceType)
.Stloc(0);
var instanceTableFieldInfos = new StructList<TableFieldInfo>();
var loadInstructions = new StructList<(IFieldHandler, Action<IILGen>?, MethodInfo?, bool Init, Type ToType)>();
var props = instanceType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance);
var persistentNameToPropertyInfo = new RefDictionary<string, PropertyInfo>();
var publicFields = instanceType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (var field in publicFields)
{
if (field.GetCustomAttribute<NotStoredAttribute>(true) != null) continue;
throw new BTDBException(
$"Public field {instanceType.ToSimpleName()}.{field.Name} must have NotStoredAttribute. It is just intermittent, until they can start to be supported.");
}
foreach (var pi in props)
{
if (pi.GetCustomAttributes(typeof(NotStoredAttribute), true).Length != 0) continue;
if (pi.GetIndexParameters().Length != 0) continue;
var tfi = TableFieldInfo.Build(_owner.Name, pi, _owner._relationInfoResolver.FieldHandlerFactory,
FieldHandlerOptions.None);
instanceTableFieldInfos.Add(tfi);
persistentNameToPropertyInfo.GetOrAddValueRef(tfi.Name) = pi;
}
foreach (var srcFieldInfo in fields)
{
var fieldInfo = persistentNameToPropertyInfo.GetOrFakeValueRef(srcFieldInfo.Name);
if (fieldInfo != null)
{
var setterMethod = fieldInfo.GetAnySetMethod();
var fieldType = setterMethod!.GetParameters()[0].ParameterType;
var specializedSrcHandler =
srcFieldInfo.Handler!.SpecializeLoadForType(fieldType, null,
_owner._relationInfoResolver.FieldHandlerLogger);
var willLoad = specializedSrcHandler.HandledType();
var converterGenerator =
_owner._relationInfoResolver.TypeConvertorGenerator
.GenerateConversion(willLoad!, fieldType);
if (converterGenerator != null)
{
for (var i = 0; i < instanceTableFieldInfos.Count; i++)
{
if (instanceTableFieldInfos[i].Name != srcFieldInfo.Name) continue;
instanceTableFieldInfos.RemoveAt(i);
break;
}
loadInstructions.Add((specializedSrcHandler, converterGenerator, setterMethod, false, fieldType));
continue;
}
}
loadInstructions.Add((srcFieldInfo.Handler!, null, null, false, null));
}
// Remove useless skips from end
while (loadInstructions.Count > 0 && loadInstructions.Last.Item2 == null)
{
loadInstructions.RemoveAt(^1);
}
foreach (var srcFieldInfo in instanceTableFieldInfos)
{
var iFieldHandlerWithInit = srcFieldInfo.Handler as IFieldHandlerWithInit;
if (iFieldHandlerWithInit == null) continue;
var specializedSrcHandler = srcFieldInfo.Handler;
var willLoad = specializedSrcHandler.HandledType();
var fieldInfo = persistentNameToPropertyInfo.GetOrFakeValueRef(srcFieldInfo.Name);
var setterMethod = fieldInfo.GetAnySetMethod();
var toType = setterMethod!.GetParameters()[0].ParameterType;
var converterGenerator =
_owner._relationInfoResolver.TypeConvertorGenerator.GenerateConversion(willLoad!,
toType);
if (converterGenerator == null) continue;
if (!iFieldHandlerWithInit.NeedInit()) continue;
loadInstructions.Add((specializedSrcHandler, converterGenerator, setterMethod, true, toType));
}
var anyNeedsCtx = false;
for (var i = 0; i < loadInstructions.Count; i++)
{
if (!loadInstructions[i].Item1.NeedsCtx()) continue;
anyNeedsCtx = true;
break;
}
if (anyNeedsCtx)
{
ilGenerator.DeclareLocal(typeof(IReaderCtx));
ilGenerator
.Ldarg(0)
.Newobj(() => new DBReaderCtx(null))
.Stloc(1);
}
for (var i = 0; i < loadInstructions.Count; i++)
{
ref var loadInstruction = ref loadInstructions[i];
var readerOrCtx = loadInstruction.Item1.NeedsCtx() ? (Action<IILGen>?)(il => il.Ldloc(1)) : null;
if (loadInstruction.Item2 != null)
{
var loc = ilGenerator.DeclareLocal(loadInstruction.ToType);
if (loadInstruction.Init)
{
((IFieldHandlerWithInit)loadInstruction.Item1).Init(ilGenerator, readerOrCtx);
}
else
{
loadInstruction.Item1.Load(ilGenerator, il => il.Ldarg(1), readerOrCtx);
}
loadInstruction.Item2(ilGenerator);
ilGenerator
.Stloc(loc)
.Ldloc(0)
.Ldloc(loc)
.Call(loadInstruction.Item3!);
continue;
}
loadInstruction.Item1.Skip(ilGenerator, il => il.Ldarg(1), readerOrCtx);
}
ilGenerator.Ret();
return method.Create();
}
}
FreeContentFun?[] _valueIDictFinders = Array.Empty<FreeContentFun?>();
RelationSaver[] _secondaryKeysSavers; //secondary key idx => sk key saver
internal delegate void SecondaryKeyConvertSaver(IInternalObjectDBTransaction tr, ref SpanWriter writer,
ref SpanReader keyReader, ref SpanReader valueReader, object emptyValue);
readonly ConcurrentDictionary<ulong, SecondaryKeyConvertSaver> _secondaryKeysConvertSavers = new();
public delegate void SecondaryKeyValueToPKLoader(ref SpanReader readerKey, ref SpanWriter writer);
readonly ConcurrentDictionary<ulong, SecondaryKeyValueToPKLoader> _secondaryKeyValueToPKLoader = new();
public readonly struct SimpleLoaderType : IEquatable<SimpleLoaderType>
{
public IFieldHandler FieldHandler { get; }
public Type RealType { get; }
public SimpleLoaderType(IFieldHandler fieldHandler, Type realType)
{
FieldHandler = fieldHandler;
RealType = realType;
}
public bool Equals(SimpleLoaderType other)
{
return FieldHandler == other.FieldHandler && RealType == other.RealType;
}
}
readonly
ConcurrentDictionary<SimpleLoaderType, object> //object is of type Action<AbstractBufferedReader, IReaderCtx, (object or value type same as in conc. dic. key)>
_simpleLoader = new ConcurrentDictionary<SimpleLoaderType, object>();
internal readonly List<ulong> FreeContentOldDict = new List<ulong>();
internal readonly List<ulong> FreeContentNewDict = new List<ulong>();
internal byte[] Prefix;
internal byte[] PrefixSecondary;
bool? _needImplementFreeContent;
internal byte[]? PrimeSK2Real;
// ReSharper disable once NotNullMemberIsNotInitialized - not true
public RelationInfo(uint id, string name, RelationBuilder builder, IInternalObjectDBTransaction tr)
{
_id = id;
_name = name;
_relationInfoResolver = builder.RelationInfoResolver;
_interfaceType = builder.InterfaceType;
_clientType = builder.ItemType;
_defaultClientObject = builder.PristineItemInstance;
CalculatePrefix();
LoadUnresolvedVersionInfos(tr.KeyValueDBTransaction);
ResolveVersionInfos();
ClientRelationVersionInfo = CreateVersionInfoFromPrime(builder.ClientRelationVersionInfo);
Extensions.RegisterFieldHandlers(ClientRelationVersionInfo.GetAllFields().ToArray().Select(a => a.Handler),
tr.Owner);
foreach (var loadType in builder.LoadTypes)
{
ItemLoaderInfos.Add(new ItemLoaderInfo(this, loadType));
}
if (LastPersistedVersion > 0 &&
RelationVersionInfo.Equal(_relationVersions[LastPersistedVersion]!, ClientRelationVersionInfo))
{
_relationVersions[LastPersistedVersion] = ClientRelationVersionInfo;
ClientTypeVersion = LastPersistedVersion;
CreateCreatorLoadersAndSavers();
CheckSecondaryKeys(tr, ClientRelationVersionInfo);
}
else
{
ClientTypeVersion = LastPersistedVersion + 1;
_relationVersions[ClientTypeVersion] = ClientRelationVersionInfo;
var writerKey = new SpanWriter();
writerKey.WriteByteArrayRaw(ObjectDB.RelationVersionsPrefix);
writerKey.WriteVUInt32(_id);
writerKey.WriteVUInt32(ClientTypeVersion);
var writerValue = new SpanWriter();
ClientRelationVersionInfo.Save(ref writerValue);
tr.KeyValueDBTransaction.CreateOrUpdateKeyValue(writerKey.GetSpan(), writerValue.GetSpan());
CreateCreatorLoadersAndSavers();
if (LastPersistedVersion > 0)
{
CheckThatPrimaryKeyHasNotChanged(tr, name, ClientRelationVersionInfo,
_relationVersions[LastPersistedVersion]!);
UpdateSecondaryKeys(tr, ClientRelationVersionInfo, _relationVersions[LastPersistedVersion]!);
}
}
}
void CheckThatPrimaryKeyHasNotChanged(IInternalObjectDBTransaction tr, string name,
RelationVersionInfo info, RelationVersionInfo previousInfo)
{
var db = tr.Owner;
var pkFields = info.PrimaryKeyFields;
var prevPkFields = previousInfo.PrimaryKeyFields;
if (pkFields.Length != prevPkFields.Length)
{
if (db.ActualOptions.SelfHealing)
{
db.Logger?.ReportIncompatiblePrimaryKey(name, $"{pkFields.Length}!={prevPkFields.Length}");
ClearRelationData(tr, previousInfo);
return;
}
throw new BTDBException(
$"Change of primary key in relation '{name}' is not allowed. Field count {pkFields.Length} != {prevPkFields.Length}.");
}
for (var i = 0; i < pkFields.Length; i++)
{
if (ArePrimaryKeyFieldsCompatible(pkFields.Span[i].Handler!, prevPkFields.Span[i].Handler!)) continue;
db.Logger?.ReportIncompatiblePrimaryKey(name, pkFields.Span[i].Name);
if (db.ActualOptions.SelfHealing)
{
ClearRelationData(tr, previousInfo);
return;
}
throw new BTDBException(
$"Change of primary key in relation '{name}' is not allowed. Field '{pkFields.Span[i].Name}' is not compatible.");
}
}
static bool ArePrimaryKeyFieldsCompatible(IFieldHandler newHandler, IFieldHandler previousHandler)
{
var newHandledType = newHandler.HandledType();
var previousHandledType = previousHandler.HandledType();
if (newHandledType == previousHandledType)
return true;
if (newHandledType!.IsEnum && previousHandledType!.IsEnum)
{
var prevEnumCfg =
new EnumFieldHandler.EnumConfiguration(((EnumFieldHandler)previousHandler).Configuration);
var newEnumCfg = new EnumFieldHandler.EnumConfiguration(((EnumFieldHandler)newHandler).Configuration);
return prevEnumCfg.IsBinaryRepresentationSubsetOf(newEnumCfg);
}
return false;
}
public bool NeedImplementFreeContent()
{
if (!_needImplementFreeContent.HasValue)
{
CalcNeedImplementFreeContent();
}
return _needImplementFreeContent!.Value;
}
void CalcNeedImplementFreeContent()
{
for (var i = 0; i < _relationVersions.Length; i++)
{
if (_relationVersions[i] == null) continue;
GetIDictFinder((uint)i);
if (_needImplementFreeContent.HasValue)
return;
}
_needImplementFreeContent = false;
}
void CheckSecondaryKeys(IInternalObjectDBTransaction tr, RelationVersionInfo info)
{
var count = GetRelationCount(tr);
var secKeysToAdd = new StructList<KeyValuePair<uint, SecondaryKeyInfo>>();
foreach (var sk in info.SecondaryKeys)
{
if (WrongCountInSecondaryKey(tr.KeyValueDBTransaction, count, sk.Key))
{
DeleteSecondaryKey(tr.KeyValueDBTransaction, sk.Key);
secKeysToAdd.Add(sk);
}
}
if (secKeysToAdd.Count > 0)
CalculateSecondaryKey(tr, secKeysToAdd);
}
long GetRelationCount(IInternalObjectDBTransaction tr)
{
return tr.KeyValueDBTransaction.GetKeyValueCount(Prefix);
}
void UpdateSecondaryKeys(IInternalObjectDBTransaction tr, RelationVersionInfo info,
RelationVersionInfo previousInfo)
{
var count = GetRelationCount(tr);
foreach (var prevIdx in previousInfo.SecondaryKeys.Keys)
{
if (!info.SecondaryKeys.ContainsKey(prevIdx))
DeleteSecondaryKey(tr.KeyValueDBTransaction, prevIdx);
}
var secKeysToAdd = new StructList<KeyValuePair<uint, SecondaryKeyInfo>>();
foreach (var sk in info.SecondaryKeys)
{
if (!previousInfo.SecondaryKeys.ContainsKey(sk.Key))
{
secKeysToAdd.Add(sk);
}
else if (WrongCountInSecondaryKey(tr.KeyValueDBTransaction, count, sk.Key))
{
DeleteSecondaryKey(tr.KeyValueDBTransaction, sk.Key);
secKeysToAdd.Add(sk);
}
}
if (secKeysToAdd.Count > 0)
CalculateSecondaryKey(tr, secKeysToAdd);
}
bool WrongCountInSecondaryKey(IKeyValueDBTransaction tr, long count, uint index)
{
return count != tr.GetKeyValueCount(GetPrefixToSecondaryKey(index));
}
void ClearRelationData(IInternalObjectDBTransaction tr, RelationVersionInfo info)
{
foreach (var prevIdx in info.SecondaryKeys.Keys)
{
DeleteSecondaryKey(tr.KeyValueDBTransaction, prevIdx);
}
var writer = new SpanWriter();
writer.WriteBlock(ObjectDB.AllRelationsPKPrefix);
writer.WriteVUInt32(Id);
tr.KeyValueDBTransaction.EraseAll(writer.GetSpan());
}
void DeleteSecondaryKey(IKeyValueDBTransaction keyValueTr, uint index)
{
keyValueTr.EraseAll(GetPrefixToSecondaryKey(index));
}
ReadOnlySpan<byte> GetPrefixToSecondaryKey(uint index)
{
var writer = new SpanWriter();
writer.WriteBlock(PrefixSecondary);
writer.WriteUInt8((byte)index);
return writer.GetSpan();
}
void CalculateSecondaryKey(IInternalObjectDBTransaction tr,
ReadOnlySpan<KeyValuePair<uint, SecondaryKeyInfo>> indexes)
{
var enumeratorType = typeof(RelationEnumerator<>).MakeGenericType(_clientType);
var enumerator = (IEnumerator)Activator.CreateInstance(enumeratorType, tr, this,
Prefix, new SimpleModificationCounter(), 0);
var keySavers = new RelationSaver[indexes.Length];
for (var i = 0; i < indexes.Length; i++)
{
keySavers[i] = CreateSaver(ClientRelationVersionInfo.GetSecondaryKeyFields(indexes[i].Key),
$"Relation_{Name}_Upgrade_SK_{indexes[i].Value.Name}_KeySaver");
}
var keyWriter = new SpanWriter();
while (enumerator!.MoveNext())
{
var obj = enumerator.Current;
for (var i = 0; i < indexes.Length; i++)
{
keyWriter.WriteBlock(PrefixSecondary);
keyWriter.WriteUInt8((byte)indexes[i].Key);
keySavers[i](tr, ref keyWriter, obj!);
var keyBytes = keyWriter.GetSpan();
if (!tr.KeyValueDBTransaction.CreateOrUpdateKeyValue(keyBytes, new ReadOnlySpan<byte>()))
throw new BTDBException("Internal error, secondary key bytes must be always unique.");
keyWriter.Reset();
}
}
}
[SkipLocalsInit]
void LoadUnresolvedVersionInfos(IKeyValueDBTransaction tr)
{
LastPersistedVersion = 0;
var writer = new SpanWriter();
writer.WriteByteArrayRaw(ObjectDB.RelationVersionsPrefix);
writer.WriteVUInt32(_id);
var prefix = writer.GetSpan();
var relationVersions = new Dictionary<uint, RelationVersionInfo>();
if (tr.FindFirstKey(prefix))
{
Span<byte> keyBuffer = stackalloc byte[16];
do
{
var valueReader = new SpanReader(tr.GetValue());
LastPersistedVersion = (uint)PackUnpack.UnpackVUInt(tr
.GetKey(ref MemoryMarshal.GetReference(keyBuffer), keyBuffer.Length).Slice(prefix.Length));
var relationVersionInfo = RelationVersionInfo.LoadUnresolved(ref valueReader, _name);
relationVersions[LastPersistedVersion] = relationVersionInfo;
} while (tr.FindNextKey(prefix));
}
_relationVersions = new RelationVersionInfo[LastPersistedVersion + 2];
foreach (var (key, value) in relationVersions)
{
_relationVersions[key] = value;
}
_valueIDictFinders = new FreeContentFun?[_relationVersions.Length];
}
void ResolveVersionInfos()
{
foreach (var versionInfo in _relationVersions)
{
versionInfo?.ResolveFieldHandlers(_relationInfoResolver.FieldHandlerFactory);
}
}
internal uint Id => _id;
internal string Name => _name;
internal Type ClientType => _clientType;
internal Type? InterfaceType => _interfaceType;
internal object DefaultClientObject => _defaultClientObject;
internal RelationVersionInfo ClientRelationVersionInfo { get; }
internal uint LastPersistedVersion { get; set; }
internal uint ClientTypeVersion { get; }
void CreateCreatorLoadersAndSavers()
{
_valueSaver = CreateSaver(ClientRelationVersionInfo.Fields.Span, $"RelationValueSaver_{Name}");
_primaryKeysSaver = CreateSaver(ClientRelationVersionInfo.PrimaryKeyFields.Span,
$"RelationKeySaver_{Name}");
if (ClientRelationVersionInfo.SecondaryKeys.Count > 0)
{
_secondaryKeysSavers = new RelationSaver[ClientRelationVersionInfo.SecondaryKeys.Keys.Max() + 1];
foreach (var (idx, secondaryKeyInfo) in ClientRelationVersionInfo.SecondaryKeys)
{
_secondaryKeysSavers[idx] = CreateSaver(
ClientRelationVersionInfo.GetSecondaryKeyFields(idx),
$"Relation_{Name}_SK_{secondaryKeyInfo.Name}_KeySaver");
}
}
}
internal RelationSaver ValueSaver => _valueSaver;
internal RelationSaver PrimaryKeysSaver => _primaryKeysSaver;
void CreateSaverIl(IILGen ilGen, ReadOnlySpan<TableFieldInfo> fields,
Action<IILGen> pushInstance,
Action<IILGen> pushWriter, Action<IILGen> pushTransaction)
{
var writerCtxLocal = CreateWriterCtx(ilGen, fields, pushTransaction);
var props = ClientType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var field in fields)
{
var getter = props.First(p => GetPersistentName(p) == field.Name).GetAnyGetMethod();
var handler = field.Handler!.SpecializeSaveForType(getter!.ReturnType);
handler.Save(ilGen, pushWriter, il => il.Ldloc(writerCtxLocal!), il =>
{
il.Do(pushInstance);
il.Callvirt(getter);
_relationInfoResolver.TypeConvertorGenerator.GenerateConversion(getter.ReturnType,
handler.HandledType()!)!(il);
});
}
}
static IILLocal? CreateWriterCtx(IILGen ilGenerator, ReadOnlySpan<TableFieldInfo> fields,
Action<IILGen> pushTransaction)
{
var anyNeedsCtx = false;
foreach (var field in fields)
{
if (field.Handler!.NeedsCtx())
{
anyNeedsCtx = true;
break;
}
}
IILLocal writerCtxLocal = null;
if (anyNeedsCtx)
{
writerCtxLocal = ilGenerator.DeclareLocal(typeof(IWriterCtx));
ilGenerator
.Do(pushTransaction)
.Newobj(() => new DBWriterCtx(null))
.Stloc(writerCtxLocal);
}
return writerCtxLocal;
}
static void StoreNthArgumentOfTypeIntoLoc(IILGen il, ushort argIdx, Type type, ushort locIdx)
{
il
.Ldarg(argIdx)
.Castclass(type)
.Stloc(locIdx);
}
struct LocalAndHandler
{
public IILLocal Local;
public IFieldHandler Handler;
}
SecondaryKeyConvertSaver CreateBytesToSKSaver(uint version, uint secondaryKeyIndex, string saverName)
{
var method = ILBuilder.Instance.NewMethod<SecondaryKeyConvertSaver>(saverName);
var ilGenerator = method.Generator;
IILLocal defaultObjectLoc = null;
static void PushWriter(IILGen il) => il.Ldarg(1);
var firstBuffer = new BufferInfo(); //pk's
var secondBuffer = new BufferInfo(); //values
var outOfOrderSkParts = new Dictionary<int, LocalAndHandler>(); //local and specialized saver
var pks = ClientRelationVersionInfo.PrimaryKeyFields.Span;
var skFieldIds = ClientRelationVersionInfo.SecondaryKeys[secondaryKeyIndex].Fields;
var skFields = ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex).ToArray();
var valueFields = _relationVersions[version]!.Fields.Span;
var writerCtxLocal = CreateWriterCtx(ilGenerator, skFields, il => il.Ldarg(0));
for (var skFieldIdx = 0; skFieldIdx < skFieldIds.Count; skFieldIdx++)
{
if (outOfOrderSkParts.TryGetValue(skFieldIdx, out var saveLocalInfo))
{
var pushCtx = WriterOrContextForHandler(writerCtxLocal);
saveLocalInfo.Handler.Save(ilGenerator, PushWriter, pushCtx, il => il.Ldloc(saveLocalInfo.Local));
continue;
}
var skf = skFieldIds[skFieldIdx];
if (skf.IsFromPrimaryKey)
{
InitializeBuffer(2, ref firstBuffer, ilGenerator, pks, true);
//firstBuffer.ActualFieldIdx == number of processed PK's
for (var pkIdx = firstBuffer.ActualFieldIdx; pkIdx < skf.Index; pkIdx++)
{
//all PK parts are contained in SK
FindPosition(pkIdx, skFieldIds, out var skFieldIdxForPk);
StoreIntoLocal(ilGenerator, pks[pkIdx].Handler!, firstBuffer, outOfOrderSkParts,
skFieldIdxForPk,
skFields[skFieldIdxForPk].Handler!);
}
CopyToOutput(ilGenerator, pks[(int)skf.Index].Handler!, writerCtxLocal!, PushWriter,
skFields[skFieldIdx].Handler!, firstBuffer);
firstBuffer.ActualFieldIdx = (int)skf.Index + 1;
}
else
{
InitializeBuffer(3, ref secondBuffer, ilGenerator, valueFields, false);
var valueFieldIdx = -1;
for (var i = 0; i < valueFields.Length; i++)
{
if (valueFields[i].Name == skFields[skFieldIdx].Name)
{
valueFieldIdx = i;
break;
}
}
if (valueFieldIdx >= 0)
{
for (var valueIdx = secondBuffer.ActualFieldIdx; valueIdx < valueFieldIdx; valueIdx++)
{
var valueField = valueFields[valueIdx];
var storeForSkIndex = -1;
for (var i = 0; i < skFields.Length; i++)
{
if (skFields[i].Name == valueField.Name)
{
storeForSkIndex = i;
break;
}
}
if (storeForSkIndex == -1)
valueField.Handler!.Skip(ilGenerator, secondBuffer.PushReader, secondBuffer.PushCtx);
else
StoreIntoLocal(ilGenerator, valueField.Handler!, secondBuffer, outOfOrderSkParts,
storeForSkIndex, skFields[storeForSkIndex].Handler!);
}
CopyToOutput(ilGenerator, valueFields[valueFieldIdx].Handler!, writerCtxLocal!, PushWriter,
skFields[skFieldIdx].Handler!, secondBuffer);
secondBuffer.ActualFieldIdx = valueFieldIdx + 1;
}
else
{
//older version of value does not contain sk field - store field from default value (can be initialized in constructor)
if (defaultObjectLoc == null)
{
defaultObjectLoc = ilGenerator.DeclareLocal(ClientType);
ilGenerator.Ldarg(4)
.Castclass(ClientType)
.Stloc(defaultObjectLoc);
}
var loc = defaultObjectLoc;
CreateSaverIl(ilGenerator,
new[] { ClientRelationVersionInfo.GetSecondaryKeyField((int)skf.Index) },
il => il.Ldloc(loc), PushWriter, il => il.Ldarg(0));
}
}
}
ilGenerator.Ret();
return method.Create();
}
static void CopyToOutput(IILGen ilGenerator, IFieldHandler valueHandler, IILLocal writerCtxLocal,
Action<IILGen> pushWriter,
IFieldHandler skHandler, BufferInfo buffer)
{
var pushCtx = WriterOrContextForHandler(writerCtxLocal);
skHandler.SpecializeSaveForType(valueHandler.HandledType()!).Save(ilGenerator, pushWriter, pushCtx,
il => { valueHandler.Load(ilGenerator, buffer.PushReader, buffer.PushCtx); });
}
static void StoreIntoLocal(IILGen ilGenerator, IFieldHandler valueHandler, BufferInfo bufferInfo,
Dictionary<int, LocalAndHandler> outOfOrderSkParts, int skFieldIdx, IFieldHandler skFieldHandler)
{
var local = ilGenerator.DeclareLocal(valueHandler.HandledType()!);
valueHandler.Load(ilGenerator, bufferInfo.PushReader, bufferInfo.PushCtx);
ilGenerator.Stloc(local);
outOfOrderSkParts[skFieldIdx] = new LocalAndHandler
{
Handler = skFieldHandler.SpecializeSaveForType(valueHandler.HandledType()!),
Local = local
};
}
static Action<IILGen> WriterOrContextForHandler(IILLocal? writerCtxLocal)
{
return il => il.Ldloc(writerCtxLocal!);
}
static void InitializeBuffer(ushort bufferArgIdx, ref BufferInfo bufferInfo, IILGen ilGenerator,
ReadOnlySpan<TableFieldInfo> fields, bool skipAllRelationsPKPrefix)
{
if (bufferInfo.ReaderCreated) return;
bufferInfo.ReaderCreated = true;
bufferInfo.PushReader = il => il.Ldarg(bufferArgIdx);
if (skipAllRelationsPKPrefix)
ilGenerator
.Do(bufferInfo.PushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipInt8))!); //ObjectDB.AllRelationsPKPrefix
ilGenerator
.Do(bufferInfo.PushReader).Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipVUInt64))!);
var anyNeedsCtx = false;
foreach (var fieldInfo in fields)
{
if (fieldInfo.Handler!.NeedsCtx())
{
anyNeedsCtx = true;
break;
}
}
if (anyNeedsCtx)
{
var readerCtxLocal = ilGenerator.DeclareLocal(typeof(IReaderCtx));
ilGenerator
.Ldarg(0) // tr
.Newobj(() => new DBReaderCtx(null))
.Stloc(readerCtxLocal);
bufferInfo.PushCtx = il => il.Ldloc(readerCtxLocal);
}
}
RelationSaver CreateSaver(ReadOnlySpan<TableFieldInfo> fields, string saverName)
{
var method = ILBuilder.Instance.NewMethod<RelationSaver>(saverName);
var ilGenerator = method.Generator;
ilGenerator.DeclareLocal(ClientType);
StoreNthArgumentOfTypeIntoLoc(ilGenerator, 2, ClientType, 0);
CreateSaverIl(ilGenerator, fields,
il => il.Ldloc(0), il => il.Ldarg(1), il => il.Ldarg(0));
ilGenerator.Ret();
return method.Create();
}
static bool SecondaryIndexHasSameDefinition(ReadOnlySpan<TableFieldInfo> currFields,
ReadOnlySpan<TableFieldInfo> prevFields)
{
if (currFields.Length != prevFields.Length)
return false;
for (var i = 0; i < currFields.Length; i++)
{
if (!TableFieldInfo.Equal(currFields[i], prevFields[i]))
return false;
}
return true;
}
RelationVersionInfo CreateVersionInfoFromPrime(RelationVersionInfo prime)
{
var secondaryKeys = new Dictionary<uint, SecondaryKeyInfo>();
PrimeSK2Real = new byte[prime.SecondaryKeys.Count];
if (LastPersistedVersion > 0)
{
var prevVersion = _relationVersions[LastPersistedVersion];
foreach (var primeSecondaryKey in prime.SecondaryKeys)
{
if (prevVersion!.SecondaryKeysNames.TryGetValue(primeSecondaryKey.Value.Name, out var index))
{
var prevFields = prevVersion.GetSecondaryKeyFields(index);
var currFields = prime.GetSecondaryKeyFields(primeSecondaryKey.Key);
if (SecondaryIndexHasSameDefinition(currFields, prevFields))
goto existing;
}
while (prevVersion.SecondaryKeys.ContainsKey(index) || secondaryKeys.ContainsKey(index))
index++;
existing:
PrimeSK2Real[primeSecondaryKey.Key] = (byte)index;
secondaryKeys.Add(index, primeSecondaryKey.Value);
}
}
else
{
foreach (var primeSecondaryKey in prime.SecondaryKeys)
{
PrimeSK2Real[primeSecondaryKey.Key] = (byte)primeSecondaryKey.Key;
secondaryKeys.Add(primeSecondaryKey.Key, primeSecondaryKey.Value);
}
}
return new RelationVersionInfo(prime.PrimaryKeyFields, secondaryKeys, prime.SecondaryKeyFields,
prime.Fields);
}
static bool IsIgnoredType(Type type)
{
if (type.IsGenericType)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(IReadOnlyCollection<>))
return true;
}
else
{
if (type == typeof(IEnumerable))
return true;
}
return false;
}
public static IEnumerable<MethodInfo> GetMethods(Type interfaceType)
{
if (IsIgnoredType(interfaceType)) yield break;
foreach (var methodInfo in GetAbstractMethods(interfaceType)) yield return methodInfo;
foreach (var iface in interfaceType.GetInterfaces())
{
if (IsIgnoredType(iface)) continue;
foreach (var methodInfo in GetAbstractMethods(iface)) yield return methodInfo;
}
static IEnumerable<MethodInfo> GetAbstractMethods(Type type)
{
return type.GetMethods().Where(x => x.IsAbstract);
}
}
public static IEnumerable<PropertyInfo> GetProperties(Type interfaceType)
{
if (IsIgnoredType(interfaceType)) yield break;
var properties = interfaceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var property in properties)
{
if (property.Name == nameof(IRelation.BtdbInternalNextInChain)) continue;
yield return property;
}
foreach (var iface in interfaceType.GetInterfaces())
{
if (IsIgnoredType(iface)) continue;
var inheritedProperties = iface.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var property in inheritedProperties)
{
if (property.Name == nameof(IRelation.BtdbInternalNextInChain)) continue;
yield return property;
}
}
}
FreeContentFun GetIDictFinder(uint version)
{
FreeContentFun? res;
do
{
res = _valueIDictFinders[version];
if (res != null) return res;
res = CreateIDictFinder(version);
} while (Interlocked.CompareExchange(ref _valueIDictFinders[version], res, null) != null);
return res;
}
internal RelationSaver GetSecondaryKeysKeySaver(uint secondaryKeyIndex)
{
return _secondaryKeysSavers[secondaryKeyIndex];
}
internal SecondaryKeyConvertSaver GetPKValToSKMerger(uint version, uint secondaryKeyIndex)
{
var h = secondaryKeyIndex + version * 10000ul;
return _secondaryKeysConvertSavers.GetOrAdd(h,
(_, ver, secKeyIndex, relationInfo) => CreateBytesToSKSaver(ver, secKeyIndex,
$"Relation_{relationInfo.Name}_PkVal_to_SK_{relationInfo.ClientRelationVersionInfo.SecondaryKeys[secKeyIndex].Name}_v{ver}"),
version, secondaryKeyIndex, this);
}
//takes secondaryKey key and restores primary key bytes
public SecondaryKeyValueToPKLoader GetSKKeyValueToPKMerger(uint secondaryKeyIndex)
{
return _secondaryKeyValueToPKLoader.GetOrAdd(secondaryKeyIndex,
(_, secKeyIndex, relationInfo) => relationInfo.CreatePrimaryKeyFromSKDataMerger(
secKeyIndex,
$"Relation_SK_to_PK_{relationInfo.ClientRelationVersionInfo.SecondaryKeys[secKeyIndex].Name}"),
secondaryKeyIndex, this);
}
struct MemorizedPositionWithLength
{
public IILLocal Pos { get; set; } // IMemorizedPosition
public IILLocal Length { get; set; } // int
}
struct BufferInfo
{
public bool ReaderCreated;
public Action<IILGen> PushReader;
public Action<IILGen> PushCtx;
public int ActualFieldIdx;
}
SecondaryKeyValueToPKLoader CreatePrimaryKeyFromSKDataMerger(uint secondaryKeyIndex, string mergerName)
{
var method = ILBuilder.Instance.NewMethod<SecondaryKeyValueToPKLoader>(mergerName);
var ilGenerator = method.Generator;
void PushWriter(IILGen il) => il.Ldarg(1);
var skFields = ClientRelationVersionInfo.SecondaryKeys[secondaryKeyIndex].Fields;
var memoPositionLoc = ilGenerator.DeclareLocal(typeof(uint));
var bufferInfo = new BufferInfo();
var outOfOrderPKParts =
new Dictionary<int, MemorizedPositionWithLength>(); //index -> bufferIdx, pos, length
var pks = ClientRelationVersionInfo.PrimaryKeyFields.Span;
for (var pkIdx = 0; pkIdx < pks.Length; pkIdx++)
{
if (outOfOrderPKParts.ContainsKey(pkIdx))
{
var memo = outOfOrderPKParts[pkIdx];
CopyFromMemorizedPosition(ilGenerator, bufferInfo.PushReader, PushWriter, memo);
continue;
}
FindPosition(pkIdx, skFields, out var skFieldIdx);
MergerInitializeBufferReader(ilGenerator, ref bufferInfo, ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex));
for (var idx = bufferInfo.ActualFieldIdx; idx < skFieldIdx; idx++)
{
var field = skFields[idx];
if (field.IsFromPrimaryKey)
{
outOfOrderPKParts[(int)field.Index] = SkipWithMemorizing(ilGenerator, bufferInfo.PushReader,
pks[(int)field.Index].Handler!);
}
else
{
var f = ClientRelationVersionInfo.GetSecondaryKeyField((int)field.Index);
f.Handler!.Skip(ilGenerator, bufferInfo.PushReader, bufferInfo.PushCtx);
}
}
var skField = skFields[skFieldIdx];
GenerateCopyFieldFromByteBufferToWriterIl(ilGenerator, pks[(int)skField.Index].Handler!, bufferInfo.PushReader,
PushWriter, memoPositionLoc);
bufferInfo.ActualFieldIdx = skFieldIdx + 1;
}
ilGenerator.Ret();
return method.Create();
}
static void FindPosition(int pkIdx, IList<FieldId> skFields, out int skFieldIdx)
{
for (var i = 0; i < skFields.Count; i++)
{
var field = skFields[i];
if (!field.IsFromPrimaryKey) continue;
if (field.Index != pkIdx) continue;
skFieldIdx = i;
return;
}
throw new BTDBException("Secondary key relation processing error.");
}
void MergerInitializeBufferReader(IILGen ilGenerator, ref BufferInfo bi,
in ReadOnlySpan<TableFieldInfo> tableSecondaryKeyFields)
{
if (bi.ReaderCreated)
return;
bi.ReaderCreated = true;
bi.PushReader = il => il.Ldarg(0);
ilGenerator
//skip all relations
.Do(bi.PushReader).Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipUInt8))!) // ObjectDB.AllRelationsSKPrefix
//skip relation id (it is just 32bit, but 64bit skip is faster)
.Do(bi.PushReader).Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipVUInt64))!)
//skip secondary key index
.Do(bi.PushReader).Call(typeof(SpanReader).GetMethod(nameof(SpanReader.SkipUInt8))!);
var anyNeedsCtx = false;
foreach (var fieldInfo in tableSecondaryKeyFields)
{
if (fieldInfo.Handler!.NeedsCtx())
{
anyNeedsCtx = true;
break;
}
}
if (anyNeedsCtx)
{
var readerCtxLocal = ilGenerator.DeclareLocal(typeof(IReaderCtx));
ilGenerator
.Ldnull() // ctx is needed only for skipping encrypted strings, so it does not need valid transaction
.Newobj(() => new DBReaderCtx(null))
.Stloc(readerCtxLocal);
bi.PushCtx = il => il.Ldloc(readerCtxLocal);
}
}
static MemorizedPositionWithLength SkipWithMemorizing(IILGen ilGenerator, Action<IILGen> pushReader,
IFieldHandler handler)
{
var memoPos = ilGenerator.DeclareLocal(typeof(uint));
var memoLen = ilGenerator.DeclareLocal(typeof(uint));
var position = new MemorizedPositionWithLength
{ Pos = memoPos, Length = memoLen };
MemorizeCurrentPosition(ilGenerator, pushReader, memoPos);
handler.Skip(ilGenerator, pushReader, null);
ilGenerator
.Do(pushReader) //[VR]
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.GetCurrentPositionWithoutController))!) //[posNew(uint)]
.Ldloc(memoPos) //[posNew(uint), posOld(uint)]
.Sub() //[readLen(uint)]
.Stloc(memoLen); //[]
return position;
}
static void CopyFromMemorizedPosition(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushWriter,
MemorizedPositionWithLength memo)
{
ilGenerator
.Do(pushReader) //[reader]
.Ldloc(memo.Pos) //[reader, pos]
.Ldloc(memo.Length) //[reader, pos, readLen]
.Do(pushWriter) //[reader, pos, readLen, writer]
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.CopyAbsoluteToWriter))!); //[]
}
public static void CopyFromPos(IILGen ilGenerator, Action<IILGen> pushReader, IILLocal posLocal, Action<IILGen> pushWriter)
{
ilGenerator
.Do(pushReader) //[reader]
.Ldloc(posLocal) //[reader, pos]
.Do(pushWriter) //[reader, pos, writer]
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.CopyFromPosToWriter))!); //[]
}
public static void MemorizeCurrentPosition(IILGen ilGenerator, Action<IILGen> pushReader, IILLocal memoPositionLoc)
{
ilGenerator
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.GetCurrentPositionWithoutController))!)
.Stloc(memoPositionLoc);
}
void GenerateCopyFieldFromByteBufferToWriterIl(IILGen ilGenerator, IFieldHandler handler,
Action<IILGen> pushReader,
Action<IILGen> pushWriter, IILLocal memoPositionLoc)
{
MemorizeCurrentPosition(ilGenerator, pushReader, memoPositionLoc);
handler.Skip(ilGenerator, pushReader, null);
CopyFromPos(ilGenerator, pushReader, memoPositionLoc, pushWriter);
}
public object GetSimpleLoader(SimpleLoaderType handler)
{
return _simpleLoader.GetOrAdd(handler, CreateSimpleLoader);
}
object CreateSimpleLoader(SimpleLoaderType loaderType)
{
var delegateType = typeof(ReaderFun<>).MakeGenericType(loaderType.RealType);
var dm = ILBuilder.Instance.NewMethod(loaderType.FieldHandler.Name + "SimpleReader", delegateType);
var ilGenerator = dm.Generator;
loaderType.FieldHandler.Load(ilGenerator, il => il.Ldarg(0), il => il.Ldarg(1));
ilGenerator
.Do(_relationInfoResolver.TypeConvertorGenerator.GenerateConversion(
loaderType.FieldHandler.HandledType()!,
loaderType.RealType)!)
.Ret();
return dm.Create();
}
static string GetPersistentName(PropertyInfo p)
{
var a = p.GetCustomAttribute<PersistedNameAttribute>();
return a != null ? a.Name : p.Name;
}
internal static string GetPersistentName(string name, PropertyInfo[] properties)
{
foreach (var prop in properties)
{
if (prop.Name == name)
return GetPersistentName(prop);
}
return name;
}
public void FreeContent(IInternalObjectDBTransaction tr, in ReadOnlySpan<byte> valueBytes)
{
FreeContentOldDict.Clear();
FindUsedObjectsToFree(tr, valueBytes, FreeContentOldDict);
foreach (var dictId in FreeContentOldDict)
{
FreeIDictionary(tr, dictId);
}
}
internal static void FreeIDictionary(IInternalObjectDBTransaction tr, ulong dictId)
{
var len = PackUnpack.LengthVUInt(dictId);
Span<byte> prefix = stackalloc byte[1 + (int)len];
prefix[0] = ObjectDB.AllDictionariesPrefixByte;
PackUnpack.UnsafePackVUInt(ref MemoryMarshal.GetReference(prefix.Slice(1)), dictId, len);
tr.KeyValueDBTransaction.EraseAll(prefix);
}
public void FindUsedObjectsToFree(IInternalObjectDBTransaction tr, in ReadOnlySpan<byte> valueBytes,
IList<ulong> dictionaries)
{
var valueReader = new SpanReader(valueBytes);
var version = valueReader.ReadVUInt32();
GetIDictFinder(version).Invoke(tr, ref valueReader, dictionaries);
}
FreeContentFun CreateIDictFinder(uint version)
{
var method = ILBuilder.Instance.NewMethod<FreeContentFun>($"Relation{Name}_IDictFinder");
var ilGenerator = method.Generator;
var relationVersionInfo = _relationVersions[version];
var needGenerateFreeFor = 0;
var fakeMethod = ILBuilder.Instance.NewMethod<Action>("Relation_fake");
var fakeGenerator = fakeMethod.Generator;
var valueFields = relationVersionInfo!.Fields.ToArray();
for (var i = 0; i < valueFields.Length; i++)
{
var needsFreeContent = valueFields[i].Handler!.FreeContent(fakeGenerator, _ => { }, _ => { });
if (needsFreeContent != NeedsFreeContent.No)
needGenerateFreeFor = i + 1;
}
if (needGenerateFreeFor == 0)
{
return (IInternalObjectDBTransaction a, ref SpanReader b, IList<ulong> c) => { };
}
_needImplementFreeContent = true;
if (relationVersionInfo.NeedsCtx())
{
ilGenerator.DeclareLocal(typeof(IReaderCtx)); //loc 0
ilGenerator
.Ldarg(0)
.Ldarg(2)
.Newobj(() => new DBReaderWithFreeInfoCtx(null, null))
.Stloc(0);
}
for (var i = 0; i < needGenerateFreeFor; i++)
{
valueFields[i].Handler!.FreeContent(ilGenerator, il => il.Ldarg(1), il => il.Ldloc(0));
}
ilGenerator.Ret();
return method.Create();
}
void CalculatePrefix()
{
var len = PackUnpack.LengthVUInt(Id);
var prefix = new byte[1 + len];
prefix[0] = ObjectDB.AllRelationsPKPrefixByte;
PackUnpack.UnsafePackVUInt(ref prefix[1], Id, len);
Prefix = prefix;
prefix = new byte[1 + len];
prefix[0] = ObjectDB.AllRelationsSKPrefixByte;
PackUnpack.UnsafePackVUInt(ref prefix[1], Id, len);
PrefixSecondary = prefix;
}
public override string ToString()
{
return $"{Name} {ClientType} Id:{Id}";
}
}
public class DBReaderWithFreeInfoCtx : DBReaderCtx
{
readonly IList<ulong> _freeDictionaries;
StructList<bool> _seenObjects;
public DBReaderWithFreeInfoCtx(IInternalObjectDBTransaction transaction, IList<ulong> freeDictionaries)
: base(transaction)
{
_freeDictionaries = freeDictionaries;
}
public IList<ulong> DictIds => _freeDictionaries;
public override void RegisterDict(ulong dictId)
{
_freeDictionaries.Add(dictId);
}
public override void FreeContentInNativeObject(ref SpanReader outsideReader)
{
var id = outsideReader.ReadVInt64();
if (id == 0)
{
}
else if (id <= int.MinValue || id > 0)
{
if (!Transaction.KeyValueDBTransaction.FindExactKey(
ObjectDBTransaction.BuildKeyFromOidWithAllObjectsPrefix((ulong)id)))
return;
var reader = new SpanReader(Transaction.KeyValueDBTransaction.GetValue());
var tableId = reader.ReadVUInt32();
var tableInfo = ((ObjectDB)Transaction.Owner).TablesInfo.FindById(tableId);
if (tableInfo == null)
return;
var tableVersion = reader.ReadVUInt32();
var freeContentTuple = tableInfo.GetFreeContent(tableVersion);
if (freeContentTuple.Item1 != NeedsFreeContent.No)
{
freeContentTuple.Item2(Transaction, null, ref reader, _freeDictionaries);
}
}
else
{
var ido = (int)-id - 1;
if (!AlreadyProcessedInstance(ido))
Transaction.FreeContentInNativeObject(ref outsideReader, this);
}
}
bool AlreadyProcessedInstance(int ido)
{
while (_seenObjects.Count <= ido) _seenObjects.Add(false);
var res = _seenObjects[ido];
_seenObjects[ido] = true;
return res;
}
}
class SimpleModificationCounter : IRelationModificationCounter
{
public int ModificationCounter => 0;
public void CheckModifiedDuringEnum(int prevModification)
{
}
public void MarkModification()
{
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
///
/// This is used to register editor extensions and tools.
///
/// There are various callbacks you can overload to hook in your
/// own functionality without changing the core editor code.
///
/// At the moment this is primarily for the World/Mission
/// Editor and the callbacks mostly make sense in that context.
///
/// Example:
///
/// %obj = new ScriptObject()
/// {
/// superclass = "EditorPlugin";
/// class = "RoadEditor";
/// };
///
/// EditorPlugin::register( %obj );
///
/// For an a full example see: tools/roadEditor/main.cs
/// or: tools/riverEditor/main.cs
/// or: tools/decalEditor/main.cs
///
/// It is not intended for the user to overload this method.
/// If you do make sure you call the parent.
function EditorPlugin::onAdd( %this )
{
EditorPluginSet.add( %this );
}
/// Callback when the world editor is first started. It
/// is a good place to insert menus and menu items as well as
/// preparing guis.
function EditorPlugin::onWorldEditorStartup( %this )
{
}
/// Callback when the world editor is about to be totally deleted.
/// At the time of this writing this occurs when the engine is shut down
/// and the editor had been initialized.
function EditorPlugin::onWorldEditorShutdown( %this )
{
}
/// Callback right before the editor is opened.
function EditorPlugin::onEditorWake( %this )
{
}
/// Callback right before the editor is closed.
function EditorPlugin::onEditorSleep( %this )
{
}
/// Callback when the tool is 'activated' by the WorldEditor
/// Push Gui's, stuff like that
function EditorPlugin::onActivated( %this )
{
if(isDemo())
startToolTime(%this.getName());
%this.isActivated = true;
}
/// Callback when the tool is 'deactivated' / closed by the WorldEditor
/// Pop Gui's, stuff like that
function EditorPlugin::onDeactivated( %this )
{
if(isDemo())
endToolTime(%this.getName());
%this.isActivated = false;
}
/// Callback when tab is pressed.
/// Used by the WorldEditor to toggle between inspector/creator, for example.
function EditorPlugin::onToggleToolWindows( %this )
{
}
/// Callback when the edit menu is clicked or prior to handling an accelerator
/// key event mapped to an edit menu item.
/// It is up to the active editor to determine if these actions are
/// appropriate in the current state.
function EditorPlugin::onEditMenuSelect( %this, %editMenu )
{
%editMenu.enableItem( 3, false ); // Cut
%editMenu.enableItem( 4, false ); // Copy
%editMenu.enableItem( 5, false ); // Paste
%editMenu.enableItem( 6, false ); // Delete
%editMenu.enableItem( 8, false ); // Deselect
}
/// If this tool keeps track of changes that necessitate resaving the mission
/// return true in that case.
function EditorPlugin::isDirty( %this )
{
return false;
}
/// This gives tools a chance to clear whatever internal variables keep track of changes
/// since the last save.
function EditorPlugin::clearDirty( %this )
{
}
/// This gives tools chance to save data out when the mission is being saved.
/// This will only be called if the tool says it is dirty.
function EditorPlugin::onSaveMission( %this, %missionFile )
{
}
/// Called when during mission cleanup to notify plugins.
function EditorPlugin::onExitMission( %this )
{
}
/// Called on the active plugin when a SceneObject is selected.
///
/// @param object The object being selected.
function EditorPlugin::onObjectSelected( %this, %object )
{
}
/// Called on the active plugin when a SceneObject is deselected.
///
/// @param object The object being deselected.
function EditorPlugin::onObjectDeselected( %this, %object )
{
}
/// Called on the active plugin when the selection of SceneObjects is cleared.
function EditorPlugin::onSelectionCleared( %this )
{
}
/// Callback when the the delete item of the edit menu is selected or its
/// accelerator is pressed.
function EditorPlugin::handleDelete( %this )
{
warn( "EditorPlugin::handleDelete( " @ %this.getName() @ " )" NL
"Was not implemented in child namespace, yet menu item was enabled." );
}
/// Callback when the the deselect item of the edit menu is selected or its
/// accelerator is pressed.
function EditorPlugin::handleDeselect( %this )
{
warn( "EditorPlugin::handleDeselect( " @ %this.getName() @ " )" NL
"Was not implemented in child namespace, yet menu item was enabled." );
}
/// Callback when the the cut item of the edit menu is selected or its
/// accelerator is pressed.
function EditorPlugin::handleCut( %this )
{
warn( "EditorPlugin::handleCut( " @ %this.getName() @ " )" NL
"Was not implemented in child namespace, yet menu item was enabled." );
}
/// Callback when the the copy item of the edit menu is selected or its
/// accelerator is pressed.
function EditorPlugin::handleCopy( %this )
{
warn( "EditorPlugin::handleCopy( " @ %this.getName() @ " )" NL
"Was not implemented in child namespace, yet menu item was enabled." );
}
/// Callback when the the paste item of the edit menu is selected or its
/// accelerator is pressed.
function EditorPlugin::handlePaste( %this )
{
warn( "EditorPlugin::handlePaste( " @ %this.getName() @ " )" NL
"Was not implemented in child namespace, yet menu item was enabled." );
}
/// Callback when the escape key is pressed.
/// Return true if this tool has handled the key event in a custom way.
/// If false is returned the WorldEditor default behavior is to return
/// to the ObjectEditor.
function EditorPlugin::handleEscape( %this )
{
return false;
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Text-only Readers.
** Subclasses will include StreamReader & StringReader.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO {
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
[Serializable]
[ComVisible(true)]
#if FEATURE_REMOTING
public abstract class TextReader : MarshalByRefObject, IDisposable {
#else // FEATURE_REMOTING
public abstract class TextReader : IDisposable {
#endif // FEATURE_REMOTING
public static readonly TextReader Null = new NullTextReader();
protected TextReader() {}
// Closes this TextReader and releases any system resources associated with the
// TextReader. Following a call to Close, any operations on the TextReader
// may raise exceptions.
//
// This default method is empty, but descendant classes can override the
// method to provide the appropriate functionality.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
Contract.EndContractBlock();
int n = 0;
do {
int ch = Read();
if (ch == -1) break;
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual String ReadToEnd()
{
Contract.Ensures(Contract.Result<String>() != null);
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len=Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock([In, Out] char[] buffer, int index, int count)
{
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
int i, n = 0;
do {
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual String ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true) {
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n') Read();
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0) return sb.ToString();
return null;
}
#region Task based Async APIs
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
var tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, char[], int, int>)state;
return t.Item1.Read(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadBlockAsyncInternal(buffer, index, count);
}
[HostProtection(ExternalThreading=true)]
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
[HostProtection(Synchronization=true)]
public static TextReader Synchronized(TextReader reader)
{
if (reader==null)
throw new ArgumentNullException("reader");
Contract.Ensures(Contract.Result<TextReader>() != null);
Contract.EndContractBlock();
if (reader is SyncTextReader)
return reader;
return new SyncTextReader(reader);
}
[Serializable]
private sealed class NullTextReader : TextReader
{
public NullTextReader(){}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override String ReadLine()
{
return null;
}
}
[Serializable]
internal sealed class SyncTextReader : TextReader
{
internal TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Close()
{
// So that any overriden Close() gets run
_in.Close();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Peek()
{
return _in.Peek();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read()
{
return _in.Read();
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read([In, Out] char[] buffer, int index, int count)
{
return _in.Read(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
return _in.ReadBlock(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadLine()
{
return _in.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadToEnd()
{
return _in.ReadToEnd();
}
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(ReadBlock(buffer, index, count));
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Data;
using System.IO;
using System.Data.ProviderBase;
using System.Data.Common;
using System.Text;
namespace System.Data.SqlClient
{
internal sealed class SqlMetaDataFactory : DbMetaDataFactory
{
private const string _serverVersionNormalized90 = "09.00.0000";
private const string _serverVersionNormalized90782 = "09.00.0782";
private const string _serverVersionNormalized10 = "10.00.0000";
public SqlMetaDataFactory(Stream XMLStream,
string serverVersion,
string serverVersionNormalized) :
base(XMLStream, serverVersion, serverVersionNormalized) { }
private void addUDTsToDataTypesTable(DataTable dataTypesTable, SqlConnection connection, string ServerVersion)
{
const string sqlCommand =
"select " +
"assemblies.name, " +
"types.assembly_class, " +
"ASSEMBLYPROPERTY(assemblies.name, 'VersionMajor') as version_major, " +
"ASSEMBLYPROPERTY(assemblies.name, 'VersionMinor') as version_minor, " +
"ASSEMBLYPROPERTY(assemblies.name, 'VersionBuild') as version_build, " +
"ASSEMBLYPROPERTY(assemblies.name, 'VersionRevision') as version_revision, " +
"ASSEMBLYPROPERTY(assemblies.name, 'CultureInfo') as culture_info, " +
"ASSEMBLYPROPERTY(assemblies.name, 'PublicKey') as public_key, " +
"is_nullable, " +
"is_fixed_length, " +
"max_length " +
"from sys.assemblies as assemblies join sys.assembly_types as types " +
"on assemblies.assembly_id = types.assembly_id ";
// pre 9.0/Yukon servers do not have UDTs
if (0 > string.Compare(ServerVersion, _serverVersionNormalized90, StringComparison.OrdinalIgnoreCase))
{
return;
}
// Execute the SELECT statement
SqlCommand command = connection.CreateCommand();
command.CommandText = sqlCommand;
DataRow newRow = null;
DataColumn providerDbtype = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType];
DataColumn columnSize = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize];
DataColumn isFixedLength = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength];
DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable];
DataColumn isLiteralSupported = dataTypesTable.Columns[DbMetaDataColumnNames.IsLiteralSupported];
DataColumn typeName = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName];
DataColumn isNullable = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable];
if ((providerDbtype == null) ||
(columnSize == null) ||
(isFixedLength == null) ||
(isSearchable == null) ||
(isLiteralSupported == null) ||
(typeName == null) ||
(isNullable == null))
{
throw ADP.InvalidXml();
}
const int columnSizeIndex = 10;
const int isFixedLengthIndex = 9;
const int isNullableIndex = 8;
const int assemblyNameIndex = 0;
const int assemblyClassIndex = 1;
const int versionMajorIndex = 2;
const int versionMinorIndex = 3;
const int versionBuildIndex = 4;
const int versionRevisionIndex = 5;
const int cultureInfoIndex = 6;
const int publicKeyIndex = 7;
using (IDataReader reader = command.ExecuteReader())
{
object[] values = new object[11];
while (reader.Read())
{
reader.GetValues(values);
newRow = dataTypesTable.NewRow();
newRow[providerDbtype] = SqlDbType.Udt;
if (values[columnSizeIndex] != DBNull.Value)
{
newRow[columnSize] = values[columnSizeIndex];
}
if (values[isFixedLengthIndex] != DBNull.Value)
{
newRow[isFixedLength] = values[isFixedLengthIndex];
}
newRow[isSearchable] = true;
newRow[isLiteralSupported] = false;
if (values[isNullableIndex] != DBNull.Value)
{
newRow[isNullable] = values[isNullableIndex];
}
if ((values[assemblyNameIndex] != DBNull.Value) &&
(values[assemblyClassIndex] != DBNull.Value) &&
(values[versionMajorIndex] != DBNull.Value) &&
(values[versionMinorIndex] != DBNull.Value) &&
(values[versionBuildIndex] != DBNull.Value) &&
(values[versionRevisionIndex] != DBNull.Value))
{
StringBuilder nameString = new StringBuilder();
nameString.Append(values[assemblyClassIndex].ToString());
nameString.Append(", ");
nameString.Append(values[assemblyNameIndex].ToString());
nameString.Append(", Version=");
nameString.Append(values[versionMajorIndex].ToString());
nameString.Append(".");
nameString.Append(values[versionMinorIndex].ToString());
nameString.Append(".");
nameString.Append(values[versionBuildIndex].ToString());
nameString.Append(".");
nameString.Append(values[versionRevisionIndex].ToString());
if (values[cultureInfoIndex] != DBNull.Value)
{
nameString.Append(", Culture=");
nameString.Append(values[cultureInfoIndex].ToString());
}
if (values[publicKeyIndex] != DBNull.Value)
{
nameString.Append(", PublicKeyToken=");
StringBuilder resultString = new StringBuilder();
byte[] byteArrayValue = (byte[])values[publicKeyIndex];
foreach (byte b in byteArrayValue)
{
resultString.Append(string.Format((IFormatProvider)null, "{0,-2:x2}", b));
}
nameString.Append(resultString.ToString());
}
newRow[typeName] = nameString.ToString();
dataTypesTable.Rows.Add(newRow);
newRow.AcceptChanges();
} // if assembly name
}//end while
} // end using
}
private void AddTVPsToDataTypesTable(DataTable dataTypesTable, SqlConnection connection, string ServerVersion)
{
const string sqlCommand =
"select " +
"name, " +
"is_nullable, " +
"max_length " +
"from sys.types " +
"where is_table_type = 1";
// TODO: update this check once the server upgrades major version number!!!
// pre 9.0/Yukon servers do not have Table types
if (0 > string.Compare(ServerVersion, _serverVersionNormalized10, StringComparison.OrdinalIgnoreCase))
{
return;
}
// Execute the SELECT statement
SqlCommand command = connection.CreateCommand();
command.CommandText = sqlCommand;
DataRow newRow = null;
DataColumn providerDbtype = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType];
DataColumn columnSize = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize];
DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable];
DataColumn isLiteralSupported = dataTypesTable.Columns[DbMetaDataColumnNames.IsLiteralSupported];
DataColumn typeName = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName];
DataColumn isNullable = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable];
if ((providerDbtype == null) ||
(columnSize == null) ||
(isSearchable == null) ||
(isLiteralSupported == null) ||
(typeName == null) ||
(isNullable == null))
{
throw ADP.InvalidXml();
}
const int columnSizeIndex = 2;
const int isNullableIndex = 1;
const int typeNameIndex = 0;
using (IDataReader reader = command.ExecuteReader())
{
object[] values = new object[11];
while (reader.Read())
{
reader.GetValues(values);
newRow = dataTypesTable.NewRow();
newRow[providerDbtype] = SqlDbType.Structured;
if (values[columnSizeIndex] != DBNull.Value)
{
newRow[columnSize] = values[columnSizeIndex];
}
newRow[isSearchable] = false;
newRow[isLiteralSupported] = false;
if (values[isNullableIndex] != DBNull.Value)
{
newRow[isNullable] = values[isNullableIndex];
}
if (values[typeNameIndex] != DBNull.Value)
{
newRow[typeName] = values[typeNameIndex];
dataTypesTable.Rows.Add(newRow);
newRow.AcceptChanges();
} // if type name
}//end while
} // end using
}
private DataTable GetDataTypesTable(SqlConnection connection)
{
// verify the existance of the table in the data set
DataTable dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes];
if (dataTypesTable == null)
{
throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes);
}
// copy the table filtering out any rows that don't apply to tho current version of the prrovider
dataTypesTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataTypes, null);
addUDTsToDataTypesTable(dataTypesTable, connection, ServerVersionNormalized);
AddTVPsToDataTypesTable(dataTypesTable, connection, ServerVersionNormalized);
dataTypesTable.AcceptChanges();
return dataTypesTable;
}
protected override DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection)
{
SqlConnection sqlConnection = (SqlConnection)connection;
DataTable resultTable = null;
if (collectionName == DbMetaDataCollectionNames.DataTypes)
{
if (ADP.IsEmptyArray(restrictions) == false)
{
throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.DataTypes);
}
resultTable = GetDataTypesTable(sqlConnection);
}
if (resultTable == null)
{
throw ADP.UnableToBuildCollection(collectionName);
}
return resultTable;
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using HETSAPI;
using HETSAPI.Models;
using System.Reflection;
namespace HETSAPI.Test
{
/// <summary>
/// Class for testing the model EquipmentViewModel
/// </summary>
public class EquipmentViewModelModelTests
{
// TODO uncomment below to declare an instance variable for EquipmentViewModel
private EquipmentViewModel instance;
/// <summary>
/// Setup the test.
/// </summary>
public EquipmentViewModelModelTests()
{
instance = new EquipmentViewModel();
}
/// <summary>
/// Test an instance of EquipmentViewModel
/// </summary>
[Fact]
public void EquipmentViewModelInstanceTest()
{
Assert.IsType<EquipmentViewModel>(instance);
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Fact]
public void IdTest()
{
// TODO unit test for the property 'Id'
Assert.True(true);
}
/// <summary>
/// Test the property 'LocalArea'
/// </summary>
[Fact]
public void LocalAreaTest()
{
// TODO unit test for the property 'LocalArea'
Assert.True(true);
}
/// <summary>
/// Test the property 'DistrictEquipmentType'
/// </summary>
[Fact]
public void DistrictEquipmentTypeTest()
{
// TODO unit test for the property 'DistrictEquipmentType'
Assert.True(true);
}
/// <summary>
/// Test the property 'Owner'
/// </summary>
[Fact]
public void OwnerTest()
{
// TODO unit test for the property 'Owner'
Assert.True(true);
}
/// <summary>
/// Test the property 'EquipmentCode'
/// </summary>
[Fact]
public void EquipmentCodeTest()
{
// TODO unit test for the property 'EquipmentCode'
Assert.True(true);
}
/// <summary>
/// Test the property 'Status'
/// </summary>
[Fact]
public void StatusTest()
{
// TODO unit test for the property 'Status'
Assert.True(true);
}
/// <summary>
/// Test the property 'ReceivedDate'
/// </summary>
[Fact]
public void ReceivedDateTest()
{
// TODO unit test for the property 'ReceivedDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'ApprovedDate'
/// </summary>
[Fact]
public void ApprovedDateTest()
{
// TODO unit test for the property 'ApprovedDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'LastVerifiedDate'
/// </summary>
[Fact]
public void LastVerifiedDateTest()
{
// TODO unit test for the property 'LastVerifiedDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'IsInformationUpdateNeeded'
/// </summary>
[Fact]
public void IsInformationUpdateNeededTest()
{
// TODO unit test for the property 'IsInformationUpdateNeeded'
Assert.True(true);
}
/// <summary>
/// Test the property 'InformationUpdateNeededReason'
/// </summary>
[Fact]
public void InformationUpdateNeededReasonTest()
{
// TODO unit test for the property 'InformationUpdateNeededReason'
Assert.True(true);
}
/// <summary>
/// Test the property 'LicencePlate'
/// </summary>
[Fact]
public void LicencePlateTest()
{
// TODO unit test for the property 'LicencePlate'
Assert.True(true);
}
/// <summary>
/// Test the property 'Make'
/// </summary>
[Fact]
public void MakeTest()
{
// TODO unit test for the property 'Make'
Assert.True(true);
}
/// <summary>
/// Test the property 'Model'
/// </summary>
[Fact]
public void ModelTest()
{
// TODO unit test for the property 'Model'
Assert.True(true);
}
/// <summary>
/// Test the property 'Year'
/// </summary>
[Fact]
public void YearTest()
{
// TODO unit test for the property 'Year'
Assert.True(true);
}
/// <summary>
/// Test the property 'Type'
/// </summary>
[Fact]
public void TypeTest()
{
// TODO unit test for the property 'Type'
Assert.True(true);
}
/// <summary>
/// Test the property 'Operator'
/// </summary>
[Fact]
public void OperatorTest()
{
// TODO unit test for the property 'Operator'
Assert.True(true);
}
/// <summary>
/// Test the property 'PayRate'
/// </summary>
[Fact]
public void PayRateTest()
{
// TODO unit test for the property 'PayRate'
Assert.True(true);
}
/// <summary>
/// Test the property 'RefuseRate'
/// </summary>
[Fact]
public void RefuseRateTest()
{
// TODO unit test for the property 'RefuseRate'
Assert.True(true);
}
/// <summary>
/// Test the property 'SerialNumber'
/// </summary>
[Fact]
public void SerialNumberTest()
{
// TODO unit test for the property 'SerialNumber'
Assert.True(true);
}
/// <summary>
/// Test the property 'Size'
/// </summary>
[Fact]
public void SizeTest()
{
// TODO unit test for the property 'Size'
Assert.True(true);
}
/// <summary>
/// Test the property 'ToDate'
/// </summary>
[Fact]
public void ToDateTest()
{
// TODO unit test for the property 'ToDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'BlockNumber'
/// </summary>
[Fact]
public void BlockNumberTest()
{
// TODO unit test for the property 'BlockNumber'
Assert.True(true);
}
/// <summary>
/// Test the property 'Seniority'
/// </summary>
[Fact]
public void SeniorityTest()
{
// TODO unit test for the property 'Seniority'
Assert.True(true);
}
/// <summary>
/// Test the property 'IsSeniorityOverridden'
/// </summary>
[Fact]
public void IsSeniorityOverriddenTest()
{
// TODO unit test for the property 'IsSeniorityOverridden'
Assert.True(true);
}
/// <summary>
/// Test the property 'SeniorityOverrideReason'
/// </summary>
[Fact]
public void SeniorityOverrideReasonTest()
{
// TODO unit test for the property 'SeniorityOverrideReason'
Assert.True(true);
}
/// <summary>
/// Test the property 'SeniorityEffectiveDate'
/// </summary>
[Fact]
public void SeniorityEffectiveDateTest()
{
// TODO unit test for the property 'SeniorityEffectiveDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'YearsOfService'
/// </summary>
[Fact]
public void YearsOfServiceTest()
{
// TODO unit test for the property 'YearsOfService'
Assert.True(true);
}
/// <summary>
/// Test the property 'ServiceHoursLastYear'
/// </summary>
[Fact]
public void ServiceHoursLastYearTest()
{
// TODO unit test for the property 'ServiceHoursLastYear'
Assert.True(true);
}
/// <summary>
/// Test the property 'ServiceHoursTwoYearsAgo'
/// </summary>
[Fact]
public void ServiceHoursTwoYearsAgoTest()
{
// TODO unit test for the property 'ServiceHoursTwoYearsAgo'
Assert.True(true);
}
/// <summary>
/// Test the property 'ServiceHoursThreeYearsAgo'
/// </summary>
[Fact]
public void ServiceHoursThreeYearsAgoTest()
{
// TODO unit test for the property 'ServiceHoursThreeYearsAgo'
Assert.True(true);
}
/// <summary>
/// Test the property 'ArchiveCode'
/// </summary>
[Fact]
public void ArchiveCodeTest()
{
// TODO unit test for the property 'ArchiveCode'
Assert.True(true);
}
/// <summary>
/// Test the property 'ArchiveReason'
/// </summary>
[Fact]
public void ArchiveReasonTest()
{
// TODO unit test for the property 'ArchiveReason'
Assert.True(true);
}
/// <summary>
/// Test the property 'ArchiveDate'
/// </summary>
[Fact]
public void ArchiveDateTest()
{
// TODO unit test for the property 'ArchiveDate'
Assert.True(true);
}
/// <summary>
/// Test the property 'DumpTruck'
/// </summary>
[Fact]
public void DumpTruckTest()
{
// TODO unit test for the property 'DumpTruck'
Assert.True(true);
}
/// <summary>
/// Test the property 'EquipmentAttachments'
/// </summary>
[Fact]
public void EquipmentAttachmentsTest()
{
// TODO unit test for the property 'EquipmentAttachments'
Assert.True(true);
}
/// <summary>
/// Test the property 'Notes'
/// </summary>
[Fact]
public void NotesTest()
{
// TODO unit test for the property 'Notes'
Assert.True(true);
}
/// <summary>
/// Test the property 'Attachments'
/// </summary>
[Fact]
public void AttachmentsTest()
{
// TODO unit test for the property 'Attachments'
Assert.True(true);
}
/// <summary>
/// Test the property 'History'
/// </summary>
[Fact]
public void HistoryTest()
{
// TODO unit test for the property 'History'
Assert.True(true);
}
/// <summary>
/// Test the property 'SeniorityAudit'
/// </summary>
[Fact]
public void SeniorityAuditTest()
{
// TODO unit test for the property 'SeniorityAudit'
Assert.True(true);
}
/// <summary>
/// Test the property 'ServiceHoursThisYear'
/// </summary>
[Fact]
public void ServiceHoursThisYearTest()
{
// TODO unit test for the property 'ServiceHoursThisYear'
Assert.True(true);
}
/// <summary>
/// Test the property 'HasDuplicates'
/// </summary>
[Fact]
public void HasDuplicatesTest()
{
// TODO unit test for the property 'HasDuplicates'
Assert.True(true);
}
/// <summary>
/// Test the property 'DuplicateEquipment'
/// </summary>
[Fact]
public void DuplicateEquipmentTest()
{
// TODO unit test for the property 'DuplicateEquipment'
Assert.True(true);
}
/// <summary>
/// Test the property 'IsWorking'
/// </summary>
[Fact]
public void IsWorkingTest()
{
// TODO unit test for the property 'IsWorking'
Assert.True(true);
}
/// <summary>
/// Test the property 'LastTimeRecordDateThisYear'
/// </summary>
[Fact]
public void LastTimeRecordDateThisYearTest()
{
// TODO unit test for the property 'LastTimeRecordDateThisYear'
Assert.True(true);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: math.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Math {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Math {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Math() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgptYXRoLnByb3RvEgRtYXRoIiwKB0RpdkFyZ3MSEAoIZGl2aWRlbmQYASAB",
"KAMSDwoHZGl2aXNvchgCIAEoAyIvCghEaXZSZXBseRIQCghxdW90aWVudBgB",
"IAEoAxIRCglyZW1haW5kZXIYAiABKAMiGAoHRmliQXJncxINCgVsaW1pdBgB",
"IAEoAyISCgNOdW0SCwoDbnVtGAEgASgDIhkKCEZpYlJlcGx5Eg0KBWNvdW50",
"GAEgASgDMqQBCgRNYXRoEiYKA0RpdhINLm1hdGguRGl2QXJncxoOLm1hdGgu",
"RGl2UmVwbHkiABIuCgdEaXZNYW55Eg0ubWF0aC5EaXZBcmdzGg4ubWF0aC5E",
"aXZSZXBseSIAKAEwARIjCgNGaWISDS5tYXRoLkZpYkFyZ3MaCS5tYXRoLk51",
"bSIAMAESHwoDU3VtEgkubWF0aC5OdW0aCS5tYXRoLk51bSIAKAFiBnByb3Rv",
"Mw=="));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Math.DivArgs), new[]{ "Dividend", "Divisor" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Math.DivReply), new[]{ "Quotient", "Remainder" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Math.FibArgs), new[]{ "Limit" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Math.Num), new[]{ "Num_" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Math.FibReply), new[]{ "Count" }, null, null, null)
}));
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DivArgs : pb::IMessage<DivArgs> {
private static readonly pb::MessageParser<DivArgs> _parser = new pb::MessageParser<DivArgs>(() => new DivArgs());
public static pb::MessageParser<DivArgs> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.Proto.Math.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DivArgs() {
OnConstruction();
}
partial void OnConstruction();
public DivArgs(DivArgs other) : this() {
dividend_ = other.dividend_;
divisor_ = other.divisor_;
}
public DivArgs Clone() {
return new DivArgs(this);
}
public const int DividendFieldNumber = 1;
private long dividend_;
public long Dividend {
get { return dividend_; }
set {
dividend_ = value;
}
}
public const int DivisorFieldNumber = 2;
private long divisor_;
public long Divisor {
get { return divisor_; }
set {
divisor_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as DivArgs);
}
public bool Equals(DivArgs other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Dividend != other.Dividend) return false;
if (Divisor != other.Divisor) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Dividend != 0L) hash ^= Dividend.GetHashCode();
if (Divisor != 0L) hash ^= Divisor.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Dividend != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Dividend);
}
if (Divisor != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Divisor);
}
}
public int CalculateSize() {
int size = 0;
if (Dividend != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Dividend);
}
if (Divisor != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Divisor);
}
return size;
}
public void MergeFrom(DivArgs other) {
if (other == null) {
return;
}
if (other.Dividend != 0L) {
Dividend = other.Dividend;
}
if (other.Divisor != 0L) {
Divisor = other.Divisor;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Dividend = input.ReadInt64();
break;
}
case 16: {
Divisor = input.ReadInt64();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DivReply : pb::IMessage<DivReply> {
private static readonly pb::MessageParser<DivReply> _parser = new pb::MessageParser<DivReply>(() => new DivReply());
public static pb::MessageParser<DivReply> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.Proto.Math.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DivReply() {
OnConstruction();
}
partial void OnConstruction();
public DivReply(DivReply other) : this() {
quotient_ = other.quotient_;
remainder_ = other.remainder_;
}
public DivReply Clone() {
return new DivReply(this);
}
public const int QuotientFieldNumber = 1;
private long quotient_;
public long Quotient {
get { return quotient_; }
set {
quotient_ = value;
}
}
public const int RemainderFieldNumber = 2;
private long remainder_;
public long Remainder {
get { return remainder_; }
set {
remainder_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as DivReply);
}
public bool Equals(DivReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Quotient != other.Quotient) return false;
if (Remainder != other.Remainder) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Quotient != 0L) hash ^= Quotient.GetHashCode();
if (Remainder != 0L) hash ^= Remainder.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Quotient != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Quotient);
}
if (Remainder != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Remainder);
}
}
public int CalculateSize() {
int size = 0;
if (Quotient != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Quotient);
}
if (Remainder != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Remainder);
}
return size;
}
public void MergeFrom(DivReply other) {
if (other == null) {
return;
}
if (other.Quotient != 0L) {
Quotient = other.Quotient;
}
if (other.Remainder != 0L) {
Remainder = other.Remainder;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Quotient = input.ReadInt64();
break;
}
case 16: {
Remainder = input.ReadInt64();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FibArgs : pb::IMessage<FibArgs> {
private static readonly pb::MessageParser<FibArgs> _parser = new pb::MessageParser<FibArgs>(() => new FibArgs());
public static pb::MessageParser<FibArgs> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.Proto.Math.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FibArgs() {
OnConstruction();
}
partial void OnConstruction();
public FibArgs(FibArgs other) : this() {
limit_ = other.limit_;
}
public FibArgs Clone() {
return new FibArgs(this);
}
public const int LimitFieldNumber = 1;
private long limit_;
public long Limit {
get { return limit_; }
set {
limit_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FibArgs);
}
public bool Equals(FibArgs other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Limit != other.Limit) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Limit != 0L) hash ^= Limit.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Limit != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Limit);
}
}
public int CalculateSize() {
int size = 0;
if (Limit != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Limit);
}
return size;
}
public void MergeFrom(FibArgs other) {
if (other == null) {
return;
}
if (other.Limit != 0L) {
Limit = other.Limit;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Limit = input.ReadInt64();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Num : pb::IMessage<Num> {
private static readonly pb::MessageParser<Num> _parser = new pb::MessageParser<Num>(() => new Num());
public static pb::MessageParser<Num> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.Proto.Math.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Num() {
OnConstruction();
}
partial void OnConstruction();
public Num(Num other) : this() {
num_ = other.num_;
}
public Num Clone() {
return new Num(this);
}
public const int Num_FieldNumber = 1;
private long num_;
public long Num_ {
get { return num_; }
set {
num_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Num);
}
public bool Equals(Num other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Num_ != other.Num_) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Num_ != 0L) hash ^= Num_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Num_ != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Num_);
}
}
public int CalculateSize() {
int size = 0;
if (Num_ != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Num_);
}
return size;
}
public void MergeFrom(Num other) {
if (other == null) {
return;
}
if (other.Num_ != 0L) {
Num_ = other.Num_;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Num_ = input.ReadInt64();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FibReply : pb::IMessage<FibReply> {
private static readonly pb::MessageParser<FibReply> _parser = new pb::MessageParser<FibReply>(() => new FibReply());
public static pb::MessageParser<FibReply> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Math.Proto.Math.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FibReply() {
OnConstruction();
}
partial void OnConstruction();
public FibReply(FibReply other) : this() {
count_ = other.count_;
}
public FibReply Clone() {
return new FibReply(this);
}
public const int CountFieldNumber = 1;
private long count_;
public long Count {
get { return count_; }
set {
count_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FibReply);
}
public bool Equals(FibReply other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Count != other.Count) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Count != 0L) hash ^= Count.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Count != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Count);
}
}
public int CalculateSize() {
int size = 0;
if (Count != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count);
}
return size;
}
public void MergeFrom(FibReply other) {
if (other == null) {
return;
}
if (other.Count != 0L) {
Count = other.Count;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Count = input.ReadInt64();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
#endregion Using directives
namespace System.Workflow.Activities
{
[Serializable]
internal class StateMachineExecutionState
{
#region Member Variables
internal const string StateMachineExecutionStateKey = "StateMachineExecutionState";
private StateMachineSubscriptionManager _subscriptionManager;
private Queue<StateMachineAction> _actions;
private string _currentStateName;
private string _previousStateName;
private string _nextStateName;
private bool _completed = false;
private bool _queueLocked = false;
private bool _schedulerBusy = false;
#endregion Member Variables
#region Properties
internal StateMachineSubscriptionManager SubscriptionManager
{
get
{
return _subscriptionManager;
}
}
private Queue<StateMachineAction> Actions
{
get
{
if (_actions == null)
_actions = new Queue<StateMachineAction>();
return _actions;
}
}
internal bool SchedulerBusy
{
get
{
return _schedulerBusy;
}
set
{
_schedulerBusy = value;
}
}
internal string CurrentStateName
{
get
{
return _currentStateName;
}
set
{
_currentStateName = value;
}
}
internal string PreviousStateName
{
get
{
return _previousStateName;
}
set
{
_previousStateName = value;
}
}
internal string NextStateName
{
get
{
return _nextStateName;
}
set
{
_nextStateName = value;
}
}
internal bool Completed
{
get
{
return _completed;
}
set
{
_completed = value;
}
}
internal bool HasEnqueuedActions
{
get
{
return this.Actions.Count > 0;
}
}
#endregion Properties
#region Constructors
internal StateMachineExecutionState(Guid instanceId)
{
_subscriptionManager = new StateMachineSubscriptionManager(this, instanceId);
}
#endregion
internal void LockQueue()
{
_queueLocked = true;
}
internal void EnqueueAction(StateMachineAction action)
{
Debug.Assert(!this._queueLocked);
this.Actions.Enqueue(action);
}
internal StateMachineAction DequeueAction()
{
StateMachineAction action = this.Actions.Dequeue();
if (this.Actions.Count == 0)
_queueLocked = false;
return action;
}
internal void ProcessActions(ActivityExecutionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.SchedulerBusy)
return;
StateActivity state = (StateActivity)context.Activity;
if (this.Actions.Count == 0)
{
this.SubscriptionManager.ProcessQueue(context);
return;
}
StateMachineAction action = this.Actions.Peek();
while (action.StateName.Equals(state.QualifiedName))
{
action = DequeueAction();
action.Execute(context);
// If the previous action just
// requested something to the runtime
// scheduler, then we quit, since
// the scheduler takes precedence.
// we'll pick up the processing of actions
// after the scheduler return the control to us.
if (this.SchedulerBusy)
return;
if (this.Actions.Count == 0)
break;
action = this.Actions.Peek();
}
if (this.Actions.Count > 0)
{
StateActivity rootState = StateMachineHelpers.GetRootState(state);
StateActivity nextActionState = StateMachineHelpers.FindDynamicStateByName(rootState, action.StateName);
if (nextActionState == null)
throw new InvalidOperationException(SR.GetInvalidStateMachineAction(action.StateName));
nextActionState.RaiseProcessActionEvent(context);
}
else
{
this.SubscriptionManager.ProcessQueue(context);
}
}
internal void ProcessTransitionRequest(ActivityExecutionContext context)
{
if (String.IsNullOrEmpty(this.NextStateName))
return;
StateActivity currentState = StateMachineHelpers.GetCurrentState(context);
CalculateStateTransition(currentState, this.NextStateName);
LockQueue();
this.NextStateName = null;
}
internal void CalculateStateTransition(StateActivity currentState, string targetStateName)
{
if (currentState == null)
throw new ArgumentNullException("currentState");
if (String.IsNullOrEmpty(targetStateName))
throw new ArgumentNullException("targetStateName");
while (currentState != null && (currentState.QualifiedName.Equals(targetStateName) || !StateMachineHelpers.ContainsState(currentState, targetStateName)))
{
CloseStateAction action = new CloseStateAction(currentState.QualifiedName);
this.Actions.Enqueue(action);
currentState = currentState.Parent as StateActivity;
}
if (currentState == null)
throw new InvalidOperationException(SR.GetUnableToTransitionToState(targetStateName));
while (!currentState.QualifiedName.Equals(targetStateName))
{
foreach (Activity childActivity in currentState.EnabledActivities)
{
StateActivity childState = childActivity as StateActivity;
if (childState != null)
{
//
if (StateMachineHelpers.ContainsState(childState, targetStateName))
{
ExecuteChildStateAction action = new ExecuteChildStateAction(currentState.QualifiedName, childState.QualifiedName);
this.Actions.Enqueue(action);
currentState = childState;
break;
}
}
}
}
if (!StateMachineHelpers.IsLeafState(currentState))
throw new InvalidOperationException(SR.GetInvalidStateTransitionPath());
}
#region Static Methods
internal static StateMachineExecutionState Get(StateActivity state)
{
Debug.Assert(StateMachineHelpers.IsRootState(state));
StateMachineExecutionState executionState = (StateMachineExecutionState)state.GetValue(StateActivity.StateMachineExecutionStateProperty);
Debug.Assert(executionState != null);
return executionState;
}
#endregion
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Parse.Abstractions.Infrastructure;
using Parse.Abstractions.Platform.Push;
using Parse.Platform.Push;
namespace Parse
{
/// <summary>
/// A utility class for sending and receiving push notifications.
/// </summary>
public partial class ParsePush
{
object Mutex { get; } = new object { };
IPushState State { get; set; }
IServiceHub Services { get; }
#warning Make default(IServiceHub) the default value of serviceHub once all dependents properly inject it.
/// <summary>
/// Creates a push which will target every device. The Data field must be set before calling SendAsync.
/// </summary>
public ParsePush(IServiceHub serviceHub)
{
Services = serviceHub ?? ParseClient.Instance;
State = new MutablePushState { Query = Services.GetInstallationQuery() };
}
#region Properties
/// <summary>
/// An installation query that specifies which installations should receive
/// this push.
/// This should not be used in tandem with Channels.
/// </summary>
public ParseQuery<ParseInstallation> Query
{
get => State.Query;
set => MutateState(state =>
{
if (state.Channels is { } && value is { } && value.GetConstraint("channels") is { })
{
throw new InvalidOperationException("A push may not have both Channels and a Query with a channels constraint.");
}
state.Query = value;
});
}
/// <summary>
/// A short-hand to set a query which only discriminates on the channels to which a device is subscribed.
/// This is shorthand for:
///
/// <code>
/// var push = new Push();
/// push.Query = ParseInstallation.Query.WhereKeyContainedIn("channels", channels);
/// </code>
///
/// This cannot be used in tandem with Query.
/// </summary>
public IEnumerable<string> Channels
{
get => State.Channels;
set => MutateState(state =>
{
if (value is { } && state.Query is { } && state.Query.GetConstraint("channels") is { })
{
throw new InvalidOperationException("A push may not have both Channels and a Query with a channels constraint.");
}
state.Channels = value;
});
}
/// <summary>
/// The time at which this push will expire. This should not be used in tandem with ExpirationInterval.
/// </summary>
public DateTime? Expiration
{
get => State.Expiration;
set => MutateState(state =>
{
if (state.ExpirationInterval is { })
{
throw new InvalidOperationException("Cannot set Expiration after setting ExpirationInterval.");
}
state.Expiration = value;
});
}
/// <summary>
/// The time at which this push will be sent.
/// </summary>
public DateTime? PushTime
{
get => State.PushTime;
set => MutateState(state =>
{
DateTime now = DateTime.Now;
if (value < now || value > now.AddDays(14))
{
throw new InvalidOperationException("Cannot set PushTime in the past or more than two weeks later than now.");
}
state.PushTime = value;
});
}
/// <summary>
/// The time from initial schedul when this push will expire. This should not be used in tandem with Expiration.
/// </summary>
public TimeSpan? ExpirationInterval
{
get => State.ExpirationInterval;
set => MutateState(state =>
{
if (state.Expiration is { })
{
throw new InvalidOperationException("Cannot set ExpirationInterval after setting Expiration.");
}
state.ExpirationInterval = value;
});
}
/// <summary>
/// The contents of this push. Some keys have special meaning. A full list of pre-defined
/// keys can be found in the Parse Push Guide. The following keys affect WinRT devices.
/// Keys which do not start with x-winrt- can be prefixed with x-winrt- to specify an
/// override only sent to winrt devices.
/// alert: the body of the alert text.
/// title: The title of the text.
/// x-winrt-payload: A full XML payload to be sent to WinRT installations instead of
/// the auto-layout.
/// This should not be used in tandem with Alert.
/// </summary>
public IDictionary<string, object> Data
{
get => State.Data;
set => MutateState(state =>
{
if (state.Alert is { } && value is { })
{
throw new InvalidOperationException("A push may not have both an Alert and Data.");
}
state.Data = value;
});
}
/// <summary>
/// A convenience method which sets Data to a dictionary with alert as its only field. Equivalent to
///
/// <code>
/// Data = new Dictionary<string, object> {{"alert", alert}};
/// </code>
///
/// This should not be used in tandem with Data.
/// </summary>
public string Alert
{
get => State.Alert;
set => MutateState(state =>
{
if (state.Data is { } && value is { })
{
throw new InvalidOperationException("A push may not have both an Alert and Data.");
}
state.Alert = value;
});
}
#endregion
internal IDictionary<string, object> Encode() => ParsePushEncoder.Instance.Encode(State);
void MutateState(Action<MutablePushState> func)
{
lock (Mutex)
{
State = State.MutatedClone(func);
}
}
#region Sending Push
/// <summary>
/// Request a push to be sent. When this task completes, Parse has successfully acknowledged a request
/// to send push notifications but has not necessarily finished sending all notifications
/// requested. The current status of recent push notifications can be seen in your Push Notifications
/// console on http://parse.com
/// </summary>
/// <returns>A Task for continuation.</returns>
public Task SendAsync() => SendAsync(CancellationToken.None);
/// <summary>
/// Request a push to be sent. When this task completes, Parse has successfully acknowledged a request
/// to send push notifications but has not necessarily finished sending all notifications
/// requested. The current status of recent push notifications can be seen in your Push Notifications
/// console on http://parse.com
/// </summary>
/// <param name="cancellationToken">CancellationToken to cancel the current operation.</param>
public Task SendAsync(CancellationToken cancellationToken) => Services.PushController.SendPushNotificationAsync(State, Services, cancellationToken);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Leap;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Tugas
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
Texture2D _whiteSquare; //the white 64x64 pixels bitmap to draw with
SpriteFont _defaultFont; //font to write info with
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2 _boardPosition; //where to position the board
const int _tileSize = 12; //how wide/tall the tiles are
Vector2 _boardPositionTiny; //where to position the board
const int _tileSizeTiny = 1; //how wide/tall the tiles are
Texture2D textureObj; //pointr for leap motion controller
Texture2D textureTrain;
Texture2D textureRecog;
GameObject finger; //object finger
GameObject btnTrain;
GameObject btnRecog;
Controller leapController; //LMC controller
SingleListener leapListener; //listener for LMC
Vector2 leapDownPosition; //where the mouse was clicked down
float xObj; //get x pos for leap
float yObj; //get x pos for leap
float indicator; //get depth/z pos for leap
readonly bool[,] _board = new bool[28, 28];
//initialize matrix for preview
double[] objectVector;
TimeSpan elapTime = TimeSpan.Zero;
ProgramDNN dnn;
string recognizeRes;
string learningRes;
//denote random number from 1 to 26 to denote A to Z
Random rnd = new Random();
int label;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//set the screen size
graphics.PreferredBackBufferHeight = 700;
graphics.PreferredBackBufferWidth = 900;
//positions the top left corner of the board - change this to move the board
//_boardPosition = new Vector2(100, 75);
_boardPosition = new Vector2(0, 0);
_boardPositionTiny = new Vector2(graphics.PreferredBackBufferHeight, 300);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
leapController = new Controller();
leapListener = new SingleListener();
leapController.EnableGesture(Gesture.GestureType.TYPE_CIRCLE);
leapController.AddListener(leapListener);
//initialize vector
objectVector = new double[_board.Length];
//objectVector[0] = 9999;
dnn = new ProgramDNN();
label = 1;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//load the textures
_whiteSquare = Content.Load<Texture2D>("white_64x64");
textureObj = Content.Load<Texture2D>("pointer");
textureTrain = Content.Load<Texture2D>("train");
textureRecog = Content.Load<Texture2D>("recognize");
//load the font
_defaultFont = Content.Load<SpriteFont>("DefaultFont");
//instance finger
finger = new GameObject(textureObj, Vector2.Zero);
btnTrain = new GameObject(textureTrain, Vector2.Zero);
btnRecog = new GameObject(textureRecog, Vector2.Zero);
//remembers the draggable squares position, so we can easily test for mouseclicks on it
//finger.color = Color.Snow;
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
private void SaveData(double[] objectVector)
{
//generate random number for label
var sourcePath = @"D:\dataHuruf.csv";
var delimiter = ",";
var firstLineContainsHeaders = true;
var tempPath = @"D:\data.csv";
var lineNumber = 0;
var splitExpression = new Regex(@"(" + delimiter + @")(?=(?:[^""]|""[^""]*"")*$)");
using (var writer = new StreamWriter(tempPath))
using (var reader = new StreamReader(sourcePath))
{
string line = null;
string[] headers = null;
if (firstLineContainsHeaders)
{
line = reader.ReadLine();
lineNumber++;
if (string.IsNullOrEmpty(line)) return; // file is empty;
headers = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
writer.WriteLine(line); // write the original header to the temp file.
}
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
// if there are no headers, do a simple sanity check to make sure you always have the same number of columns in a line
if (headers == null) headers = new string[columns.Length];
if (columns.Length != headers.Length) throw new InvalidOperationException(string.Format("Line {0} is missing one or more columns.", lineNumber));
// TODO: search and replace in columns
// example: replace 'v' in the first column with '\/': if (columns[0].Contains("v")) columns[0] = columns[0].Replace("v", @"\/");
writer.WriteLine(string.Join(delimiter, columns));
}
}
File.Delete(sourcePath);
File.Move(tempPath, sourcePath);
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0},", label);
for (int i = 0; i < 783; i++)
sb.AppendFormat("{0},", objectVector[i]);
sb.AppendFormat("{0}", objectVector[783]);
// flush all rows once time.
File.AppendAllText(sourcePath, sb.ToString(), Encoding.UTF8);
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (leapListener != null)
{
foreach (FingerPointStorage f in leapListener.fingerPoint)
{
if (f.isActive)
{
xObj = f.g_X * 27*12; //graphics.PreferredBackBufferWidth;
yObj = f.g_Y * 27 * 12; // graphics.PreferredBackBufferHeight;
finger.Position.X = (int)xObj;
finger.Position.Y = (int)yObj;
if (f.g_circle >= 3 && f.g_circle < 3.4)
{
SaveData(objectVector);
label = rnd.Next(1, 26);
Console.WriteLine("Data Tesimpan\nSilahkan tulis lagi");
}
//mengambil posisi z sebagai deteksi kedalaman
if (finger.BoundingBox.Intersects(btnTrain.BoundingBox))
{
btnRecog.color = Color.SlateGray;
btnRecog.Position = new Vector2(btnRecog.Position.X + 10, btnRecog.Position.Y + 10);
finger.color = Color.Black;
elapTime += gameTime.ElapsedGameTime;
if (elapTime > TimeSpan.FromSeconds(1.2))
{
elapTime = TimeSpan.Zero;
}
}
else if (finger.BoundingBox.Intersects(btnRecog.BoundingBox))
{
btnRecog.color = Color.SlateGray;
btnRecog.Position = new Vector2(btnRecog.Position.X + 10, btnRecog.Position.Y + 10);
finger.color = Color.Black;
elapTime += gameTime.ElapsedGameTime;
if (elapTime > TimeSpan.FromSeconds(1.2))
{
//dnn.setRecognize(objectVector);
//recognizeRes = dnn.getRecognize();
SaveData(objectVector);
label = rnd.Next(1, 26);
elapTime = TimeSpan.Zero;
}
}
//find out which square the mouse is over
Vector3 tile = new Vector3(GetSquareFromCurrentMousePosition(), 0);
leapDownPosition = new Vector2((int)xObj, (int)yObj);
if (f.numHand == true)
{
for (int i = 0; i < 28; i++)
for (int j = 0; j < 28; j++)
_board[i, j] = false;
for (int i = 0; i < objectVector.Length; ++i)
objectVector[i] = 0.0d;
}
if (f.g_Z < 130)
{
//indicator = 150 - f.g_Z;
// Console.WriteLine(indicator);
//if (indicator > 50)
if (f.g_Z != 0)
{
//if the mousebutton was released inside the board
if (IsMouseInsideBoard())
{
//and set that square to true (has a piece)
//_board[(int)tile.X, (int)tile.Y] = true;
//batas horisontal dari x dan y = 0 sampai x kurang dari panjang dan y = 0
if (((int)tile.X >= 0 && ((int)tile.X < 27) && (int)tile.Y == 0))
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y + 1] = true;
_board[(int)tile.X, (int)tile.Y + 1] = true;
}
else if((int)tile.X == 27 && (int)tile.Y == 0)
{
if( _board[(int)tile.X-1, (int)tile.Y] != true && _board[(int)tile.X, (int)tile.Y+1] != true)
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X, (int)tile.Y+1] = true;
_board[(int)tile.X - 1, (int)tile.Y] = true;
_board[(int)tile.X - 1, (int)tile.Y + 1] = true;
}
}
//
//batas horisontal dari x = 0 dan y = lebar sampai x kurang dari panjang dan y = lebar
else if (((int)tile.X >= 0 && (int)tile.X < 27) && (int)tile.Y == 27)
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y] = true;
_board[(int)tile.X, (int)tile.Y - 1] = true;
_board[(int)tile.X + 1, (int)tile.Y - 1] = true;
}
else if ((int)tile.X == 27 && (int)tile.Y == 27)
{
if (_board[(int)tile.X-1, (int)tile.Y] != true && _board[(int)tile.X, (int)tile.Y - 1] != true)
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X - 1, (int)tile.Y] = true;
_board[(int)tile.X - 1, (int)tile.Y - 1] = true;
_board[(int)tile.X, (int)tile.Y - 1] = true;
}
}
//
//batas horisontal dari x dan y = 0 sampai x kurang dari panjang dan y = 0
else if (((int)tile.Y >= 0 && ((int)tile.Y < 27) && (int)tile.X == 0))
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y + 1] = true;
_board[(int)tile.X, (int)tile.Y + 1] = true;
}
else if ((int)tile.Y == 27 && (int)tile.X == 0)
{
if (_board[(int)tile.X, (int)tile.Y - 1] != true && _board[(int)tile.X+1, (int)tile.Y] != true)
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y] = true;
_board[(int)tile.X, (int)tile.Y-1] = true;
_board[(int)tile.X + 1, (int)tile.Y - 1] = true;
}
}
//batas vertical dari x = panjang dan y = 0 sampai y kurang dari lebar dan x = panjang
else if (((int)tile.Y >= 0 && (int)tile.Y < 27) && (int)tile.X == 27)
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X - 1, (int)tile.Y] = true;
_board[(int)tile.X, (int)tile.Y + 1] = true;
_board[(int)tile.X - 1, (int)tile.Y + 1] = true;
}
else
{
_board[(int)tile.X, (int)tile.Y] = true;
_board[(int)tile.X + 1, (int)tile.Y] = true;
_board[(int)tile.X, (int)tile.Y + 1] = true;
_board[(int)tile.X - 1, (int)tile.Y] = true;
_board[(int)tile.X, (int)tile.Y - 1] = true;
_board[(int)tile.X + 1, (int)tile.Y + 1] = true;
_board[(int)tile.X - 1, (int)tile.Y - 1] = true;
_board[(int)tile.X + 1, (int)tile.Y - 1] = true;
_board[(int)tile.X - 1, (int)tile.Y + 1] = true;
}
//Console.WriteLine("{0},{1}", (int)tile.X, (int)tile.Y);
int count = 0;
for (int i = 0; i < 28; i++)
{
for (int j = 0; j < 28; j++)
{
if (tile.X == j && tile.Y == i && j != 27)
{
if (count <= 755 && (count <= 27 || count == 28 || count == 56
|| count == 84 || count == 112 || count == 140 || count == 168
|| count == 196 || count == 224 || count == 252 || count == 280
|| count == 308 || count == 336 || count == 364 || count == 392
|| count == 420 || count == 448 || count == 476 || count == 504
|| count == 532 || count == 560 || count == 588 || count == 616
|| count == 644 || count == 672 || count == 700 || count == 728))
{
objectVector[count] = 1.0d;
objectVector[count + 1] = 1.0d;
objectVector[count + 28] = 1.0d;
objectVector[count + 29] = 1.0d;
//Console.WriteLine("count {0}" + count);
}
else if (count > 755 && count <= 783)
{
//barisan bawah
objectVector[count] = 1.0d;
objectVector[count + 1] = 1.0d;
}
else
{
// 6 piece
objectVector[count - 27] = 1.0d;
objectVector[count - 28] = 1.0d;
objectVector[count - 29] = 1.0d;
objectVector[count] = 1.0d;
objectVector[count + 1] = 1.0d;
objectVector[count - 1] = 1.0d;
objectVector[count + 27] = 1.0d;
objectVector[count + 28] = 1.0d;
objectVector[count + 29] = 1.0d;
}
count = 1;
}
else if (tile.X == j && tile.Y == i && j == 27)
{
if (count <= 755)
{
//untuk tepi pojok kanan
objectVector[count] = 1.0d;
objectVector[count - 1] = 1.0d;
objectVector[count + 27] = 1.0d;
objectVector[count + 28] = 1.0d;
// Console.WriteLine("count {0}" + count);
}
else if(count == 783)
{
//ujung bawah
objectVector[count] = 1.0d;
objectVector[count - 1] = 1.0d;
}
else
{
//lainnya
objectVector[count] = 1.0d;
objectVector[count - 1] = 1.0d;
}
}
else
{
count++;
}
}
}
}
}
}
else
{
//if (IsMouseInsideBoard())
//{
// _board[(int)tile.X, (int)tile.Y] = false;
// int count = 0;
// for (int i = 0; i < 28; i++)
// {
// for (int j = 0; j < 28; j++)
// {
// if (tile.X == j && tile.Y == i)
// {
// objectVector[count] = 0.0d;
// Console.WriteLine("count {0}" + count);
// count = 0;
// }
// else
// {
// count++;
// }
// }
// }
//}
}
}
}
}
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.DarkOrchid);
// TODO: Add your drawing code here
//start drawing
spriteBatch.Begin();
DrawText(); //draw helptext
DrawBoard(); //draw the board
DrawBoardTiny(); //draw the board
btnTrain.ValPosition = new Vector2(graphics.PreferredBackBufferWidth - btnTrain.getTexture().Width,20);
btnRecog.ValPosition = new Vector2(graphics.PreferredBackBufferWidth - btnRecog.getTexture().Width, btnTrain.Position.Y+btnTrain.getTexture().Height+10);
btnTrain.Draw(spriteBatch, 1f);
btnRecog.Draw(spriteBatch, 1f);
if (IsMouseInsideBoard())
{
}
else
{
finger.Draw(spriteBatch, 1f);
string strTimeWait = string.Format("{0}%", (Math.Floor(elapTime.TotalSeconds * 10 / 12 * 100)).ToString());
spriteBatch.DrawString(_defaultFont, strTimeWait, new Vector2(finger.Position.X + finger.BoundingBox.Width / 2, finger.Position.Y + finger.BoundingBox.Height / 2), Color.Black);
}
if(learningRes != null)
spriteBatch.DrawString(_defaultFont, learningRes, new Vector2(btnRecog.Position.X, btnRecog.Position.Y + btnRecog.BoundingBox.Height + 10 + 100), Color.Black);
if(recognizeRes != null)
spriteBatch.DrawString(_defaultFont, recognizeRes, new Vector2(btnRecog.Position.X, btnRecog.Position.Y + btnRecog.BoundingBox.Height + 30 + 100), Color.Black);
//end drawing
spriteBatch.End();
base.Draw(gameTime);
}
private int CountLinesInString(string s)
{
int count = 1;
int start = 0;
while ((start = s.IndexOf('\n', start)) != -1)
{
count++;
start++;
}
return count;
}
public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
result = (char)('A' + value % 26) + result;
value /= 26;
}
return result;
}
private void DrawText()
{
string labelAlphabet = IntToLetters(label);
string title = "Digit Character Recognition\nGambarkan label huruf besar ini '" + labelAlphabet + "' untuk kemudian disimpan.\nUntuk menyimpan gunakan gesture jari melingkar pada saat indikator bewarna merah\nIndikator warna merah berarti tidak bisa menulis pada board\nIndikator hijau dapat dilakukan penulisan.";
spriteBatch.DrawString(_defaultFont, title, new Vector2(20, 400), Color.White);
spriteBatch.DrawString(_defaultFont, "fly in and out your hand onto board with leap controller\nplace all your hand to erase all stroke on board", new Vector2(100, 640), Color.White);
spriteBatch.DrawString(_defaultFont, "@sukasenyumm", new Vector2(725, 665), Color.White);
}
// Draws the game board
private void DrawBoard()
{
float opacity = .5f; //how opaque/transparent to draw the square
Color colorToUse = Color.White; //background color to use
Rectangle squareToDrawPosition = new Rectangle(); //the square to draw (local variable to avoid creating a new variable per square)
//for all columns
for (int x = 0; x < _board.GetLength(0); x++)
{
//for all rows
for (int y = 0; y < _board.GetLength(1); y++)
{
//figure out where to draw the square
squareToDrawPosition = new Rectangle((int)(x * _tileSize + _boardPosition.X), (int)(y * _tileSize + _boardPosition.Y), _tileSize, _tileSize);
//Console.WriteLine("{0},{1}", squareToDrawPosition.X, squareToDrawPosition.Y);
//the code below will make the board checkered using only a single, white square:
//if we add the x and y value of the tile
//and it is even, we make it one third opaque
if ((x + y) % 2 == 0)
{
// opacity = .33f;
}
else
{
//otherwise it is one tenth opaque
opacity = .1f;
}
if (IsMouseInsideBoard() && IsMouseOnTile(x, y))
{
colorToUse = Color.Red;
opacity = .5f;
}
else
{
colorToUse = Color.White;
}
//if the square has a tile - draw it
if (_board[x, y])
{
spriteBatch.Draw(_whiteSquare, squareToDrawPosition, Color.Black);
colorToUse = Color.Yellow;
}
//draw the white square at the given position, offset by the x- and y-offset, in the opacity desired
spriteBatch.Draw(_whiteSquare, squareToDrawPosition, colorToUse * opacity);
}
}
}
// Draws the game board
private void DrawBoardTiny()
{
float opacity = .5f; //how opaque/transparent to draw the square
Color colorToUse = Color.White; //background color to use
Rectangle squareToDrawPosition = new Rectangle(); //the square to draw (local variable to avoid creating a new variable per square)
for (int x = 0; x < _board.GetLength(0); x++)
{
for (int y = 0; y < _board.GetLength(1); y++)
{
squareToDrawPosition = new Rectangle((int)(x * _tileSizeTiny + _boardPositionTiny.X), (int)(y * _tileSizeTiny + _boardPositionTiny.Y), _tileSizeTiny, _tileSizeTiny);
if ((x + y) % 2 == 0)
{
// opacity = .33f;
}
else
{
opacity = .1f;
}
if (IsMouseInsideBoard() && IsMouseOnTile(x, y))
{
colorToUse = Color.Red;
opacity = .5f;
}
else
{
colorToUse = Color.White;
}
spriteBatch.Draw(_whiteSquare, squareToDrawPosition, colorToUse * opacity);
if (_board[x, y])
{
spriteBatch.Draw(_whiteSquare, squareToDrawPosition, Color.Black);
}
}
}
}
bool IsMouseInsideBoard()
{
if (xObj >= _boardPosition.X && xObj <= _boardPosition.X + _board.GetLength(0) * _tileSize && yObj >= _boardPosition.Y && yObj <= _boardPosition.Y + _board.GetLength(1) * _tileSize)
{
return true;
}
else
{ return false; }
}
Vector2 GetSquareFromCurrentMousePosition()
{
//adjust for the boards offset (_boardPosition) and do an integerdivision
return new Vector2((int)(xObj - _boardPosition.X) / _tileSize, (int)(yObj - _boardPosition.Y) / _tileSize);
}
// Checks to see whether a given coordinate is within the board
private bool IsMouseOnTile(int x, int y)
{
//do an integerdivision (whole-number) of the coordinates relative to the board offset with the tilesize in mind
return (int)(xObj - _boardPosition.X) / _tileSize == x && (int)(yObj - _boardPosition.Y) / _tileSize == y;
}
}
}
| |
// HTSpriteSheet v2.0 (Aout 2012)
// HTSpriteSheet.cs library is copyright (c) of Hedgehog Team
// Please send feedback or bug reports to the.hedgehog.team@gmail.com
// Release note :
// V2.0
// - Add color variation
// - Add Rotation variation
// - Add life parameter
using UnityEngine;
using System.Collections;
/// <summary>
/// HTSpriteSheet allows the creation of a particle and play an animated sprite from spritesheet.
/// </summary>
public class HTSpriteSheet : MonoBehaviour {
#region enumeration
/// <summary>
/// The rendering mode for particles..
/// </summary>
public enum CameraFacingMode{
/// <summary>
/// Render the particles as billboards facing the camera with tag "MainCamera". (Default)
/// </summary>
BillBoard,
/// <summary>
/// Render the particles as billboards always facing up along the y-Axis.
/// </summary>
Horizontal,
/// <summary>
/// Render the particles as billboards always facing up along the X-Axis.
/// </summary>
Vertical,
/// <summary>
/// The particle never facinc up the camera.
/// </summary>
Never
};
#endregion
#region public properties
/// <summary>
/// The sprite sheet material.
/// </summary>
public Material spriteSheetMaterial;
/// <summary>
/// The number of sprtie on the spritesheet.
/// </summary>
public int spriteCount;
/// <summary>
/// The uv animation tile x.
/// </summary>
public int uvAnimationTileX;
/// <summary>
/// The uv animation tile y.
/// </summary>
public int uvAnimationTileY;
/// <summary>
/// The number of images per second to play animation
/// </summary>
public int framesPerSecond;
/// <summary>
/// The initial size of the explosion
/// </summary>
public Vector3 sizeStart = new Vector3(1,1,1);
/// <summary>
/// The size end.
/// </summary>
public Vector3 sizeEnd = new Vector3(1,1,1);
/// <summary>
/// Applied a rondom rotation on z-Axis.
/// </summary>
public bool randomRotation;
/// <summary>
/// The rotation start.
/// </summary>
public float rotationStart;
/// <summary>
/// The rotation end.
/// </summary>
public float rotationEnd;
/// <summary>
/// The is one shot animation.
/// </summary>
public bool isOneShot=true;
/// <summary>
/// The life.
/// </summary>
public float life=0;
/// <summary>
/// The billboarding mode
/// </summary>
public CameraFacingMode billboarding; // Bilboardin mode
/// <summary>
/// The add light effect.
/// </summary>
public bool addLightEffect=false;
/// <summary>
/// The light range.
/// </summary>
public float lightRange;
/// <summary>
/// The color of the light.
/// </summary>
public Color lightColor;
/// <summary>
/// The light fade speed.
/// </summary>
public float lightFadeSpeed=1;
/// <summary>
/// The add color effect.
/// </summary>
public bool addColorEffect;
/// <summary>
/// The color start.
/// </summary>
public Color colorStart = new Color(1f,1f,1f,1f);
/// <summary>
/// The color end.
/// </summary>
public Color colorEnd = new Color(1f,1f,1f,1f);
/// <summary>
/// The fold out.
/// </summary>
public bool foldOut=false;
// For inspector save
public Vector3 offset;
public float waittingTime;
public bool copy=false;
#endregion
#region private properties
/// <summary>
/// The material with the sprite speed.
/// </summary>
//private Material mat;
/// <summary>
/// The mesh.
/// </summary>
private Mesh mesh;
/// <summary>
/// The mesh render.
/// </summary>
private MeshRenderer meshRender;
/// <summary>
/// The audio source.
/// </summary>
private AudioSource soundEffect;
/// <summary>
/// The start time of the explosion
/// </summary>
private float startTime;
/// <summary>
/// The main camera.
/// </summary>
private Transform mainCamTransform;
/// <summary>
/// The effect end.
/// </summary>
private bool effectEnd=false;
/// <summary>
/// The random Z angle.
/// </summary>
private float randomZAngle;
/// <summary>
/// The color step.
/// </summary>
private Color colorStep;
/// <summary>
/// The current color.
/// </summary>
private Color currentColor;
/// <summary>
/// The size step.
/// </summary>
private Vector3 sizeStep;
/// <summary>
/// The size of the current.
/// </summary>
private Vector3 currentSize;
/// <summary>
/// The current rotation.
/// </summary>
private float currentRotation;
/// <summary>
/// The rotation step.
/// </summary>
private float rotationStep;
/// <summary>
/// The list start.
/// </summary>
private float lifeStart;
/// <summary>
/// Transform cahce.
/// </summary>
private Transform myTransform;
#endregion
#region MonoBehaviour methods
/// <summary>
/// Awake this instance.
/// </summary>
void Awake(){
// Creation of the particle
CreateParticle();
// We search the main camera
mainCamTransform = Camera.main.transform;
// do we have sound effect ?
soundEffect = GetComponent<AudioSource>();
// Add light
if (addLightEffect){
gameObject.AddComponent<Light>();
gameObject.GetComponent<Light>().color = lightColor;
gameObject.GetComponent<Light>().range = lightRange;
}
GetComponent<Renderer>().enabled = false;
}
// Use this for initialization
void Start () {
InitSpriteSheet();
}
/// <summary>
/// Update this instance.
/// </summary>
void Update () {
bool end=false;
Camera_BillboardingMode();
// Calculate index
float index = (Time.time-startTime) * framesPerSecond;
if (!isOneShot && life>0 && (Time.time -lifeStart)> life){
effectEnd=true;
}
if ((index<=spriteCount || !isOneShot ) && !effectEnd ){
if (index >= spriteCount){
startTime = Time.time;
index=0;
if (addColorEffect){
currentColor = colorStart;
meshRender.material.SetColor("_Color", currentColor);
}
currentSize = sizeStart;
myTransform.localScale = currentSize;
if (randomRotation){
currentRotation = Random.Range(-180.0f,180.0f);
}
else{
currentRotation = rotationStart;
}
}
// repeat when exhausting all frames
index = index % (uvAnimationTileX * uvAnimationTileY);
// Size of every tile
Vector2 size = new Vector2 (1.0f / uvAnimationTileX, 1.0f / uvAnimationTileY);
// split into horizontal and vertical index
float uIndex = Mathf.Floor(index % uvAnimationTileX);
float vIndex = Mathf.Floor(index / uvAnimationTileX);
// build offset
Vector2 offset = new Vector2 (uIndex * size.x , 1.0f - size.y - vIndex * size.y);
GetComponent<Renderer>().material.SetTextureOffset ("_MainTex", offset);
GetComponent<Renderer>().material.SetTextureScale ("_MainTex", size);
GetComponent<Renderer>().enabled = true;
}
else{
effectEnd = true;
GetComponent<Renderer>().enabled = false;
end = true;
if (soundEffect){
if (soundEffect.isPlaying){
end = false;
}
}
if (addLightEffect && end){
if (gameObject.GetComponent<Light>().intensity>0){
end = false;
}
}
if (end){
Destroy(gameObject);
}
}
// Size
if (sizeStart != sizeEnd){
myTransform.localScale += sizeStep * Time.deltaTime ;
}
// Light effect
if (addLightEffect && lightFadeSpeed!=0){
gameObject.GetComponent<Light>().intensity -= lightFadeSpeed*Time.deltaTime;
}
// Color Effect
if (addColorEffect){
currentColor = new Color(currentColor.r + colorStep.r * Time.deltaTime,currentColor.g + colorStep.g* Time.deltaTime,currentColor.b + colorStep.b* Time.deltaTime , currentColor.a + colorStep. a*Time.deltaTime);
meshRender.material.SetColor("_TintColor", currentColor);
}
}
#endregion
#region private methods
/// <summary>
/// Creates the particle.
/// </summary>
void CreateParticle(){
mesh = gameObject.AddComponent<MeshFilter>().mesh;
meshRender = gameObject.AddComponent<MeshRenderer>();
mesh.vertices = new Vector3[] { new Vector3(-0.5f,-0.5f,0f),new Vector3(-0.5f,0.5f,0f), new Vector3(0.5f,0.5f,0f), new Vector3(0.5f,-0.5f,0f) };
mesh.triangles = new int[] {0,1,2, 2,3,0 };
mesh.uv = new Vector2[] { new Vector2(1f,0f), new Vector2 (1f, 1f), new Vector2 (0f, 1f), new Vector2 (0f, 0f)};
meshRender.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
//meshRender.castShadows = false;
meshRender.receiveShadows = false;
mesh.RecalculateNormals();
GetComponent<Renderer>().material= spriteSheetMaterial;
}
/// <summary>
/// Camera_s the billboarding mode.
/// </summary>
void Camera_BillboardingMode(){
Vector3 lookAtVector = myTransform.position-mainCamTransform.position ;
switch (billboarding){
case CameraFacingMode.BillBoard:
myTransform.LookAt( mainCamTransform.position - lookAtVector);
break;
case CameraFacingMode.Horizontal:
lookAtVector.x = lookAtVector.z =0 ;
myTransform.LookAt(mainCamTransform.position - lookAtVector);
break;
case CameraFacingMode.Vertical:
lookAtVector.y=lookAtVector.z =0;
myTransform.LookAt(mainCamTransform.position - lookAtVector);
break;
}
if (rotationStart!=rotationEnd){
currentRotation+=rotationStep*Time.deltaTime;
}
myTransform.eulerAngles = new Vector3(myTransform.eulerAngles.x,myTransform.eulerAngles.y,currentRotation);
}
#endregion
#region public methos
/// <summary>
/// Inits the sprite sheet.
/// </summary>
public void InitSpriteSheet(){
startTime = Time.time;
lifeStart = Time.time;
myTransform = transform;
// time divider
float divider = (float)spriteCount/(float)framesPerSecond;
// size
sizeStep = new Vector3( (sizeEnd.x - sizeStart.x)/divider, (sizeEnd.y - sizeStart.y)/divider,(sizeEnd.z - sizeStart.z)/divider);
currentSize = sizeStart;
myTransform.localScale = currentSize;
//rotation
rotationStep = (rotationEnd-rotationStart)/divider;
// Random start rotation
if (randomRotation){
currentRotation = Random.Range(-180.0f,180.0f);
}
else{
currentRotation = rotationStart;
}
// Add color effect
if (addColorEffect){
colorStep = new Color( (colorEnd.r - colorStart.r)/divider,(colorEnd.g - colorStart.g)/divider,(colorEnd.b - colorStart.b)/divider, (colorEnd.a - colorStart.a)/divider);
currentColor = colorStart;
meshRender.material.SetColor("_TintColor", currentColor);
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Nimbus.ConcurrentCollections;
using Nimbus.Configuration.Settings;
using Nimbus.Extensions;
using Nimbus.Infrastructure.Events;
using Nimbus.Infrastructure.Heartbeat.PerformanceCounters;
using Nimbus.InfrastructureContracts;
using Nimbus.MessageContracts.ControlMessages;
using Timer = System.Timers.Timer;
namespace Nimbus.Infrastructure.Heartbeat
{
internal class Heartbeat : IHeartbeat, IDisposable
{
private readonly ApplicationNameSetting _applicationName;
private readonly HeartbeatIntervalSetting _heartbeatInterval;
private readonly InstanceNameSetting _instanceName;
private readonly IEventSender _eventSender;
private readonly ILogger _logger;
private readonly IClock _clock;
private readonly List<PerformanceCounterBase> _performanceCounters = new List<PerformanceCounterBase>();
private readonly List<PerformanceCounterDto> _performanceCounterHistory = new List<PerformanceCounterDto>();
private readonly object _mutex = new object();
private static readonly ThreadSafeLazy<Type[]> _performanceCounterTypes = new ThreadSafeLazy<Type[]>(() => typeof (Heartbeat).Assembly
.DefinedTypes
.Select(ti => ti.AsType())
.Where(
t =>
typeof (PerformanceCounterBase)
.IsAssignableFrom(t))
.Where(t => !t.IsAbstract)
.ToArray());
private Timer _heartbeatTimer;
private Timer _collectTimer;
private bool _isRunning;
private int _heartbeatExecuting;
public Heartbeat(ApplicationNameSetting applicationName,
HeartbeatIntervalSetting heartbeatInterval,
InstanceNameSetting instanceName,
IClock clock,
IEventSender eventSender,
ILogger logger)
{
_applicationName = applicationName;
_heartbeatInterval = heartbeatInterval;
_instanceName = instanceName;
_eventSender = eventSender;
_logger = logger;
_clock = clock;
}
private void OnCollectTimerElapsed(object sender, ElapsedEventArgs e)
{
Task.Run(async () => await Collect()).ConfigureAwaitFalse();
}
private async Task Collect()
{
lock (_mutex)
{
var dtos = _performanceCounters
.AsParallel()
.Select(c => new PerformanceCounterDto(_clock.UtcNow, c.CounterName, c.CategoryName, c.InstanceName, c.GetNextTransformedValue()))
.ToArray();
_performanceCounterHistory.AddRange(dtos);
}
}
private async void OnHeartbeatTimerElapsed(object sender, ElapsedEventArgs e)
{
// Prevent overlapping execution of heartbeats
if (Interlocked.CompareExchange(ref _heartbeatExecuting, 1, 0) == 0)
{
try
{
// The timer elapsed handler is already executing on the threadpool, so
// there is no reason to use Task.Run() to invoke the Beat method. Await the
// beat so the heartbeatExecuting flag can be set to zero (reset) when complete.
await Beat();
}
catch (Exception exc)
{
_logger.Warn("Error publishing heartbeat: {Message}.", exc.ToString());
}
finally
{
_heartbeatExecuting = 0; // indicates completion
}
}
}
private async Task Beat()
{
var heartbeatEvent = CreateHeartbeatEvent();
await _eventSender.Publish(heartbeatEvent);
}
public async Task Start()
{
if (_heartbeatInterval.Value == TimeSpan.MaxValue) return;
if (_isRunning) return;
foreach (var counterType in _performanceCounterTypes.Value)
{
try
{
var counter = (PerformanceCounterBase) Activator.CreateInstance(counterType);
_performanceCounters.Add(counter);
}
catch (Exception exc)
{
_logger.Warn(
"Could not create performance counter {PerformanceCounter}: {Message}. This might occur because the current process is not running with suffucient privileges.",
counterType.FullName,
exc.ToString());
}
}
_collectTimer = new Timer(TimeSpan.FromSeconds(5).TotalMilliseconds)
{
AutoReset = true
};
_collectTimer.Elapsed += OnCollectTimerElapsed;
_collectTimer.Start();
_heartbeatTimer = new Timer(_heartbeatInterval.Value.TotalMilliseconds)
{
AutoReset = true
};
_heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;
_heartbeatTimer.Start();
_isRunning = true;
}
public async Task Stop()
{
if (_heartbeatInterval.Value == TimeSpan.MaxValue) return;
if (!_isRunning) return;
var collectTimer = _collectTimer;
_collectTimer = null;
if (collectTimer != null)
{
collectTimer.Stop();
collectTimer.Dispose();
}
var heartbeatTimer = _heartbeatTimer;
_heartbeatTimer = null;
if (heartbeatTimer != null)
{
heartbeatTimer.Stop();
heartbeatTimer.Dispose();
}
_performanceCounters
.AsParallel()
.OfType<IDisposable>()
.Do(c => c.Dispose())
.Done();
_performanceCounters.Clear();
}
private HeartbeatEvent CreateHeartbeatEvent()
{
var process = Process.GetCurrentProcess();
PerformanceCounterDto[] performanceCounterHistory;
lock (_mutex)
{
performanceCounterHistory = _performanceCounterHistory.ToArray();
_performanceCounterHistory.Clear();
}
var heartbeatEvent = new HeartbeatEvent
{
Timestamp = _clock.UtcNow,
ApplicationName = _applicationName,
InstanceName = _instanceName,
ProcessId = process.Id,
ProcessName = process.ProcessName,
MachineName = Environment.MachineName,
OSVersion = Environment.OSVersion.VersionString,
ProcessorCount = Environment.ProcessorCount,
StartTime = new DateTimeOffset(process.StartTime),
UserProcessorTime = process.UserProcessorTime,
TotalProcessorTime = process.TotalProcessorTime,
WorkingSet64 = process.WorkingSet64,
PeakWorkingSet64 = process.PeakWorkingSet64,
VirtualMemorySize64 = process.VirtualMemorySize64,
PerformanceCounters = performanceCounterHistory
};
return heartbeatEvent;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
Stop().Wait();
}
}
}
| |
// <copyright file="RetryContext.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IX.StandardExtensions.ComponentModel;
using IX.StandardExtensions.Contracts;
using IX.StandardExtensions.Extensions;
namespace IX.Retry.Contexts
{
internal abstract class RetryContext : DisposableBase
{
private RetryOptions options;
internal RetryContext(RetryOptions options)
{
Contract.RequiresNotNullPrivate(
in options,
nameof(options));
this.options = options;
}
/// <summary>
/// Begins the retry process asynchronously.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>System.Threading.Tasks.Task.</returns>
internal async Task BeginRetryProcessAsync(CancellationToken cancellationToken)
{
this.RequiresNotDisposedPrivate();
DateTime now = DateTime.UtcNow;
var retries = 0;
var exceptions = new List<Exception>();
bool shouldRetry;
do
{
shouldRetry = this.RunOnce(
exceptions,
now,
ref retries);
cancellationToken.ThrowIfCancellationRequested();
if (!shouldRetry || this.options.WaitBetweenRetriesType == WaitType.None)
{
continue;
}
TimeSpan waitFor = this.GetRetryTimeSpan(
retries,
now);
await Task.Delay(
(int)waitFor.TotalMilliseconds,
cancellationToken).ConfigureAwait(false);
}
while (shouldRetry);
if (this.options.ThrowExceptionOnLastRetry)
{
throw new AggregateException(exceptions);
}
}
/// <summary>
/// Begins the retry process.
/// </summary>
internal void BeginRetryProcess(CancellationToken cancellationToken)
{
this.RequiresNotDisposedPrivate();
DateTime now = DateTime.UtcNow;
var retries = 0;
var exceptions = new List<Exception>();
bool shouldRetry;
do
{
shouldRetry = this.RunOnce(
exceptions,
now,
ref retries);
cancellationToken.ThrowIfCancellationRequested();
if (!shouldRetry || this.options.WaitBetweenRetriesType == WaitType.None)
{
continue;
}
TimeSpan waitFor = this.GetRetryTimeSpan(
retries,
now);
Thread.Sleep((int)waitFor.TotalMilliseconds);
}
while (shouldRetry);
if (this.options.ThrowExceptionOnLastRetry)
{
throw new AggregateException(exceptions);
}
}
/// <summary>
/// Disposes in the general (managed and unmanaged) context.
/// </summary>
protected override void DisposeGeneralContext()
{
this.options = null;
base.DisposeGeneralContext();
}
/// <summary>
/// Invokes the method that needs retrying.
/// </summary>
private protected abstract void Invoke();
private bool RunOnce(
ICollection<Exception> exceptions,
DateTime now,
ref int retries)
{
Contract.RequiresNotNullPrivate(
in exceptions,
nameof(exceptions));
var shouldRetry = true;
try
{
this.Invoke();
shouldRetry = false;
}
catch (StandardExtensions.StopRetryingException)
{
shouldRetry = false;
}
catch (Exception ex)
{
List<Tuple<Type, Func<Exception, bool>>> retryOnExceptions = this.options.RetryOnExceptions;
if (retryOnExceptions.Count > 0 && !this.options.RetryOnExceptions.Any(
(
p,
exL1) => p.Item1 == exL1.GetType() && (p.Item2 == null || p.Item2(exL1)), ex))
{
throw;
}
exceptions.Add(ex);
if ((this.options.Type & RetryType.Times) != 0 && retries >= this.options.RetryTimes - 1)
{
shouldRetry = false;
}
if (shouldRetry && (this.options.Type & RetryType.For) != 0 &&
DateTime.UtcNow - now > this.options.RetryFor)
{
shouldRetry = false;
}
if (shouldRetry && (this.options.Type & RetryType.Until) != 0 && this.options.RetryUntil(
retries,
now,
exceptions,
this.options))
{
shouldRetry = false;
}
if (shouldRetry)
{
retries++;
}
}
return shouldRetry;
}
private TimeSpan GetRetryTimeSpan(
int retries,
DateTime now) =>
this.options.WaitBetweenRetriesType switch
{
WaitType.For when this.options.WaitForDuration.HasValue => this.options.WaitForDuration.Value,
WaitType.Until => this.options.WaitUntilDelegate.Invoke(
retries,
now,
this.options),
_ => TimeSpan.Zero
};
}
}
| |
#region Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com>
/// <copyright>
/// Copyright (c) 2007 Ryan Williams <drcforbin@gmail.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.
/// </copyright>
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using Mono.Cecil;
using Mono.Security.Cryptography;
using System.Security.Cryptography;
namespace Obfuscar
{
class Project : IEnumerable<AssemblyInfo>
{
private const string SPECIALVAR_PROJECTFILEDIRECTORY = "ProjectFileDirectory";
private readonly List<AssemblyInfo> assemblyList = new List<AssemblyInfo> ();
public List<AssemblyInfo> CopyAssemblyList {
get {
return copyAssemblyList;
}
}
private readonly List<AssemblyInfo> copyAssemblyList = new List<AssemblyInfo> ();
private readonly Dictionary<string, AssemblyInfo> assemblyMap = new Dictionary<string, AssemblyInfo> ();
private readonly Variables vars = new Variables ();
InheritMap inheritMap;
Settings settings;
// FIXME: Figure out why this exists if it is never used.
private RSA keyvalue;
// don't create. call FromXml.
private Project ()
{
}
public string [] ExtraPaths {
get {
return vars.GetValue ("ExtraFrameworkFolders", "").Split (new char [] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
}
}
public string KeyContainerName = null;
public RSA KeyValue {
get {
if (keyvalue != null)
return keyvalue;
var lKeyFileName = vars.GetValue ("KeyFile", null);
var lKeyContainerName = vars.GetValue ("KeyContainer", null);
if (lKeyFileName == null && lKeyContainerName == null)
return null;
if (lKeyFileName != null && lKeyContainerName != null)
throw new Exception ("'Key file' and 'Key container' properties cann't be setted together.");
if (vars.GetValue ("KeyContainer", null) != null) {
KeyContainerName = vars.GetValue ("KeyContainer", null);
return RSA.Create ();
//if (Type.GetType("System.MonoType") != null)
// throw new Exception("Key containers are not supported for Mono.");
//try
//{
// CspParameters cp = new CspParameters();
// cp.KeyContainerName = vars.GetValue("KeyContainer", null);
// cp.Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey;
// cp.KeyNumber = 1;
// RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// keyvalue = CryptoConvert.FromCapiKeyBlob(rsa.ExportCspBlob(false));
//}
//catch (Exception CryptEx)
////catch (System.Security.Cryptography.CryptographicException CryptEx)
//{
// try
// {
// CspParameters cp = new CspParameters();
// cp.KeyContainerName = vars.GetValue("KeyContainer", null);
// cp.Flags = CspProviderFlags.UseExistingKey;
// cp.KeyNumber = 1;
// RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
// keyvalue = CryptoConvert.FromCapiKeyBlob(rsa.ExportCspBlob(false));
// }
// catch
// {
// throw new ApplicationException(String.Format("Failure loading key from container - \"{0}\"", vars.GetValue("KeyContainer", null)), CryptEx);
// }
//}
} else {
try {
keyvalue = CryptoConvert.FromCapiKeyBlob (File.ReadAllBytes (vars.GetValue ("KeyFile", null)));
} catch (Exception ex) {
throw new ApplicationException (String.Format ("Failure loading key file \"{0}\"", vars.GetValue ("KeyFile", null)), ex);
}
}
return keyvalue;
}
}
AssemblyCache m_cache;
internal AssemblyCache Cache
{
get
{
if (m_cache == null)
{
m_cache = new AssemblyCache(this);
}
return m_cache;
}
}
public static Project FromXml (XmlReader reader, string projectFileDirectory)
{
Project project = new Project ();
project.vars.Add (SPECIALVAR_PROJECTFILEDIRECTORY, string.IsNullOrEmpty (projectFileDirectory) ? "." : projectFileDirectory);
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
switch (reader.Name) {
case "Var":
{
string name = Helper.GetAttribute (reader, "name");
if (name.Length > 0) {
string value = Helper.GetAttribute (reader, "value");
if (value.Length > 0)
project.vars.Add (name, value);
else
project.vars.Remove (name);
}
break;
}
case "Module":
AssemblyInfo info = AssemblyInfo.FromXml (project, reader, project.vars);
if (info.Exclude) {
project.copyAssemblyList.Add (info);
break;
}
Console.WriteLine ("Processing assembly: " + info.Definition.Name.FullName);
project.assemblyList.Add (info);
project.assemblyMap [info.Name] = info;
break;
}
}
}
return project;
}
/// <summary>
/// Looks through the settings, trys to make sure everything looks ok.
/// </summary>
public void CheckSettings ()
{
if (!Directory.Exists (Settings.InPath))
throw new ApplicationException ("Path specified by InPath variable must exist:" + Settings.InPath);
if (!Directory.Exists (Settings.OutPath)) {
try {
Directory.CreateDirectory (Settings.OutPath);
} catch (IOException e) {
throw new ApplicationException ("Could not create path specified by OutPath: " + Settings.OutPath, e);
}
}
}
internal InheritMap InheritMap {
get { return inheritMap; }
}
internal Settings Settings {
get {
if (settings == null)
settings = new Settings (vars);
return settings;
}
}
public void LoadAssemblies ()
{
// build reference tree
foreach (AssemblyInfo info in assemblyList) {
// add self reference...makes things easier later, when
// we need to go through the member references
info.ReferencedBy.Add (info);
// try to get each assembly referenced by this one. if it's in
// the map (and therefore in the project), set up the mappings
foreach (AssemblyNameReference nameRef in info.Definition.MainModule.AssemblyReferences) {
AssemblyInfo reference;
if (assemblyMap.TryGetValue (nameRef.Name, out reference)) {
info.References.Add (reference);
reference.ReferencedBy.Add (info);
}
}
}
// make each assembly's list of member refs
foreach (AssemblyInfo info in assemblyList) {
info.Init ();
}
// build inheritance map
inheritMap = new InheritMap (this);
}
/// <summary>
/// Returns whether the project contains a given type.
/// </summary>
public bool Contains (TypeReference type)
{
string name = Helper.GetScopeName (type);
return assemblyMap.ContainsKey (name);
}
/// <summary>
/// Returns whether the project contains a given type.
/// </summary>
internal bool Contains (TypeKey type)
{
return assemblyMap.ContainsKey (type.Scope);
}
public TypeDefinition GetTypeDefinition (TypeReference type)
{
if (type == null)
return null;
TypeDefinition typeDef = type as TypeDefinition;
if (typeDef == null) {
string name = Helper.GetScopeName (type);
AssemblyInfo info;
if (assemblyMap.TryGetValue (name, out info)) {
string fullName = type.Namespace + "." + type.Name;
typeDef = info.Definition.MainModule.GetType (fullName);
}
}
return typeDef;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return assemblyList.GetEnumerator ();
}
public IEnumerator<AssemblyInfo> GetEnumerator ()
{
return assemblyList.GetEnumerator ();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// Goal: Test arrays of doubles are allocated on large object heap and therefore 8 byte aligned
// Assumptions:
// 1) large object heap is always 8 byte aligned
// 2) double array greater than 1000 elements is on large object heap
// 3) non-double array greater than 1000 elements but less than 85K is NOT on large object heap
// 4) new arrays allocated in large object heap is of generation 2
// 5) new arrays NOT allocated in large object heap is of generation 0
// 6) the threshold can be set by registry key DoubleArrayToLargeObjectHeap
using System;
internal class DblArray
{
private static int s_LOH_GEN = 0;
public static void f0()
{
double[] arr = new double[1000];
if (GC.GetGeneration(arr) != s_LOH_GEN)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f1a()
{
float[] arr = new float[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f1b()
{
float[] arr = new float[3000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f2a()
{
decimal[] arr = new decimal[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f2b()
{
decimal[] arr = new decimal[3000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f3a()
{
long[] arr = new long[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f3b()
{
long[] arr = new long[3000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f4a()
{
ulong[] arr = new ulong[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f4b()
{
ulong[] arr = new ulong[3000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f5a()
{
int[] arr = new int[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f5b()
{
int[] arr = new int[3000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f6a()
{
uint[] arr = new uint[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f6b()
{
uint[] arr = new uint[3000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f7a()
{
short[] arr = new short[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f7b()
{
short[] arr = new short[5000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f8a()
{
ushort[] arr = new ushort[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f8b()
{
ushort[] arr = new ushort[5000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f9a()
{
byte[] arr = new byte[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f9b()
{
byte[] arr = new byte[10000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f10a()
{
sbyte[] arr = new sbyte[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f10b()
{
sbyte[] arr = new sbyte[10000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f11a()
{
char[] arr = new char[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f11b()
{
char[] arr = new char[10000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f12a()
{
bool[] arr = new bool[1000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static void f12b()
{
bool[] arr = new bool[10000];
if (GC.GetGeneration(arr) != 0)
{
Console.WriteLine("Generation {0}", GC.GetGeneration(arr));
throw new Exception();
}
}
public static int Main()
{
if (Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "x86")
{
s_LOH_GEN = 2;
}
try
{
f0();
f1a();
f2a();
f3a();
f4a();
f5a();
f6a();
f7a();
f8a();
f9a();
f10a();
f11a();
f12a();
f1b();
f2b();
f3b();
f4b();
f5b();
f6b();
f7b();
f8b();
f9b();
f10b();
f11b();
f12b();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.WriteLine("FAILED");
Console.WriteLine();
Console.WriteLine(@"// Goal: Test arrays of doubles are allocated on large object heap and therefore 8 byte aligned
// Assumptions:
// 1) large object heap is always 8 byte aligned
// 2) double array greater than 1000 elements is on large object heap
// 3) non-double array greater than 1000 elements but less than 85K is NOT on large object heap
// 4) new arrays allocated in large object heap is of generation 2
// 5) new arrays NOT allocated in large object heap is of generation 0 ");
return -1;
}
Console.WriteLine("PASSED");
return 100;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Common.Logging;
using Ninject;
namespace NuGet.Server.Infrastructure.Lucene
{
public class PackageFileSystemWatcher : IInitializable, IDisposable
{
public static ILog Log = LogManager.GetLogger<PackageFileSystemWatcher>();
private FileSystemWatcher fileWatcher;
private IDisposable fileObserver;
private IDisposable dirObserver;
[Inject]
public IFileSystem FileSystem { get; set; }
[Inject]
public ILucenePackageRepository PackageRepository { get; set; }
[Inject]
public IPackageIndexer Indexer { get; set; }
/// <summary>
/// Sets the amount of time to wait after receiving a <c cref="FileSystemWatcher.Changed">Changed</c>
/// event before attempting to index a package. This timeout is meant to avoid trying to read a package
/// while it is still being built or copied into place.
/// </summary>
public TimeSpan QuietTime { get; set; }
public PackageFileSystemWatcher()
{
QuietTime = TimeSpan.FromSeconds(3);
}
public void Initialize()
{
fileWatcher = new FileSystemWatcher(FileSystem.Root, "*.nupkg")
{
NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite,
IncludeSubdirectories = true,
};
var modifiedFilesThrottledByPath = ModifiedFiles
.Select(args => args.EventArgs.FullPath)
.GroupBy(path => path)
.Select(groupByPath => groupByPath.Throttle(QuietTime))
.SelectMany(obs => obs);
#pragma warning disable 4014 // Because this call is not awaited, execution of the current method continues before the call is completed.
fileObserver = modifiedFilesThrottledByPath.Subscribe(path => OnPackageModified(path));
fileWatcher.Deleted += (s, e) => OnPackageDeleted(e.FullPath);
fileWatcher.Renamed += (s, e) => OnPackageRenamed(e.OldFullPath, e.FullPath);
#pragma warning restore 4014
fileWatcher.EnableRaisingEvents = true;
dirObserver = MovedDirectories.Select(args => args.EventArgs.FullPath).Throttle(QuietTime).Subscribe(OnDirectoryMoved);
}
public void Dispose()
{
fileObserver.Dispose();
fileWatcher.Dispose();
dirObserver.Dispose();
}
public void OnDirectoryMoved(string fullPath)
{
try
{
if (FileSystem.GetFiles(fullPath, "*.nupkg", true).IsEmpty()) return;
}
catch (IOException ex)
{
Log.Error(ex);
return;
}
Indexer.SynchronizeIndexWithFileSystem();
}
public async Task OnPackageModified(string fullPath)
{
Log.Info(m => m("Indexing modified package " + fullPath));
await AddToIndex(fullPath).ContinueWith(LogOnFault);
}
public async Task OnPackageRenamed(string oldFullPath, string fullPath)
{
Log.Info(m => m("Package path {0} renamed to {1}.", oldFullPath, fullPath));
var task = RemoveFromIndex(oldFullPath).ContinueWith(LogOnFault);
if (fullPath.EndsWith(Constants.PackageExtension))
{
var addToIndex = AddToIndex(fullPath).ContinueWith(LogOnFault);
await Task.WhenAll(addToIndex, task);
return;
}
await task;
}
public async Task OnPackageDeleted(string fullPath)
{
Log.Info(m => m("Package path {0} deleted.", fullPath));
await RemoveFromIndex(fullPath).ContinueWith(LogOnFault);
}
private async Task AddToIndex(string fullPath)
{
var tasks = new List<Task>();
Action checkTimestampAndIndexPackage = () =>
{
var existingPackage = PackageRepository.LoadFromIndex(fullPath);
var flag = (existingPackage == null ||
IndexDifferenceCalculator.TimestampsMismatch(existingPackage,
FileSystem.GetLastModified(fullPath)));
if (!flag) return;
var package = PackageRepository.LoadFromFileSystem(fullPath);
tasks.Add(Indexer.AddPackage(package));
};
tasks.Add(Task.Factory.StartNew(checkTimestampAndIndexPackage));
await Task.WhenAll(tasks);
}
private async Task RemoveFromIndex(string fullPath)
{
var package = PackageRepository.LoadFromIndex(fullPath);
if (package != null)
{
await Indexer.RemovePackage(package);
}
}
private void LogOnFault(Task task)
{
if (task.IsFaulted)
{
Log.Error(task.Exception);
}
}
private IObservable<EventPattern<FileSystemEventArgs>> ModifiedFiles
{
get
{
var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
eh => eh.Invoke,
eh => fileWatcher.Created += eh,
eh => fileWatcher.Created -= eh);
var changed = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
eh => eh.Invoke,
eh => fileWatcher.Changed += eh,
eh => fileWatcher.Changed -= eh);
return created.Merge(changed);
}
}
private IObservable<EventPattern<FileSystemEventArgs>> MovedDirectories
{
get
{
Func<FileSystemWatcher> createDirWatcher = () =>
new FileSystemWatcher(FileSystem.Root)
{
NotifyFilter = NotifyFilters.DirectoryName,
IncludeSubdirectories = true,
EnableRaisingEvents = true
};
Func<FileSystemWatcher, IObservable<EventPattern<FileSystemEventArgs>>> createObservable = dirWatcher =>
{
var created = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
eh => eh.Invoke,
eh => dirWatcher.Created += eh,
eh => dirWatcher.Created -= eh);
var renamed = Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(
eh => eh.Invoke,
eh => dirWatcher.Renamed += eh,
eh => dirWatcher.Renamed -= eh);
return created.Merge(renamed.Select(re => new EventPattern<FileSystemEventArgs>(re.Sender, re.EventArgs)));
};
return Observable.Using(createDirWatcher, createObservable);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class XObjectBuilderTest : BridgeHelpers
{
//[Variation(Priority = 2, Desc = "LookupPrefix(null)")]
public void var_1()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
string prefix = w.LookupPrefix(null);
}
catch (ArgumentNullException e)
{
TestLog.Compare(e.ParamName, "ns", "prefix mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
string prefix = w.LookupPrefix(null);
}
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, "ns", "prefix mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteAttributes(null, true)", Param = true)]
//[Variation(Priority = 2, Desc = "WriteAttributes(null, false)", Param = false)]
public void var_2()
{
XDocument doc = new XDocument();
bool defattr = (bool)Variation.Param;
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteAttributes(null, defattr);
}
catch (ArgumentNullException e)
{
TestLog.Compare(e.ParamName, "reader", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteAttributes(null, defattr);
}
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
TestLog.Compare(ae.ParamName, "reader", "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteAttributeString(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteAttributeString(String.Empty)", Param = "")]
public void var_3()
{
XDocument doc = new XDocument();
string name = (string)Variation.Param;
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteAttributeString(name, null);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteAttributeString(name, null);
}
catch (ArgumentException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(e.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteBase64(null)")]
public void var_4()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteBase64(null, 0, 0);
}
catch (ArgumentNullException e)
{
TestLog.Compare(e.ParamName, "buffer", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteBase64(null, 0, 0);
}
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, "buffer", "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteBinHex(null)")]
public void var_5()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
w.WriteStartDocument();
w.WriteStartElement("a");
try
{
TestLog.Compare(w.WriteState, WriteState.Element, "Error");
w.WriteBinHex(null, 0, 0);
}
catch (ArgumentNullException e)
{
TestLog.Compare(e.ParamName, "buffer", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteBinHex(null, 0, 0);
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteCData(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteCData('')", Param = "")]
public void var_6()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteCData(param);
}
catch (InvalidOperationException)
{
try
{
w.WriteCData(param);
}
catch (InvalidOperationException) { return; }
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteChars(null)")]
public void var_7()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteChars(null, 0, 0);
}
catch (ArgumentNullException)
{
try
{
w.WriteChars(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "Other APIs")]
public void var_8()
{
XDocument doc = new XDocument();
XmlWriter w = CreateWriter(doc);
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteComment(null);
TestLog.Compare(w.Equals(null), false, "Error");
w.WriteComment("");
w.LookupPrefix("");
TestLog.Compare(w.Equals(""), false, "Error");
TestLog.Compare(w.WriteState, WriteState.Prolog, "Error");
w.Flush();
w.Dispose();
TestLog.Compare(w.WriteState, WriteState.Closed, "Error");
w.Flush();
w.Dispose();
TestLog.Compare(w.WriteState, WriteState.Closed, "Error");
}
//[Variation(Priority = 2, Desc = "WriteDocType(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteDocType('')", Param = "")]
public void var_9()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteDocType(param, param, param, param);
}
catch (ArgumentException)
{
try
{
w.WriteDocType(param, param, param, param);
}
catch (ArgumentException) { return; }
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteElementString(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteElementString(String.Empty)", Param = "")]
public void var_10()
{
XDocument doc = new XDocument();
string name = (string)Variation.Param;
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteElementString(name, null, null, null);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteElementString(name, null, null, null);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteEndAttribute()")]
public void var_11()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteEndAttribute();
}
catch (InvalidOperationException)
{
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteEndAttribute();
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteEndDocument()")]
public void var_12()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteEndDocument();
}
catch (InvalidOperationException)
{
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteEndDocument();
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteEndElement()")]
public void var_13()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteEndElement();
}
catch (InvalidOperationException)
{
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteEndElement();
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteEntityRef(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteEntityRef('')", Param = "")]
public void var_14()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteEntityRef(param);
}
catch (ArgumentException)
{
try
{
w.WriteEntityRef(param);
}
catch (ArgumentException)
{
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteFullEndElement()")]
public void var_15()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteFullEndElement();
}
catch (InvalidOperationException)
{
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteFullEndElement();
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteName(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteName('')", Param = "")]
public void var_16()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteName(param);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, "name", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteName(param);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
TestLog.Compare(ae.ParamName, "name", "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteNmToken(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteNmToken('')", Param = "")]
public void var_17()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteNmToken(param);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteNmToken(param);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
TestLog.Compare(ae.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "reader", true })]
//[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "reader", false })]
//[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "navigator", true })]
//[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "navigator", false })]
public void var_18()
{
string param1 = (string)Variation.Params[0];
bool param2 = (bool)Variation.Params[1];
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
switch (param1)
{
case ("reader"):
w.WriteNode((XmlReader)null, param2);
break;
}
}
catch (ArgumentNullException e)
{
switch (param1)
{
case ("reader"):
TestLog.Compare(e.ParamName, "reader", "mismatch");
break;
case ("navigator"):
TestLog.Compare(e.ParamName, "navigator", "mismatch");
break;
}
try
{
switch (param1)
{
case ("reader"):
w.WriteNode((XmlReader)null, param2);
break;
}
}
catch (ArgumentNullException)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
switch (param1)
{
case ("reader"):
TestLog.Compare(e.ParamName, "reader", "mismatch");
break;
}
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteProcessingInstruction(null, null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteProcessingInstruction('', '')", Param = "")]
public void var_19()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteProcessingInstruction(param, param);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteProcessingInstruction(param, param);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteQualifiedName(null, null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteQualifiedName('', '')", Param = "")]
public void var_20()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteQualifiedName(param, param);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteQualifiedName(param, param);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteRaw(null, 0, 0)")]
public void var_21()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteRaw(null, 0, 0);
}
catch (ArgumentNullException e)
{
TestLog.Compare(e.ParamName, "buffer", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteRaw(null, 0, 0);
}
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, "buffer", "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteStartAttribute(null, null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteStartAttribute('', '')", Param = "")]
public void var_22()
{
XDocument doc = new XDocument();
string param = (string)Variation.Param;
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartAttribute(param, param);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteStartAttribute(param, param);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteStartElement(null, null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteStartElement('', '')", Param = "")]
public void var_23()
{
XDocument doc = new XDocument();
string param = (string)Variation.Param;
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartElement(param);
}
catch (ArgumentException e)
{
TestLog.Compare(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteStartElement(param);
}
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
TestLog.Compare(ae.ParamName, null, "mismatch");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteStartDocument()", Param = 1)]
//[Variation(Priority = 2, Desc = "WriteStartDocument(true)", Param = 2)]
//[Variation(Priority = 2, Desc = "WriteStartDocument(false)", Param = 3)]
public void var_24()
{
XDocument doc = new XDocument();
XmlWriter w = CreateWriter(doc);
int param = (int)Variation.Param;
switch (param)
{
case 1: w.WriteStartDocument(); break;
case 2: w.WriteStartDocument(true); break;
case 3: w.WriteStartDocument(false); break;
default: throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(w.WriteState, WriteState.Prolog, "Error");
w.WriteStartElement("a");
TestLog.Compare(w.WriteState, WriteState.Element, "Error");
w.Dispose();
TestLog.Compare(w.WriteState, WriteState.Closed, "Error");
if (doc.ToString() != "<a />")
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteString(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteString('')", Param = "")]
public void var_25()
{
XDocument doc = new XDocument();
string param = (string)Variation.Param;
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteString(param);
}
catch (InvalidOperationException)
{
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteString(param);
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
if (param == null)
throw;
else
return;
}
}
}
if (param == null)
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteValue(true)", Param = true)]
//[Variation(Priority = 2, Desc = "WriteValue(false)", Param = false)]
public void var_26()
{
bool param = (bool)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteValue(param);
}
catch (InvalidOperationException)
{
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
w.WriteValue(param);
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
}
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "WriteWhitespace(null)", Param = null)]
//[Variation(Priority = 2, Desc = "WriteWhitespace('')", Param = "")]
public void var_27()
{
string param = (string)Variation.Param;
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
w.WriteWhitespace(param);
TestLog.Compare(w.WriteState, WriteState.Prolog, "Error");
}
}
//[Variation(Priority = 2, Desc = "EntityRef after Document should error - PROLOG")]
public void var_28()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteEntityRef("ent");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteEntityRef("ent");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "EntityRef after Document should error - EPILOG")]
public void var_29()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
TestLog.Compare(w.WriteState, WriteState.Prolog, "Error");
w.WriteStartElement("Root");
TestLog.Compare(w.WriteState, WriteState.Element, "Error");
w.WriteEndElement();
TestLog.Compare(w.WriteState, WriteState.Content, "Error");
w.WriteEntityRef("ent");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteEntityRef("ent");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "CharEntity after Document should error - PROLOG")]
public void var_30()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteCharEntity('\uD23E');
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteCharEntity('\uD23E');
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "CharEntity after Document should error - EPILOG")]
public void var_31()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteStartElement("Root");
w.WriteEndElement();
w.WriteCharEntity('\uD23E');
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteCharEntity('\uD23E');
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "SurrogateCharEntity after Document should error - PROLOG")]
public void var_32()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteSurrogateCharEntity('\uDF41', '\uD920');
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteSurrogateCharEntity('\uDF41', '\uD920');
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "SurrogateCharEntity after Document should error - EPILOG")]
public void var_33()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteStartElement("Root");
w.WriteEndElement();
w.WriteSurrogateCharEntity('\uDF41', '\uD920');
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteSurrogateCharEntity('\uDF41', '\uD920');
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "Attribute after Document should error - PROLOG")]
public void var_34()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteStartAttribute("attr", "");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteStartAttribute("attr", "");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "Attribute after Document should error - EPILOG")]
public void var_35()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
w.WriteStartDocument();
w.WriteStartElement("Root");
w.WriteEndElement();
w.WriteStartAttribute("attr", "");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteStartAttribute("attr", "");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "CDATA after Document should error - PROLOG")]
public void var_36()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteStartDocument();
TestLog.Compare(w.WriteState, WriteState.Prolog, "Error");
w.WriteCData("Invalid");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteCData("Invalid");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
}
//[Variation(Priority = 2, Desc = "CDATA after Document should error - EPILOG")]
public void var_37()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteStartDocument();
w.WriteStartElement("Root");
w.WriteEndElement();
TestLog.Compare(w.WriteState, WriteState.Content, "Error");
w.WriteCData("Invalid");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteCData("Invalid");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "Element followed by Document should error")]
public void var_38()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteStartElement("Root");
TestLog.Compare(w.WriteState, WriteState.Element, "Error");
w.WriteStartDocument();
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteStartDocument();
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 2, Desc = "Element followed by DocType should error")]
public void var_39()
{
XDocument doc = new XDocument();
using (XmlWriter w = CreateWriter(doc))
{
try
{
w.WriteStartElement("Root");
TestLog.Compare(w.WriteState, WriteState.Element, "Error");
w.WriteDocType("Test", null, null, "");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
try
{
w.WriteDocType("Test", null, null, "");
}
catch (InvalidOperationException) { return; }
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "WriteBase64")]
public void Variation41()
{
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int readByte = 1;
XDocument d = new XDocument();
XmlWriter xw = d.CreateWriter();
TestLog.Compare(xw.WriteState, WriteState.Start, "Error");
xw.WriteStartDocument(true);
TestLog.Compare(xw.WriteState, WriteState.Prolog, "Error");
xw.WriteStartElement("root");
TestLog.Compare(xw.WriteState, WriteState.Element, "Error");
try
{
xw.WriteBase64(buffer, 0, readByte);
}
catch (NotSupportedException)
{
TestLog.Compare(xw.WriteState, WriteState.Error, "Error");
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Desc = "WriteEntityRef")]
public void Variation42()
{
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
try
{
w.WriteEntityRef("ent");
}
catch (NotSupportedException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
return;
}
throw new TestException(TestResult.Failed, "");
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.