context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//
// Authors:
// Ben Motmans <ben.motmans@gmail.com>
//
// Copyright (c) 2007 Ben Motmans
//
// 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 Gtk;
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Components;
using MonoDevelop.Database.Sql;
using MonoDevelop.Database.Components;
namespace MonoDevelop.Database.Designer
{
public partial class ProcedureEditorDialog : Gtk.Dialog
{
private SchemaActions action;
private Notebook notebook;
private IEditSchemaProvider schemaProvider;
private ProcedureSchema procedure;
private CommentEditorWidget commentEditor;
private SqlEditorWidget sqlEditor;
private ProcedureEditorSettings settings;
public ProcedureEditorDialog (IEditSchemaProvider schemaProvider, bool create, ProcedureEditorSettings settings)
{
if (schemaProvider == null)
throw new ArgumentNullException ("schemaProvider");
this.settings = settings;
this.schemaProvider = schemaProvider;
this.action = create ? SchemaActions.Create : SchemaActions.Alter;
this.Build();
if (create)
Title = AddinCatalog.GetString ("Create Procedure");
else
Title = AddinCatalog.GetString ("Alter Procedure");
notebook = new Notebook ();
sqlEditor = new SqlEditorWidget ();
sqlEditor.TextChanged += new EventHandler (SqlChanged);
notebook.AppendPage (sqlEditor, new Label (AddinCatalog.GetString ("Definition")));
if (settings.ShowComment) {
commentEditor = new CommentEditorWidget ();
notebook.AppendPage (commentEditor, new Label (AddinCatalog.GetString ("Comment")));
}
if (!settings.ShowName) {
nameLabel.Visible = false;
entryName.Visible = false;
}
vboxContent.PackStart (notebook, true, true, 0);
vboxContent.ShowAll ();
SetWarning (null);
}
public void Initialize (ProcedureSchema procedure)
{
if (procedure == null)
throw new ArgumentNullException ("procedure");
this.procedure = procedure;
entryName.Text = procedure.Name;
if (action == SchemaActions.Alter) {
sqlEditor.Text = schemaProvider.GetProcedureAlterStatement (procedure);
if (commentEditor != null)
commentEditor.Comment = procedure.Comment;
} else
sqlEditor.Text = procedure.Definition;
}
protected virtual void OkClicked (object sender, EventArgs e)
{
if (settings.ShowName)
procedure.Name = entryName.Text;
procedure.Definition = sqlEditor.Text;
if (settings.ShowComment)
procedure.Comment = commentEditor.Comment;
Respond (ResponseType.Ok);
Hide ();
}
protected virtual void CancelClicked (object sender, EventArgs e)
{
Respond (ResponseType.Cancel);
Hide ();
}
protected virtual void NameChanged (object sender, EventArgs e)
{
CheckState ();
}
protected virtual void SqlChanged (object sender, EventArgs e)
{
CheckState ();
}
private void CheckState ()
{
buttonOk.Sensitive = entryName.Text.Length > 0 && sqlEditor.Text.Length > 0;
//TODO: check for duplicate name
}
protected virtual void SetWarning (string msg)
{
if (msg == null) {
hboxWarning.Hide ();
labelWarning.Text = "";
} else {
hboxWarning.ShowAll ();
labelWarning.Text = msg;
}
}
protected virtual void OnButtonSaveClicked (object sender, System.EventArgs e)
{
FileChooserDialog dlg = new FileChooserDialog (
AddinCatalog.GetString ("Save Script"), null, FileChooserAction.Save,
"gtk-cancel", ResponseType.Cancel,
"gtk-save", ResponseType.Accept
);
dlg.SelectMultiple = false;
dlg.LocalOnly = true;
dlg.Modal = true;
FileFilter filter = new FileFilter ();
filter.AddPattern ("*.sql");
filter.Name = AddinCatalog.GetString ("SQL Scripts");
FileFilter filterAll = new FileFilter ();
filterAll.AddPattern ("*");
filterAll.Name = AddinCatalog.GetString ("All files");
dlg.AddFilter (filter);
dlg.AddFilter (filterAll);
try {
if (dlg.Run () == (int)ResponseType.Accept) {
if (File.Exists (dlg.Filename)) {
if (!MessageService.Confirm (AddinCatalog.GetString (@"File {0} already exists.
Do you want to overwrite\nthe existing file?", dlg.Filename),
AlertButton.Yes))
return;
else
File.Delete (dlg.Filename);
}
using (StreamWriter writer = File.CreateText (dlg.Filename)) {
writer.Write (sqlEditor.Text);
writer.Close ();
}
}
} finally {
dlg.Destroy ();
}
}
protected virtual void OnButtonOpenClicked (object sender, System.EventArgs e)
{
FileChooserDialog dlg = new FileChooserDialog (
AddinCatalog.GetString ("Open Script"), null, FileChooserAction.Open,
"gtk-cancel", ResponseType.Cancel,
"gtk-open", ResponseType.Accept
);
dlg.SelectMultiple = false;
dlg.LocalOnly = true;
dlg.Modal = true;
FileFilter filter = new FileFilter ();
filter.AddPattern ("*.sql");
filter.Name = AddinCatalog.GetString ("SQL Scripts");
FileFilter filterAll = new FileFilter ();
filterAll.AddPattern ("*");
filterAll.Name = AddinCatalog.GetString ("All files");
dlg.AddFilter (filter);
dlg.AddFilter (filterAll);
try {
if (dlg.Run () == (int)ResponseType.Accept) {
using (StreamReader reader = File.OpenText (dlg.Filename)) {
sqlEditor.Text = reader.ReadToEnd ();
reader.Close ();
}
}
} finally {
dlg.Destroy ();
}
}
}
public class ProcedureEditorSettings
{
bool showComment = false;
bool showName = true;
public bool ShowComment {
get { return showComment; }
set { showComment = value; }
}
public bool ShowName {
get { return showName; }
set { showName = value; }
}
}
}
| |
// Generated by TinyPG v1.2 available at www.codeproject.com
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Rawr.Mage.StateDescription
{
#region Scanner
public partial class Scanner
{
public string Input;
public int StartPos = 0;
public int EndPos = 0;
public int CurrentLine;
public int CurrentColumn;
public int CurrentPosition;
public List<Token> Skipped; // tokens that were skipped
public Dictionary<TokenType, Regex> Patterns;
private Token LookAheadToken;
private List<TokenType> Tokens;
private List<TokenType> SkipList; // tokens to be skipped
public Scanner()
{
Regex regex;
Patterns = new Dictionary<TokenType, Regex>();
Tokens = new List<TokenType>();
LookAheadToken = null;
SkipList = new List<TokenType>();
#if SILVERLIGHT
RegexOptions ropt = RegexOptions.None;
#else
RegexOptions ropt = RegexOptions.Compiled;
#endif
regex = new Regex(@"[^\(\)!\|\+-]+", ropt);
Patterns.Add(TokenType.STATE, regex);
Tokens.Add(TokenType.STATE);
regex = new Regex(@"\|", ropt);
Patterns.Add(TokenType.INTERSECTION, regex);
Tokens.Add(TokenType.INTERSECTION);
regex = new Regex(@"\+", ropt);
Patterns.Add(TokenType.UNION, regex);
Tokens.Add(TokenType.UNION);
regex = new Regex(@"-", ropt);
Patterns.Add(TokenType.DIFFERENCE, regex);
Tokens.Add(TokenType.DIFFERENCE);
regex = new Regex(@"!", ropt);
Patterns.Add(TokenType.COMPLEMENT, regex);
Tokens.Add(TokenType.COMPLEMENT);
regex = new Regex(@"\(", ropt);
Patterns.Add(TokenType.BROPEN, regex);
Tokens.Add(TokenType.BROPEN);
regex = new Regex(@"\)", ropt);
Patterns.Add(TokenType.BRCLOSE, regex);
Tokens.Add(TokenType.BRCLOSE);
regex = new Regex(@"^$", ropt);
Patterns.Add(TokenType.EOF, regex);
Tokens.Add(TokenType.EOF);
}
public void Init(string input)
{
this.Input = input;
StartPos = 0;
EndPos = 0;
CurrentLine = 0;
CurrentColumn = 0;
CurrentPosition = 0;
Skipped = new List<Token>();
LookAheadToken = null;
}
public Token GetToken(TokenType type)
{
Token t = new Token(this.StartPos, this.EndPos);
t.Type = type;
return t;
}
/// <summary>
/// executes a lookahead of the next token
/// and will advance the scan on the input string
/// </summary>
/// <returns></returns>
public Token Scan(params TokenType[] expectedtokens)
{
Token tok = LookAhead(expectedtokens); // temporarely retrieve the lookahead
LookAheadToken = null; // reset lookahead token, so scanning will continue
StartPos = tok.EndPos;
EndPos = tok.EndPos; // set the tokenizer to the new scan position
return tok;
}
/// <summary>
/// returns token with longest best match
/// </summary>
/// <returns></returns>
public Token LookAhead(params TokenType[] expectedtokens)
{
int i;
int startpos = StartPos;
Token tok = null;
List<TokenType> scantokens;
// this prevents double scanning and matching
// increased performance
if (LookAheadToken != null
&& LookAheadToken.Type != TokenType._UNDETERMINED_
&& LookAheadToken.Type != TokenType._NONE_) return LookAheadToken;
// if no scantokens specified, then scan for all of them (= backward compatible)
if (expectedtokens.Length == 0)
scantokens = Tokens;
else
{
scantokens = new List<TokenType>(expectedtokens);
scantokens.AddRange(SkipList);
}
do
{
int len = -1;
TokenType index = (TokenType)int.MaxValue;
string input = Input.Substring(startpos);
tok = new Token(startpos, EndPos);
for (i = 0; i < scantokens.Count; i++)
{
Regex r = Patterns[scantokens[i]];
Match m = r.Match(input);
if (m.Success && m.Index == 0 && ((m.Length > len) || (scantokens[i] < index && m.Length == len )))
{
len = m.Length;
index = scantokens[i];
}
}
if (index >= 0 && len >= 0)
{
tok.EndPos = startpos + len;
tok.Text = Input.Substring(tok.StartPos, len);
tok.Type = index;
}
else
{
if (tok.StartPos < tok.EndPos - 1)
tok.Text = Input.Substring(tok.StartPos, 1);
}
if (SkipList.Contains(tok.Type))
{
startpos = tok.EndPos;
Skipped.Add(tok);
}
}
while (SkipList.Contains(tok.Type));
LookAheadToken = tok;
return tok;
}
}
#endregion
#region Token
public enum TokenType
{
//Non terminal tokens:
_NONE_ = 0,
_UNDETERMINED_= 1,
//Non terminal tokens:
Start = 2,
UnionExpr= 3,
DiffExpr= 4,
IntExpr = 5,
CompExpr= 6,
Atom = 7,
//Terminal tokens:
STATE = 8,
INTERSECTION= 9,
UNION = 10,
DIFFERENCE= 11,
COMPLEMENT= 12,
BROPEN = 13,
BRCLOSE = 14,
EOF = 15
}
public class Token
{
private int startpos;
private int endpos;
private string text;
private object value;
public int StartPos {
get { return startpos;}
set { startpos = value; }
}
public int Length {
get { return endpos - startpos;}
}
public int EndPos {
get { return endpos;}
set { endpos = value; }
}
public string Text {
get { return text;}
set { text = value; }
}
public object Value {
get { return value;}
set { this.value = value; }
}
public TokenType Type;
public Token()
: this(0, 0)
{
}
public Token(int start, int end)
{
Type = TokenType._UNDETERMINED_;
startpos = start;
endpos = end;
Text = ""; // must initialize with empty string, may cause null reference exceptions otherwise
Value = null;
}
public void UpdateRange(Token token)
{
if (token.StartPos < startpos) startpos = token.StartPos;
if (token.EndPos > endpos) endpos = token.EndPos;
}
public override string ToString()
{
if (Text != null)
return Type.ToString() + " '" + Text + "'";
else
return Type.ToString();
}
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Collections.Generic;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
namespace OpenSim.Framework.Serialization
{
/// <summary>
/// Constants for the archiving module
/// </summary>
public class ArchiveConstants
{
/// <value>
/// The location of the archive control file
/// </value>
public const string CONTROL_FILE_PATH = "archive.xml";
/// <value>
/// Path for the assets held in an archive
/// </value>
public const string ASSETS_PATH = "assets/";
/// <value>
/// Path for the inventory data
/// </value>
public const string INVENTORY_PATH = "inventory/";
/// <value>
/// Path for regions in a multi-region archive
/// </value>
public const string REGIONS_PATH = "regions/";
/// <value>
/// Path for the prims file
/// </value>
public const string OBJECTS_PATH = "objects/";
/// <value>
/// Path for terrains. Technically these may be assets, but I think it's quite nice to split them out.
/// </value>
public const string TERRAINS_PATH = "terrains/";
/// <value>
/// Path for region settings.
/// </value>
public const string SETTINGS_PATH = "settings/";
/// <value>
/// Path for region settings.
/// </value>
public const string LANDDATA_PATH = "landdata/";
/// <value>
/// Path for user profiles
/// </value>
public const string USERS_PATH = "userprofiles/";
/// <value>
/// The character the separates the uuid from extension information in an archived asset filename
/// </value>
public const string ASSET_EXTENSION_SEPARATOR = "_";
/// <value>
/// Used to separate components in an inventory node name
/// </value>
public const string INVENTORY_NODE_NAME_COMPONENT_SEPARATOR = "__";
/// <summary>
/// Template used for creating filenames in OpenSim Archives.
/// </summary>
public const string OAR_OBJECT_FILENAME_TEMPLATE = "{0}_{1:000}-{2:000}-{3:000}__{4}.xml";
/// <value>
/// Extensions used for asset types in the archive
/// </value>
public static readonly IDictionary<sbyte, string> ASSET_TYPE_TO_EXTENSION = new Dictionary<sbyte, string>();
public static readonly IDictionary<string, sbyte> EXTENSION_TO_ASSET_TYPE = new Dictionary<string, sbyte>();
static ArchiveConstants()
{
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Animation] = ASSET_EXTENSION_SEPARATOR + "animation.bvh";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Bodypart] = ASSET_EXTENSION_SEPARATOR + "bodypart.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.CallingCard] = ASSET_EXTENSION_SEPARATOR + "callingcard.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Clothing] = ASSET_EXTENSION_SEPARATOR + "clothing.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Folder] = ASSET_EXTENSION_SEPARATOR + "folder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Gesture] = ASSET_EXTENSION_SEPARATOR + "gesture.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.ImageJPEG] = ASSET_EXTENSION_SEPARATOR + "image.jpg";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.ImageTGA] = ASSET_EXTENSION_SEPARATOR + "image.tga";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Landmark] = ASSET_EXTENSION_SEPARATOR + "landmark.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.LostAndFoundFolder] = ASSET_EXTENSION_SEPARATOR + "lostandfoundfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.LSLBytecode] = ASSET_EXTENSION_SEPARATOR + "bytecode.lso";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.LSLText] = ASSET_EXTENSION_SEPARATOR + "script.lsl";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Mesh] = ASSET_EXTENSION_SEPARATOR + "mesh.llmesh";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Notecard] = ASSET_EXTENSION_SEPARATOR + "notecard.txt";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Object] = ASSET_EXTENSION_SEPARATOR + "object.xml";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.RootFolder] = ASSET_EXTENSION_SEPARATOR + "rootfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Simstate] = ASSET_EXTENSION_SEPARATOR + "simstate.bin"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SnapshotFolder] = ASSET_EXTENSION_SEPARATOR + "snapshotfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Sound] = ASSET_EXTENSION_SEPARATOR + "sound.ogg";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV] = ASSET_EXTENSION_SEPARATOR + "sound.wav";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.Texture] = ASSET_EXTENSION_SEPARATOR + "texture.jp2";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TextureTGA] = ASSET_EXTENSION_SEPARATOR + "texture.tga";
ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.TrashFolder] = ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"; // Not sure if we'll ever see this
ASSET_TYPE_TO_EXTENSION[(sbyte)OpenSimAssetType.Material] = ASSET_EXTENSION_SEPARATOR + "material.xml"; // Not sure if we'll ever see this
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "animation.bvh"] = (sbyte)AssetType.Animation;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bodypart.txt"] = (sbyte)AssetType.Bodypart;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "callingcard.txt"] = (sbyte)AssetType.CallingCard;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "clothing.txt"] = (sbyte)AssetType.Clothing;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "folder.txt"] = (sbyte)AssetType.Folder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "gesture.txt"] = (sbyte)AssetType.Gesture;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "image.jpg"] = (sbyte)AssetType.ImageJPEG;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "image.tga"] = (sbyte)AssetType.ImageTGA;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "landmark.txt"] = (sbyte)AssetType.Landmark;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "lostandfoundfolder.txt"] = (sbyte)AssetType.LostAndFoundFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "bytecode.lso"] = (sbyte)AssetType.LSLBytecode;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "script.lsl"] = (sbyte)AssetType.LSLText;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "mesh.llmesh"] = (sbyte)AssetType.Mesh;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "notecard.txt"] = (sbyte)AssetType.Notecard;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "object.xml"] = (sbyte)AssetType.Object;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "rootfolder.txt"] = (sbyte)AssetType.RootFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "simstate.bin"] = (sbyte)AssetType.Simstate;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "snapshotfolder.txt"] = (sbyte)AssetType.SnapshotFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "sound.ogg"] = (sbyte)AssetType.Sound;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "sound.wav"] = (sbyte)AssetType.SoundWAV;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.jp2"] = (sbyte)AssetType.Texture;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "texture.tga"] = (sbyte)AssetType.TextureTGA;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "trashfolder.txt"] = (sbyte)AssetType.TrashFolder;
EXTENSION_TO_ASSET_TYPE[ASSET_EXTENSION_SEPARATOR + "material.xml"] = (sbyte)OpenSimAssetType.Material;
}
public static string CreateOarLandDataPath(LandData ld)
{
return string.Format("{0}{1}.xml", ArchiveConstants.LANDDATA_PATH, ld.GlobalID);
}
/// <summary>
/// Create the filename used to store an object in an OpenSim Archive.
/// </summary>
/// <param name="objectName"></param>
/// <param name="uuid"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static string CreateOarObjectFilename(string objectName, UUID uuid, Vector3 pos)
{
return string.Format(
OAR_OBJECT_FILENAME_TEMPLATE, objectName,
Math.Round(pos.X), Math.Round(pos.Y), Math.Round(pos.Z),
uuid);
}
/// <summary>
/// Create the path used to store an object in an OpenSim Archives.
/// </summary>
/// <param name="objectName"></param>
/// <param name="uuid"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static string CreateOarObjectPath(string objectName, UUID uuid, Vector3 pos)
{
return OBJECTS_PATH + CreateOarObjectFilename(objectName, uuid, pos);
}
/// <summary>
/// Extract a plain path from an IAR path
/// </summary>
/// <param name="iarPath"></param>
/// <returns></returns>
public static string ExtractPlainPathFromIarPath(string iarPath)
{
List<string> plainDirs = new List<string>();
string[] iarDirs = iarPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string iarDir in iarDirs)
{
if (!iarDir.Contains(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR))
plainDirs.Add(iarDir);
int i = iarDir.LastIndexOf(ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR);
plainDirs.Add(iarDir.Remove(i));
}
return string.Join("/", plainDirs.ToArray());
}
}
}
| |
// 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.Globalization;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Guid : IFormattable, IComparable
, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
private int _a;
private short _b;
private short _c;
private byte _d;
private byte _e;
private byte _f;
private byte _g;
private byte _h;
private byte _i;
private byte _j;
private byte _k;
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
//
public Guid(byte[] b)
{
if (b == null)
throw new ArgumentNullException(nameof(b));
if (b.Length != 16)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b));
Contract.EndContractBlock();
_a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0];
_b = (short)(((int)b[5] << 8) | b[4]);
_c = (short)(((int)b[7] << 8) | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
_g = b[11];
_h = b[12];
_i = b[13];
_j = b[14];
_k = b[15];
}
[CLSCompliant(false)]
public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
_c = (short)c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
// Check that array is not too big
if (d.Length != 8)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d));
Contract.EndContractBlock();
_a = a;
_b = b;
_c = c;
_d = d[0];
_e = d[1];
_f = d[2];
_g = d[3];
_h = d[4];
_i = d[5];
_j = d[6];
_k = d[7];
}
// Creates a new GUID initialized to the value represented by the
// arguments. The bytes are specified like this to avoid endianness issues.
//
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = a;
_b = b;
_c = c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
[Flags]
private enum GuidStyles
{
None = 0x00000000,
AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
RequireDashes = 0x00000040, //Require the guid to contain dash group separators
RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
HexFormat = RequireBraces | RequireHexPrefix, /* X */
NumberFormat = None, /* N */
DigitFormat = RequireDashes, /* D */
BraceFormat = RequireBraces | RequireDashes, /* B */
ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
}
private enum GuidParseThrowStyle
{
None = 0,
All = 1,
AllButOverflow = 2
}
private enum ParseFailureKind
{
None = 0,
ArgumentNull = 1,
Format = 2,
FormatWithParameter = 3,
NativeException = 4,
FormatWithInnerException = 5
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult
{
internal Guid parsedGuid;
internal GuidParseThrowStyle throwStyle;
internal ParseFailureKind m_failure;
internal string m_failureMessageID;
internal object m_failureMessageFormatArgument;
internal string m_failureArgumentName;
internal Exception m_innerException;
internal void Init(GuidParseThrowStyle canThrow)
{
parsedGuid = Guid.Empty;
throwStyle = canThrow;
}
internal void SetFailure(Exception nativeException)
{
m_failure = ParseFailureKind.NativeException;
m_innerException = nativeException;
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID)
{
SetFailure(failure, failureMessageID, null, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
{
SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException)
{
Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
m_failureArgumentName = failureArgumentName;
m_innerException = innerException;
if (throwStyle != GuidParseThrowStyle.None)
{
throw GetGuidParseException();
}
}
internal Exception GetGuidParseException()
{
switch (m_failure)
{
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureArgumentName, SR.GetResourceString(m_failureMessageID));
case ParseFailureKind.FormatWithInnerException:
return new FormatException(SR.GetResourceString(m_failureMessageID), m_innerException);
case ParseFailureKind.FormatWithParameter:
return new FormatException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
case ParseFailureKind.Format:
return new FormatException(SR.GetResourceString(m_failureMessageID));
case ParseFailureKind.NativeException:
return m_innerException;
default:
Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
return new FormatException(SR.Format_GuidUnrecognized);
}
}
}
// Creates a new guid based on the value in the string. The value is made up
// of hex digits speared by the dash ("-"). The string may begin and end with
// brackets ("{", "}").
//
// The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
public Guid(String g)
{
if (g == null)
{
throw new ArgumentNullException(nameof(g));
}
Contract.EndContractBlock();
this = Guid.Empty;
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
if (TryParseGuid(g, GuidStyles.Any, ref result))
{
this = result.parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static Guid Parse(String input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, GuidStyles.Any, ref result))
{
return result.parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static bool TryParse(String input, out Guid result)
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, GuidStyles.Any, ref parseResult))
{
result = parseResult.parsedGuid;
return true;
}
else
{
result = Guid.Empty;
return false;
}
}
public static Guid ParseExact(String input, String format)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (format == null)
throw new ArgumentNullException(nameof(format));
if (format.Length != 1)
{
// all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n')
{
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b')
{
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p')
{
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x')
{
style = GuidStyles.HexFormat;
}
else
{
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, style, ref result))
{
return result.parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static bool TryParseExact(String input, String format, out Guid result)
{
if (format == null || format.Length != 1)
{
result = Guid.Empty;
return false;
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n')
{
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b')
{
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p')
{
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x')
{
style = GuidStyles.HexFormat;
}
else
{
// invalid guid format specification
result = Guid.Empty;
return false;
}
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, style, ref parseResult))
{
result = parseResult.parsedGuid;
return true;
}
else
{
result = Guid.Empty;
return false;
}
}
private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result)
{
if (g == null)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
String guidString = g.Trim(); //Remove Whitespace
if (guidString.Length == 0)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
// Check for dashes
bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0);
if (dashesExistInString)
{
if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0)
{
// dashes are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else
{
if ((flags & GuidStyles.RequireDashes) != 0)
{
// dashes are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
// Check for braces
bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0);
if (bracesExistInString)
{
if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0)
{
// braces are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else
{
if ((flags & GuidStyles.RequireBraces) != 0)
{
// braces are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
// Check for parenthesis
bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0);
if (parenthesisExistInString)
{
if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0)
{
// parenthesis are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else
{
if ((flags & GuidStyles.RequireParenthesis) != 0)
{
// parenthesis are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
try
{
// let's get on with the parsing
if (dashesExistInString)
{
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
return TryParseGuidWithDashes(guidString, ref result);
}
else if (bracesExistInString)
{
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
return TryParseGuidWithHexPrefix(guidString, ref result);
}
else
{
// Check if it's of the form dddddddddddddddddddddddddddddddd
return TryParseGuidWithNoStyle(guidString, ref result);
}
}
catch (IndexOutOfRangeException ex)
{
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
catch (ArgumentException ex)
{
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
}
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result)
{
int numStart = 0;
int numLen = 0;
// Eat all of the whitespace
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
if (String.IsNullOrEmpty(guidString) || guidString[0] != '{')
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, 1))
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}");
return false;
}
// Find the end of this hex number (since it is not fixed length)
numStart = 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
// Check for '{'
if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{')
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
// Prepare for loop
numLen++;
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}");
return false;
}
// +3 to get by ',0x' or '{0x' for first case
numStart = numStart + numLen + 3;
// Calculate number length
if (i < 7) // first 7 cases
{
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
}
else // last case ends with '}', not ','
{
numLen = guidString.IndexOf('}', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber");
return false;
}
}
// Read in the number
int signedNumber;
if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result))
{
return false;
}
uint number = (uint)signedNumber;
// check for overflow
if (number > 255)
{
result.SetFailure(ParseFailureKind.Format, "Overflow_Byte");
return false;
}
bytes[i] = (byte)number;
}
result.parsedGuid._d = bytes[0];
result.parsedGuid._e = bytes[1];
result.parsedGuid._f = bytes[2];
result.parsedGuid._g = bytes[3];
result.parsedGuid._h = bytes[4];
result.parsedGuid._i = bytes[5];
result.parsedGuid._j = bytes[6];
result.parsedGuid._k = bytes[7];
// Check for last '}'
if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}')
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace");
return false;
}
// Check if we have extra characters at the end
if (numStart + numLen + 1 != guidString.Length - 1)
{
result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd");
return false;
}
return true;
}
// Check if it's of the form dddddddddddddddddddddddddddddddd
private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
long templ;
int currentPos = 0;
if (guidString.Length != 32)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
for (int i = 0; i < guidString.Length; i++)
{
char ch = guidString[i];
if (ch >= '0' && ch <= '9')
{
continue;
}
else
{
char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture);
if (upperCaseCh >= 'A' && upperCaseCh <= 'F')
{
continue;
}
}
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
return false;
}
if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
startPos += 8;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
startPos += 4;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
startPos += 4;
if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result))
return false;
startPos += 4;
currentPos = startPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
result.parsedGuid._d = (byte)(temp >> 8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp >> 8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp >> 24);
result.parsedGuid._i = (byte)(temp >> 16);
result.parsedGuid._j = (byte)(temp >> 8);
result.parsedGuid._k = (byte)(temp);
return true;
}
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
long templ;
int currentPos = 0;
// check to see that it's the proper length
if (guidString[0] == '{')
{
if (guidString.Length != 38 || guidString[37] != '}')
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
startPos = 1;
}
else if (guidString[0] == '(')
{
if (guidString.Length != 38 || guidString[37] != ')')
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
startPos = 1;
}
else if (guidString.Length != 36)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
if (guidString[8 + startPos] != '-' ||
guidString[13 + startPos] != '-' ||
guidString[18 + startPos] != '-' ||
guidString[23 + startPos] != '-')
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes");
return false;
}
currentPos = startPos;
if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._a = temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._b = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._c = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
++currentPos; //Increment past the '-';
startPos = currentPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12)
{
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
result.parsedGuid._d = (byte)(temp >> 8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp >> 8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp >> 24);
result.parsedGuid._i = (byte)(temp >> 16);
result.parsedGuid._j = (byte)(temp >> 8);
result.parsedGuid._k = (byte)(temp);
return true;
}
//
// StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
return StringToShort(str, null, requiredLength, flags, out result, ref parseResult);
}
private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
result = 0;
int x;
bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult);
result = (short)x;
return retValue;
}
private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
return StringToInt(str, null, requiredLength, flags, out result, ref parseResult);
}
private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
fixed (int* ppos = &parsePos)
{
return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
result = 0;
int currStart = (parsePos == null) ? 0 : (*parsePos);
try
{
result = ParseNumbers.StringToInt(str, 16, flags, parsePos);
}
catch (OverflowException ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.All)
{
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
else
{
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
}
else
{
throw;
}
}
//If we didn't parse enough characters, there's clearly an error.
if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength)
{
parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
return false;
}
return true;
}
private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult)
{
fixed (int* ppos = &parsePos)
{
return StringToLong(str, ppos, flags, out result, ref parseResult);
}
}
private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult)
{
result = 0;
try
{
result = ParseNumbers.StringToLong(str, 16, flags, parsePos);
}
catch (OverflowException ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.All)
{
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
else
{
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex)
{
if (parseResult.throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
}
else
{
throw;
}
}
return true;
}
private static String EatAllWhitespace(String str)
{
int newLength = 0;
char[] chArr = new char[str.Length];
char curChar;
// Now get each char from str and if it is not whitespace add it to chArr
for (int i = 0; i < str.Length; i++)
{
curChar = str[i];
if (!Char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
}
// Return a new string based on chArr
return new String(chArr, 0, newLength);
}
private static bool IsHexPrefix(String str, int i)
{
if (str.Length > i + 1 && str[i] == '0' && (Char.ToLower(str[i + 1], CultureInfo.InvariantCulture) == 'x'))
return true;
else
return false;
}
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
byte[] g = new byte[16];
g[0] = (byte)(_a);
g[1] = (byte)(_a >> 8);
g[2] = (byte)(_a >> 16);
g[3] = (byte)(_a >> 24);
g[4] = (byte)(_b);
g[5] = (byte)(_b >> 8);
g[6] = (byte)(_c);
g[7] = (byte)(_c >> 8);
g[8] = _d;
g[9] = _e;
g[10] = _f;
g[11] = _g;
g[12] = _h;
g[13] = _i;
g[14] = _j;
g[15] = _k;
return g;
}
// Returns the guid in "registry" format.
public override String ToString()
{
return ToString("D", null);
}
public unsafe override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
fixed (int* ptr = &_a)
return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(Object o)
{
Guid g;
// Check that o is a Guid first
if (o == null || !(o is Guid))
return false;
else g = (Guid)o;
// Now compare each of the elements
if (g._a != _a)
return false;
if (g._b != _b)
return false;
if (g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
public bool Equals(Guid g)
{
// Now compare each of the elements
if (g._a != _a)
return false;
if (g._b != _b)
return false;
if (g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
private int GetResult(uint me, uint them)
{
if (me < them)
{
return -1;
}
return 1;
}
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (!(value is Guid))
{
throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value));
}
Guid g = (Guid)value;
if (g._a != _a)
{
return GetResult((uint)_a, (uint)g._a);
}
if (g._b != _b)
{
return GetResult((uint)_b, (uint)g._b);
}
if (g._c != _c)
{
return GetResult((uint)_c, (uint)g._c);
}
if (g._d != _d)
{
return GetResult((uint)_d, (uint)g._d);
}
if (g._e != _e)
{
return GetResult((uint)_e, (uint)g._e);
}
if (g._f != _f)
{
return GetResult((uint)_f, (uint)g._f);
}
if (g._g != _g)
{
return GetResult((uint)_g, (uint)g._g);
}
if (g._h != _h)
{
return GetResult((uint)_h, (uint)g._h);
}
if (g._i != _i)
{
return GetResult((uint)_i, (uint)g._i);
}
if (g._j != _j)
{
return GetResult((uint)_j, (uint)g._j);
}
if (g._k != _k)
{
return GetResult((uint)_k, (uint)g._k);
}
return 0;
}
public int CompareTo(Guid value)
{
if (value._a != _a)
{
return GetResult((uint)_a, (uint)value._a);
}
if (value._b != _b)
{
return GetResult((uint)_b, (uint)value._b);
}
if (value._c != _c)
{
return GetResult((uint)_c, (uint)value._c);
}
if (value._d != _d)
{
return GetResult((uint)_d, (uint)value._d);
}
if (value._e != _e)
{
return GetResult((uint)_e, (uint)value._e);
}
if (value._f != _f)
{
return GetResult((uint)_f, (uint)value._f);
}
if (value._g != _g)
{
return GetResult((uint)_g, (uint)value._g);
}
if (value._h != _h)
{
return GetResult((uint)_h, (uint)value._h);
}
if (value._i != _i)
{
return GetResult((uint)_i, (uint)value._i);
}
if (value._j != _j)
{
return GetResult((uint)_j, (uint)value._j);
}
if (value._k != _k)
{
return GetResult((uint)_k, (uint)value._k);
}
return 0;
}
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
if (a._a != b._a)
return false;
if (a._b != b._b)
return false;
if (a._c != b._c)
return false;
if (a._d != b._d)
return false;
if (a._e != b._e)
return false;
if (a._f != b._f)
return false;
if (a._g != b._g)
return false;
if (a._h != b._h)
return false;
if (a._i != b._i)
return false;
if (a._j != b._j)
return false;
if (a._k != b._k)
return false;
return true;
}
public static bool operator !=(Guid a, Guid b)
{
return !(a == b);
}
// This will create a new guid. Since we've now decided that constructors should 0-init,
// we need a method that allows users to create a guid.
public static Guid NewGuid()
{
// CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
// uniqueness guarantees. It should also never return a known GUID, but it's unclear
// how extensively it checks for known values.
Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
Guid guid;
Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
return guid;
}
public String ToString(String format)
{
return ToString(format, null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static char HexToChar(int a)
{
a = a & 0xf;
return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
unsafe private static int HexsToChars(char* guidChars, int a, int b)
{
guidChars[0] = HexToChar(a >> 4);
guidChars[1] = HexToChar(a);
guidChars[2] = HexToChar(b >> 4);
guidChars[3] = HexToChar(b);
return 4;
}
unsafe private static int HexsToCharsHexOutput(char* guidChars, int a, int b)
{
guidChars[0] = '0';
guidChars[1] = 'x';
guidChars[2] = HexToChar(a >> 4);
guidChars[3] = HexToChar(a);
guidChars[4] = ',';
guidChars[5] = '0';
guidChars[6] = 'x';
guidChars[7] = HexToChar(b >> 4);
guidChars[8] = HexToChar(b);
return 9;
}
// IFormattable interface
// We currently ignore provider
public String ToString(String format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
string guidString;
int offset = 0;
bool dash = true;
bool hex = false;
if (format.Length != 1)
{
// all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
guidString = string.FastAllocateString(36);
}
else if (formatCh == 'N' || formatCh == 'n')
{
guidString = string.FastAllocateString(32);
dash = false;
}
else if (formatCh == 'B' || formatCh == 'b')
{
guidString = string.FastAllocateString(38);
unsafe
{
fixed (char* guidChars = guidString)
{
guidChars[offset++] = '{';
guidChars[37] = '}';
}
}
}
else if (formatCh == 'P' || formatCh == 'p')
{
guidString = string.FastAllocateString(38);
unsafe
{
fixed (char* guidChars = guidString)
{
guidChars[offset++] = '(';
guidChars[37] = ')';
}
}
}
else if (formatCh == 'X' || formatCh == 'x')
{
guidString = string.FastAllocateString(68);
unsafe
{
fixed (char* guidChars = guidString)
{
guidChars[offset++] = '{';
guidChars[67] = '}';
}
}
dash = false;
hex = true;
}
else
{
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
unsafe
{
fixed (char* guidChars = guidString)
{
if (hex)
{
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset += HexsToChars(guidChars + offset, _a >> 24, _a >> 16);
offset += HexsToChars(guidChars + offset, _a >> 8, _a);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset += HexsToChars(guidChars + offset, _b >> 8, _b);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset += HexsToChars(guidChars + offset, _c >> 8, _c);
guidChars[offset++] = ',';
guidChars[offset++] = '{';
offset += HexsToCharsHexOutput(guidChars + offset, _d, _e);
guidChars[offset++] = ',';
offset += HexsToCharsHexOutput(guidChars + offset, _f, _g);
guidChars[offset++] = ',';
offset += HexsToCharsHexOutput(guidChars + offset, _h, _i);
guidChars[offset++] = ',';
offset += HexsToCharsHexOutput(guidChars + offset, _j, _k);
guidChars[offset++] = '}';
}
else
{
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
offset += HexsToChars(guidChars + offset, _a >> 24, _a >> 16);
offset += HexsToChars(guidChars + offset, _a >> 8, _a);
if (dash) guidChars[offset++] = '-';
offset += HexsToChars(guidChars + offset, _b >> 8, _b);
if (dash) guidChars[offset++] = '-';
offset += HexsToChars(guidChars + offset, _c >> 8, _c);
if (dash) guidChars[offset++] = '-';
offset += HexsToChars(guidChars + offset, _d, _e);
if (dash) guidChars[offset++] = '-';
offset += HexsToChars(guidChars + offset, _f, _g);
offset += HexsToChars(guidChars + offset, _h, _i);
offset += HexsToChars(guidChars + offset, _j, _k);
}
}
}
return guidString;
}
}
}
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public partial class Handler : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Handler()
{
InitJNI();
}
protected Handler(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.os.Handler.Callback_))]
public interface Callback : global::MonoJavaBridge.IJavaObject
{
bool handleMessage(android.os.Message arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.os.Handler.Callback))]
public sealed partial class Callback_ : java.lang.Object, Callback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Callback_()
{
InitJNI();
}
internal Callback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _handleMessage6420;
bool android.os.Handler.Callback.handleMessage(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler.Callback_._handleMessage6420, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.Callback_.staticClass, global::android.os.Handler.Callback_._handleMessage6420, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.Handler.Callback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/Handler$Callback"));
global::android.os.Handler.Callback_._handleMessage6420 = @__env.GetMethodIDNoThrow(global::android.os.Handler.Callback_.staticClass, "handleMessage", "(Landroid/os/Message;)Z");
}
}
internal static global::MonoJavaBridge.MethodId _toString6421;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._toString6421)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._toString6421)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _dump6422;
public virtual void dump(android.util.Printer arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._dump6422, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._dump6422, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _handleMessage6423;
public virtual void handleMessage(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._handleMessage6423, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._handleMessage6423, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _dispatchMessage6424;
public virtual void dispatchMessage(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._dispatchMessage6424, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._dispatchMessage6424, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _obtainMessage6425;
public virtual global::android.os.Message obtainMessage(int arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._obtainMessage6425, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.Message;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._obtainMessage6425, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.Message;
}
internal static global::MonoJavaBridge.MethodId _obtainMessage6426;
public virtual global::android.os.Message obtainMessage(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._obtainMessage6426, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.os.Message;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._obtainMessage6426, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.os.Message;
}
internal static global::MonoJavaBridge.MethodId _obtainMessage6427;
public virtual global::android.os.Message obtainMessage(int arg0, int arg1, int arg2, java.lang.Object arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._obtainMessage6427, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.os.Message;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._obtainMessage6427, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.os.Message;
}
internal static global::MonoJavaBridge.MethodId _obtainMessage6428;
public virtual global::android.os.Message obtainMessage(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._obtainMessage6428, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Message;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._obtainMessage6428, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Message;
}
internal static global::MonoJavaBridge.MethodId _obtainMessage6429;
public virtual global::android.os.Message obtainMessage()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._obtainMessage6429)) as android.os.Message;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._obtainMessage6429)) as android.os.Message;
}
internal static global::MonoJavaBridge.MethodId _post6430;
public virtual bool post(java.lang.Runnable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._post6430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._post6430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _postAtTime6431;
public virtual bool postAtTime(java.lang.Runnable arg0, java.lang.Object arg1, long arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._postAtTime6431, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._postAtTime6431, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _postAtTime6432;
public virtual bool postAtTime(java.lang.Runnable arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._postAtTime6432, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._postAtTime6432, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _postDelayed6433;
public virtual bool postDelayed(java.lang.Runnable arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._postDelayed6433, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._postDelayed6433, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _postAtFrontOfQueue6434;
public virtual bool postAtFrontOfQueue(java.lang.Runnable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._postAtFrontOfQueue6434, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._postAtFrontOfQueue6434, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeCallbacks6435;
public virtual void removeCallbacks(java.lang.Runnable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._removeCallbacks6435, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._removeCallbacks6435, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeCallbacks6436;
public virtual void removeCallbacks(java.lang.Runnable arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._removeCallbacks6436, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._removeCallbacks6436, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _sendMessage6437;
public virtual bool sendMessage(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendMessage6437, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendMessage6437, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _sendEmptyMessage6438;
public virtual bool sendEmptyMessage(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendEmptyMessage6438, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendEmptyMessage6438, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _sendEmptyMessageDelayed6439;
public virtual bool sendEmptyMessageDelayed(int arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendEmptyMessageDelayed6439, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendEmptyMessageDelayed6439, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _sendEmptyMessageAtTime6440;
public virtual bool sendEmptyMessageAtTime(int arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendEmptyMessageAtTime6440, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendEmptyMessageAtTime6440, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _sendMessageDelayed6441;
public virtual bool sendMessageDelayed(android.os.Message arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendMessageDelayed6441, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendMessageDelayed6441, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _sendMessageAtTime6442;
public virtual bool sendMessageAtTime(android.os.Message arg0, long arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendMessageAtTime6442, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendMessageAtTime6442, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _sendMessageAtFrontOfQueue6443;
public virtual bool sendMessageAtFrontOfQueue(android.os.Message arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._sendMessageAtFrontOfQueue6443, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._sendMessageAtFrontOfQueue6443, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeMessages6444;
public virtual void removeMessages(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._removeMessages6444, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._removeMessages6444, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeMessages6445;
public virtual void removeMessages(int arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._removeMessages6445, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._removeMessages6445, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _removeCallbacksAndMessages6446;
public virtual void removeCallbacksAndMessages(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.os.Handler._removeCallbacksAndMessages6446, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._removeCallbacksAndMessages6446, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _hasMessages6447;
public virtual bool hasMessages(int arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._hasMessages6447, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._hasMessages6447, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _hasMessages6448;
public virtual bool hasMessages(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.os.Handler._hasMessages6448, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._hasMessages6448, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLooper6449;
public virtual global::android.os.Looper getLooper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.os.Handler._getLooper6449)) as android.os.Looper;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.os.Handler.staticClass, global::android.os.Handler._getLooper6449)) as android.os.Looper;
}
internal static global::MonoJavaBridge.MethodId _Handler6450;
public Handler() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Handler.staticClass, global::android.os.Handler._Handler6450);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Handler6451;
public Handler(android.os.Handler.Callback arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Handler.staticClass, global::android.os.Handler._Handler6451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Handler6452;
public Handler(android.os.Looper arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Handler.staticClass, global::android.os.Handler._Handler6452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Handler6453;
public Handler(android.os.Looper arg0, android.os.Handler.Callback arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Handler.staticClass, global::android.os.Handler._Handler6453, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.Handler.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/Handler"));
global::android.os.Handler._toString6421 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "toString", "()Ljava/lang/String;");
global::android.os.Handler._dump6422 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V");
global::android.os.Handler._handleMessage6423 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "handleMessage", "(Landroid/os/Message;)V");
global::android.os.Handler._dispatchMessage6424 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "dispatchMessage", "(Landroid/os/Message;)V");
global::android.os.Handler._obtainMessage6425 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "obtainMessage", "(ILjava/lang/Object;)Landroid/os/Message;");
global::android.os.Handler._obtainMessage6426 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "obtainMessage", "(III)Landroid/os/Message;");
global::android.os.Handler._obtainMessage6427 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "obtainMessage", "(IIILjava/lang/Object;)Landroid/os/Message;");
global::android.os.Handler._obtainMessage6428 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "obtainMessage", "(I)Landroid/os/Message;");
global::android.os.Handler._obtainMessage6429 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "obtainMessage", "()Landroid/os/Message;");
global::android.os.Handler._post6430 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "post", "(Ljava/lang/Runnable;)Z");
global::android.os.Handler._postAtTime6431 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "postAtTime", "(Ljava/lang/Runnable;Ljava/lang/Object;J)Z");
global::android.os.Handler._postAtTime6432 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "postAtTime", "(Ljava/lang/Runnable;J)Z");
global::android.os.Handler._postDelayed6433 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "postDelayed", "(Ljava/lang/Runnable;J)Z");
global::android.os.Handler._postAtFrontOfQueue6434 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "postAtFrontOfQueue", "(Ljava/lang/Runnable;)Z");
global::android.os.Handler._removeCallbacks6435 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "removeCallbacks", "(Ljava/lang/Runnable;)V");
global::android.os.Handler._removeCallbacks6436 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "removeCallbacks", "(Ljava/lang/Runnable;Ljava/lang/Object;)V");
global::android.os.Handler._sendMessage6437 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendMessage", "(Landroid/os/Message;)Z");
global::android.os.Handler._sendEmptyMessage6438 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendEmptyMessage", "(I)Z");
global::android.os.Handler._sendEmptyMessageDelayed6439 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendEmptyMessageDelayed", "(IJ)Z");
global::android.os.Handler._sendEmptyMessageAtTime6440 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendEmptyMessageAtTime", "(IJ)Z");
global::android.os.Handler._sendMessageDelayed6441 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendMessageDelayed", "(Landroid/os/Message;J)Z");
global::android.os.Handler._sendMessageAtTime6442 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendMessageAtTime", "(Landroid/os/Message;J)Z");
global::android.os.Handler._sendMessageAtFrontOfQueue6443 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "sendMessageAtFrontOfQueue", "(Landroid/os/Message;)Z");
global::android.os.Handler._removeMessages6444 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "removeMessages", "(I)V");
global::android.os.Handler._removeMessages6445 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "removeMessages", "(ILjava/lang/Object;)V");
global::android.os.Handler._removeCallbacksAndMessages6446 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "removeCallbacksAndMessages", "(Ljava/lang/Object;)V");
global::android.os.Handler._hasMessages6447 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "hasMessages", "(ILjava/lang/Object;)Z");
global::android.os.Handler._hasMessages6448 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "hasMessages", "(I)Z");
global::android.os.Handler._getLooper6449 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "getLooper", "()Landroid/os/Looper;");
global::android.os.Handler._Handler6450 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "<init>", "()V");
global::android.os.Handler._Handler6451 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "<init>", "(Landroid/os/Handler$Callback;)V");
global::android.os.Handler._Handler6452 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "<init>", "(Landroid/os/Looper;)V");
global::android.os.Handler._Handler6453 = @__env.GetMethodIDNoThrow(global::android.os.Handler.staticClass, "<init>", "(Landroid/os/Looper;Landroid/os/Handler$Callback;)V");
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Pool-wide updates to the host software
/// First published in XenServer 7.1.
/// </summary>
public partial class Pool_update : XenObject<Pool_update>
{
#region Constructors
public Pool_update()
{
}
public Pool_update(string uuid,
string name_label,
string name_description,
string version,
long installation_size,
string key,
List<update_after_apply_guidance> after_apply_guidance,
XenRef<VDI> vdi,
List<XenRef<Host>> hosts,
Dictionary<string, string> other_config,
bool enforce_homogeneity)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.installation_size = installation_size;
this.key = key;
this.after_apply_guidance = after_apply_guidance;
this.vdi = vdi;
this.hosts = hosts;
this.other_config = other_config;
this.enforce_homogeneity = enforce_homogeneity;
}
/// <summary>
/// Creates a new Pool_update from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Pool_update(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Pool_update from a Proxy_Pool_update.
/// </summary>
/// <param name="proxy"></param>
public Pool_update(Proxy_Pool_update proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Pool_update.
/// </summary>
public override void UpdateFrom(Pool_update update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
installation_size = update.installation_size;
key = update.key;
after_apply_guidance = update.after_apply_guidance;
vdi = update.vdi;
hosts = update.hosts;
other_config = update.other_config;
enforce_homogeneity = update.enforce_homogeneity;
}
internal void UpdateFrom(Proxy_Pool_update proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
version = proxy.version == null ? null : proxy.version;
installation_size = proxy.installation_size == null ? 0 : long.Parse(proxy.installation_size);
key = proxy.key == null ? null : proxy.key;
after_apply_guidance = proxy.after_apply_guidance == null ? null : Helper.StringArrayToEnumList<update_after_apply_guidance>(proxy.after_apply_guidance);
vdi = proxy.vdi == null ? null : XenRef<VDI>.Create(proxy.vdi);
hosts = proxy.hosts == null ? null : XenRef<Host>.Create(proxy.hosts);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
enforce_homogeneity = (bool)proxy.enforce_homogeneity;
}
public Proxy_Pool_update ToProxy()
{
Proxy_Pool_update result_ = new Proxy_Pool_update();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.installation_size = installation_size.ToString();
result_.key = key ?? "";
result_.after_apply_guidance = after_apply_guidance == null ? new string[] {} : Helper.ObjectListToStringArray(after_apply_guidance);
result_.vdi = vdi ?? "";
result_.hosts = hosts == null ? new string[] {} : Helper.RefListToStringArray(hosts);
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.enforce_homogeneity = enforce_homogeneity;
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Pool_update
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("installation_size"))
installation_size = Marshalling.ParseLong(table, "installation_size");
if (table.ContainsKey("key"))
key = Marshalling.ParseString(table, "key");
if (table.ContainsKey("after_apply_guidance"))
after_apply_guidance = Helper.StringArrayToEnumList<update_after_apply_guidance>(Marshalling.ParseStringArray(table, "after_apply_guidance"));
if (table.ContainsKey("vdi"))
vdi = Marshalling.ParseRef<VDI>(table, "vdi");
if (table.ContainsKey("hosts"))
hosts = Marshalling.ParseSetRef<Host>(table, "hosts");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("enforce_homogeneity"))
enforce_homogeneity = Marshalling.ParseBool(table, "enforce_homogeneity");
}
public bool DeepEquals(Pool_update other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._installation_size, other._installation_size) &&
Helper.AreEqual2(this._key, other._key) &&
Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) &&
Helper.AreEqual2(this._vdi, other._vdi) &&
Helper.AreEqual2(this._hosts, other._hosts) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._enforce_homogeneity, other._enforce_homogeneity);
}
internal static List<Pool_update> ProxyArrayToObjectList(Proxy_Pool_update[] input)
{
var result = new List<Pool_update>();
foreach (var item in input)
result.Add(new Pool_update(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Pool_update server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Pool_update.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static Pool_update get_record(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_record(session.opaque_ref, _pool_update);
else
return new Pool_update(session.XmlRpcProxy.pool_update_get_record(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get a reference to the pool_update instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Pool_update> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.pool_update_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the pool_update instances with the given label.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Pool_update>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.pool_update_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_uuid(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_uuid(session.opaque_ref, _pool_update);
else
return session.XmlRpcProxy.pool_update_get_uuid(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_name_label(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_name_label(session.opaque_ref, _pool_update);
else
return session.XmlRpcProxy.pool_update_get_name_label(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_name_description(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_name_description(session.opaque_ref, _pool_update);
else
return session.XmlRpcProxy.pool_update_get_name_description(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the version field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_version(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_version(session.opaque_ref, _pool_update);
else
return session.XmlRpcProxy.pool_update_get_version(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the installation_size field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static long get_installation_size(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_installation_size(session.opaque_ref, _pool_update);
else
return long.Parse(session.XmlRpcProxy.pool_update_get_installation_size(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the key field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_key(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_key(session.opaque_ref, _pool_update);
else
return session.XmlRpcProxy.pool_update_get_key(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the after_apply_guidance field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static List<update_after_apply_guidance> get_after_apply_guidance(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_after_apply_guidance(session.opaque_ref, _pool_update);
else
return Helper.StringArrayToEnumList<update_after_apply_guidance>(session.XmlRpcProxy.pool_update_get_after_apply_guidance(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the vdi field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<VDI> get_vdi(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_vdi(session.opaque_ref, _pool_update);
else
return XenRef<VDI>.Create(session.XmlRpcProxy.pool_update_get_vdi(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the hosts field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static List<XenRef<Host>> get_hosts(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_hosts(session.opaque_ref, _pool_update);
else
return XenRef<Host>.Create(session.XmlRpcProxy.pool_update_get_hosts(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static Dictionary<string, string> get_other_config(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_other_config(session.opaque_ref, _pool_update);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.pool_update_get_other_config(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the enforce_homogeneity field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static bool get_enforce_homogeneity(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_enforce_homogeneity(session.opaque_ref, _pool_update);
else
return (bool)session.XmlRpcProxy.pool_update_get_enforce_homogeneity(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pool_update, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_set_other_config(session.opaque_ref, _pool_update, _other_config);
else
session.XmlRpcProxy.pool_update_set_other_config(session.opaque_ref, _pool_update ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pool_update, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_add_to_other_config(session.opaque_ref, _pool_update, _key, _value);
else
session.XmlRpcProxy.pool_update_add_to_other_config(session.opaque_ref, _pool_update ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given pool_update. If the key is not in that Map, then do nothing.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pool_update, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_remove_from_other_config(session.opaque_ref, _pool_update, _key);
else
session.XmlRpcProxy.pool_update_remove_from_other_config(session.opaque_ref, _pool_update ?? "", _key ?? "").parse();
}
/// <summary>
/// Introduce update VDI
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vdi">The VDI which contains a software update.</param>
public static XenRef<Pool_update> introduce(Session session, string _vdi)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_introduce(session.opaque_ref, _vdi);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.pool_update_introduce(session.opaque_ref, _vdi ?? "").parse());
}
/// <summary>
/// Introduce update VDI
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vdi">The VDI which contains a software update.</param>
public static XenRef<Task> async_introduce(Session session, string _vdi)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_introduce(session.opaque_ref, _vdi);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_update_introduce(session.opaque_ref, _vdi ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected update on a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to run the prechecks on.</param>
public static livepatch_status precheck(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_precheck(session.opaque_ref, _pool_update, _host);
else
return (livepatch_status)Helper.EnumParseDefault(typeof(livepatch_status), (string)session.XmlRpcProxy.pool_update_precheck(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected update on a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to run the prechecks on.</param>
public static XenRef<Task> async_precheck(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_precheck(session.opaque_ref, _pool_update, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_update_precheck(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected update to a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to apply the update to.</param>
public static void apply(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_apply(session.opaque_ref, _pool_update, _host);
else
session.XmlRpcProxy.pool_update_apply(session.opaque_ref, _pool_update ?? "", _host ?? "").parse();
}
/// <summary>
/// Apply the selected update to a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to apply the update to.</param>
public static XenRef<Task> async_apply(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_apply(session.opaque_ref, _pool_update, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_update_apply(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected update to all hosts in the pool
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void pool_apply(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_pool_apply(session.opaque_ref, _pool_update);
else
session.XmlRpcProxy.pool_update_pool_apply(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Apply the selected update to all hosts in the pool
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_pool_apply(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_pool_apply(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_update_pool_apply(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Removes the update's files from all hosts in the pool, but does not revert the update
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void pool_clean(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_pool_clean(session.opaque_ref, _pool_update);
else
session.XmlRpcProxy.pool_update_pool_clean(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Removes the update's files from all hosts in the pool, but does not revert the update
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_pool_clean(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_pool_clean(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_update_pool_clean(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Removes the database entry. Only works on unapplied update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void destroy(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_destroy(session.opaque_ref, _pool_update);
else
session.XmlRpcProxy.pool_update_destroy(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Removes the database entry. Only works on unapplied update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_destroy(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_destroy(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_update_destroy(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Return a list of all the pool_updates known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Pool_update>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_all(session.opaque_ref);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.pool_update_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the pool_update Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Pool_update>, Pool_update> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_all_records(session.opaque_ref);
else
return XenRef<Pool_update>.Create<Proxy_Pool_update>(session.XmlRpcProxy.pool_update_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Update version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Size of the update in bytes
/// </summary>
public virtual long installation_size
{
get { return _installation_size; }
set
{
if (!Helper.AreEqual(value, _installation_size))
{
_installation_size = value;
NotifyPropertyChanged("installation_size");
}
}
}
private long _installation_size = 0;
/// <summary>
/// GPG key of the update
/// </summary>
public virtual string key
{
get { return _key; }
set
{
if (!Helper.AreEqual(value, _key))
{
_key = value;
NotifyPropertyChanged("key");
}
}
}
private string _key = "";
/// <summary>
/// What the client should do after this update has been applied.
/// </summary>
public virtual List<update_after_apply_guidance> after_apply_guidance
{
get { return _after_apply_guidance; }
set
{
if (!Helper.AreEqual(value, _after_apply_guidance))
{
_after_apply_guidance = value;
NotifyPropertyChanged("after_apply_guidance");
}
}
}
private List<update_after_apply_guidance> _after_apply_guidance = new List<update_after_apply_guidance>() {};
/// <summary>
/// VDI the update was uploaded to
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public virtual XenRef<VDI> vdi
{
get { return _vdi; }
set
{
if (!Helper.AreEqual(value, _vdi))
{
_vdi = value;
NotifyPropertyChanged("vdi");
}
}
}
private XenRef<VDI> _vdi = new XenRef<VDI>(Helper.NullOpaqueRef);
/// <summary>
/// The hosts that have applied this update.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host>))]
public virtual List<XenRef<Host>> hosts
{
get { return _hosts; }
set
{
if (!Helper.AreEqual(value, _hosts))
{
_hosts = value;
NotifyPropertyChanged("hosts");
}
}
}
private List<XenRef<Host>> _hosts = new List<XenRef<Host>>() {};
/// <summary>
/// additional configuration
/// First published in XenServer 7.3.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Flag - if true, all hosts in a pool must apply this update
/// First published in XenServer 7.3.
/// </summary>
public virtual bool enforce_homogeneity
{
get { return _enforce_homogeneity; }
set
{
if (!Helper.AreEqual(value, _enforce_homogeneity))
{
_enforce_homogeneity = value;
NotifyPropertyChanged("enforce_homogeneity");
}
}
}
private bool _enforce_homogeneity = false;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for Text-only Writers.
** Subclasses will include StreamWriter & StringWriter.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO {
// This abstract base class represents a writer that can write a sequential
// stream of characters. A subclass must minimally implement the
// Write(char) method.
//
// This class is intended for character output, not bytes.
// There are methods on the Stream class for writing bytes.
[Serializable]
[ComVisible(true)]
public abstract class TextWriter : MarshalByRefObject, IDisposable {
public static readonly TextWriter Null = new NullTextWriter();
// This should be initialized to Environment.NewLine, but
// to avoid loading Environment unnecessarily so I've duplicated
// the value here.
#if !PLATFORM_UNIX
private const String InitialNewLine = "\r\n";
protected char[] CoreNewLine = new char[] { '\r', '\n' };
#else
private const String InitialNewLine = "\n";
protected char[] CoreNewLine = new char[] {'\n'};
#endif // !PLATFORM_UNIX
// Can be null - if so, ask for the Thread's CurrentCulture every time.
private IFormatProvider InternalFormatProvider;
protected TextWriter()
{
InternalFormatProvider = null; // Ask for CurrentCulture all the time.
}
protected TextWriter(IFormatProvider formatProvider)
{
InternalFormatProvider = formatProvider;
}
public virtual IFormatProvider FormatProvider {
get {
if (InternalFormatProvider == null)
return Thread.CurrentThread.CurrentCulture;
else
return InternalFormatProvider;
}
}
// Closes this TextWriter and releases any system resources associated with the
// TextWriter. Following a call to Close, any operations on the TextWriter
// 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);
}
protected virtual void Dispose(bool disposing)
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Clears all buffers for this TextWriter and causes any buffered data to be
// written to the underlying device. This default method is empty, but
// descendant classes can override the method to provide the appropriate
// functionality.
public virtual void Flush() {
}
public abstract Encoding Encoding {
get;
}
// Returns the line terminator string used by this TextWriter. The default line
// terminator string is a carriage return followed by a line feed ("\r\n").
//
// Sets the line terminator string for this TextWriter. The line terminator
// string is written to the text stream whenever one of the
// WriteLine methods are called. In order for text written by
// the TextWriter to be readable by a TextReader, only one of the following line
// terminator strings should be used: "\r", "\n", or "\r\n".
//
public virtual String NewLine {
get { return new String(CoreNewLine); }
set {
if (value == null)
value = InitialNewLine;
CoreNewLine = value.ToCharArray();
}
}
[HostProtection(Synchronization=true)]
public static TextWriter Synchronized(TextWriter writer) {
if (writer==null)
throw new ArgumentNullException(nameof(writer));
Contract.Ensures(Contract.Result<TextWriter>() != null);
Contract.EndContractBlock();
if (writer is SyncTextWriter)
return writer;
return new SyncTextWriter(writer);
}
// Writes a character to the text stream. This default method is empty,
// but descendant classes can override the method to provide the
// appropriate functionality.
//
public virtual void Write(char value) {
}
// Writes a character array to the text stream. This default method calls
// Write(char) for each of the characters in the character array.
// If the character array is null, nothing is written.
//
public virtual void Write(char[] buffer) {
if (buffer != null) Write(buffer, 0, buffer.Length);
}
// Writes a range of a character array to the text stream. This method will
// write count characters of data into this TextWriter from the
// buffer character array starting at position index.
//
public virtual void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
for (int i = 0; i < count; i++) Write(buffer[index + i]);
}
// Writes the text representation of a boolean to the text stream. This
// method outputs either Boolean.TrueString or Boolean.FalseString.
//
public virtual void Write(bool value) {
Write(value ? Boolean.TrueLiteral : Boolean.FalseLiteral);
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// Int32.ToString() method.
//
public virtual void Write(int value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// UInt32.ToString() method.
//
[CLSCompliant(false)]
public virtual void Write(uint value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a long to the text stream. The
// text representation of the given value is produced by calling the
// Int64.ToString() method.
//
public virtual void Write(long value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of an unsigned long to the text
// stream. The text representation of the given value is produced
// by calling the UInt64.ToString() method.
//
[CLSCompliant(false)]
public virtual void Write(ulong value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a float to the text stream. The
// text representation of the given value is produced by calling the
// Float.toString(float) method.
//
public virtual void Write(float value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a double to the text stream. The
// text representation of the given value is produced by calling the
// Double.toString(double) method.
//
public virtual void Write(double value) {
Write(value.ToString(FormatProvider));
}
public virtual void Write(Decimal value) {
Write(value.ToString(FormatProvider));
}
// Writes a string to the text stream. If the given string is null, nothing
// is written to the text stream.
//
public virtual void Write(String value) {
if (value != null) Write(value.ToCharArray());
}
// Writes the text representation of an object to the text stream. If the
// given object is null, nothing is written to the text stream.
// Otherwise, the object's ToString method is called to produce the
// string representation, and the resulting string is then written to the
// output stream.
//
public virtual void Write(Object value) {
if (value != null) {
IFormattable f = value as IFormattable;
if (f != null)
Write(f.ToString(null, FormatProvider));
else
Write(value.ToString());
}
}
#if false
// // Converts the wchar * to a string and writes this to the stream.
// //
// __attribute NonCLSCompliantAttribute()
// public void Write(wchar *value) {
// Write(new String(value));
// }
// // Treats the byte* as a LPCSTR, converts it to a string, and writes it to the stream.
// //
// __attribute NonCLSCompliantAttribute()
// public void Write(byte *value) {
// Write(new String(value));
// }
#endif
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0)
{
Write(String.Format(FormatProvider, format, arg0));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0, Object arg1)
{
Write(String.Format(FormatProvider, format, arg0, arg1));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0, Object arg1, Object arg2)
{
Write(String.Format(FormatProvider, format, arg0, arg1, arg2));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, params Object[] arg)
{
Write(String.Format(FormatProvider, format, arg));
}
// Writes a line terminator to the text stream. The default line terminator
// is a carriage return followed by a line feed ("\r\n"), but this value
// can be changed by setting the NewLine property.
//
public virtual void WriteLine() {
Write(CoreNewLine);
}
// Writes a character followed by a line terminator to the text stream.
//
public virtual void WriteLine(char value) {
Write(value);
WriteLine();
}
// Writes an array of characters followed by a line terminator to the text
// stream.
//
public virtual void WriteLine(char[] buffer) {
Write(buffer);
WriteLine();
}
// Writes a range of a character array followed by a line terminator to the
// text stream.
//
public virtual void WriteLine(char[] buffer, int index, int count) {
Write(buffer, index, count);
WriteLine();
}
// Writes the text representation of a boolean followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(bool value) {
Write(value);
WriteLine();
}
// Writes the text representation of an integer followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(int value) {
Write(value);
WriteLine();
}
// Writes the text representation of an unsigned integer followed by
// a line terminator to the text stream.
//
[CLSCompliant(false)]
public virtual void WriteLine(uint value) {
Write(value);
WriteLine();
}
// Writes the text representation of a long followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(long value) {
Write(value);
WriteLine();
}
// Writes the text representation of an unsigned long followed by
// a line terminator to the text stream.
//
[CLSCompliant(false)]
public virtual void WriteLine(ulong value) {
Write(value);
WriteLine();
}
// Writes the text representation of a float followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(float value) {
Write(value);
WriteLine();
}
// Writes the text representation of a double followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(double value) {
Write(value);
WriteLine();
}
public virtual void WriteLine(decimal value) {
Write(value);
WriteLine();
}
// Writes a string followed by a line terminator to the text stream.
//
public virtual void WriteLine(String value) {
if (value==null) {
WriteLine();
}
else {
// We'd ideally like WriteLine to be atomic, in that one call
// to WriteLine equals one call to the OS (ie, so writing to
// console while simultaneously calling printf will guarantee we
// write out a string and new line chars, without any interference).
// Additionally, we need to call ToCharArray on Strings anyways,
// so allocating a char[] here isn't any worse than what we were
// doing anyways. We do reduce the number of calls to the
// backing store this way, potentially.
int vLen = value.Length;
int nlLen = CoreNewLine.Length;
char[] chars = new char[vLen+nlLen];
value.CopyTo(0, chars, 0, vLen);
// CoreNewLine will almost always be 2 chars, and possibly 1.
if (nlLen == 2) {
chars[vLen] = CoreNewLine[0];
chars[vLen+1] = CoreNewLine[1];
}
else if (nlLen == 1)
chars[vLen] = CoreNewLine[0];
else
Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2);
Write(chars, 0, vLen + nlLen);
}
/*
Write(value); // We could call Write(String) on StreamWriter...
WriteLine();
*/
}
// Writes the text representation of an object followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(Object value) {
if (value==null) {
WriteLine();
}
else {
// Call WriteLine(value.ToString), not Write(Object), WriteLine().
// This makes calls to WriteLine(Object) atomic.
IFormattable f = value as IFormattable;
if (f != null)
WriteLine(f.ToString(null, FormatProvider));
else
WriteLine(value.ToString());
}
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine(String format, Object arg0)
{
WriteLine(String.Format(FormatProvider, format, arg0));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine (String format, Object arg0, Object arg1)
{
WriteLine(String.Format(FormatProvider, format, arg0, arg1));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine (String format, Object arg0, Object arg1, Object arg2)
{
WriteLine(String.Format(FormatProvider, format, arg0, arg1, arg2));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine (String format, params Object[] arg)
{
WriteLine(String.Format(FormatProvider, format, arg));
}
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char value)
{
var tuple = new Tuple<TextWriter, char>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char>)state;
t.Item1.Write(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(String value)
{
var tuple = new Tuple<TextWriter, string>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, string>)state;
t.Item1.Write(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(char[] buffer)
{
if (buffer == null) return Task.CompletedTask;
return WriteAsync(buffer, 0, buffer.Length);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char[] buffer, int index, int count)
{
var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char[], int, int>)state;
t.Item1.Write(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char value)
{
var tuple = new Tuple<TextWriter, char>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char>)state;
t.Item1.WriteLine(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(String value)
{
var tuple = new Tuple<TextWriter, string>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, string>)state;
t.Item1.WriteLine(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteLineAsync(char[] buffer)
{
if (buffer == null) return Task.CompletedTask;
return WriteLineAsync(buffer, 0, buffer.Length);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char[] buffer, int index, int count)
{
var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char[], int, int>)state;
t.Item1.WriteLine(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync()
{
return WriteAsync(CoreNewLine);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task FlushAsync()
{
return Task.Factory.StartNew(state =>
{
((TextWriter)state).Flush();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
#endregion
[Serializable]
private sealed class NullTextWriter : TextWriter
{
internal NullTextWriter(): base(CultureInfo.InvariantCulture) {
}
public override Encoding Encoding {
get { return Encoding.Default; }
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void Write(char[] buffer, int index, int count) {
}
public override void Write(String value) {
}
// Not strictly necessary, but for perf reasons
public override void WriteLine() {
}
// Not strictly necessary, but for perf reasons
public override void WriteLine(String value) {
}
public override void WriteLine(Object value) {
}
}
[Serializable]
internal sealed class SyncTextWriter : TextWriter, IDisposable
{
private TextWriter _out;
internal SyncTextWriter(TextWriter t): base(t.FormatProvider) {
_out = t;
}
public override Encoding Encoding {
get { return _out.Encoding; }
}
public override IFormatProvider FormatProvider {
get { return _out.FormatProvider; }
}
public override String NewLine {
[MethodImplAttribute(MethodImplOptions.Synchronized)]
get { return _out.NewLine; }
[MethodImplAttribute(MethodImplOptions.Synchronized)]
set { _out.NewLine = value; }
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Close() {
// So that any overriden Close() gets run
_out.Close();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_out).Dispose();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Flush() {
_out.Flush();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(char value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer) {
_out.Write(buffer);
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer, int index, int count) {
_out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(bool value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(int value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(uint value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(long value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(ulong value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(float value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(double value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(Decimal value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(Object value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object arg0) {
_out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object arg0, Object arg1) {
_out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object arg0, Object arg1, Object arg2) {
_out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object[] arg) {
_out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine() {
_out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(char value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(decimal value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer) {
_out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer, int index, int count) {
_out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(bool value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(int value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(uint value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(long value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(ulong value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(float value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(double value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(Object value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object arg0) {
_out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object arg0, Object arg1) {
_out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object arg0, Object arg1, Object arg2) {
_out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object[] arg) {
_out.WriteLine(format, arg);
}
//
// On SyncTextWriter all APIs should run synchronously, even the async ones.
//
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
Write(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
Write(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
Write(buffer, index, count);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
WriteLine(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
WriteLine(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
WriteLine(buffer, index, count);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task FlushAsync()
{
Flush();
return Task.CompletedTask;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Input;
using Microsoft.Win32;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Utils;
using ICSharpCode.AvalonEdit.Highlighting;
namespace beam
{
class FileViewModel : PaneViewModel
{
static int fileCount = 0;
#region Constructors
public FileViewModel(string filePath)
{
FilePath = filePath;
Load(filePath);
base.Title = Title;
}
public FileViewModel()
{
fileCount = fileCount + 1;
base.Title = "New File " + fileCount;
//this.HighlightDef = HighlightingManager.Instance.GetDefinition("GLSL");
IsDirty = true;
}
private void Load(string path)
{
if (File.Exists(path))
{
this._document = new TextDocument();
//this.HighlightDef = HighlightingManager.Instance.GetDefinition("GLSL");
this._isDirty = false;
//this.IsReadOnly = false;
//this.ShowLineNumbers = false;
//this.WordWrap = false;
// Check file attributes and set to read-only if file attributes indicate that
if ((System.IO.File.GetAttributes(path) & FileAttributes.ReadOnly) != 0)
{
this.IsReadOnly = true;
this.IsReadOnlyReason = "This file cannot be edit because another process is currently writting to it.\n" +
"Change the file access permissions or save the file in a different location if you want to edit it.";
}
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = FileReader.OpenStream(fs, Encoding.UTF8))
{
this._document = new TextDocument(reader.ReadToEnd());
}
}
}
}
#endregion
#region FilePath
private string _filePath = null;
public string FilePath
{
get { return _filePath; }
set
{
if (_filePath != value)
{
_filePath = value;
ContentId = _filePath;
RaisePropertyChanged("FilePath");
RaisePropertyChanged("FileName");
RaisePropertyChanged("Title");
}
}
}
#endregion
#region FileName
public string FileName
{
get
{
if (FilePath == null)
return base.Title;
return System.IO.Path.GetFileName(FilePath);
}
}
#endregion FileName
#region Title
new public string Title
{
get
{
return FileName + (this.IsDirty == true ? "*" : string.Empty);
}
set
{
base.Title = value;
}
}
#endregion
#region Document
private TextDocument _document = null;
public TextDocument Document
{
get { return this._document; }
set
{
if (this._document != value)
{
this._document = value;
RaisePropertyChanged("Document");
IsDirty = true;
}
}
}
#endregion
#region IsDirty
private bool _isDirty = false;
public bool IsDirty
{
get { return _isDirty; }
set
{
if (_isDirty != value)
{
_isDirty = value;
RaisePropertyChanged("IsDirty");
RaisePropertyChanged("Title");
}
}
}
#endregion
#region IsReadOnly
private bool mIsReadOnly = false;
public bool IsReadOnly
{
get
{
return this.mIsReadOnly;
}
protected set
{
if (this.mIsReadOnly != value)
{
this.mIsReadOnly = value;
this.RaisePropertyChanged("IsReadOnly");
}
}
}
private string mIsReadOnlyReason = string.Empty;
public string IsReadOnlyReason
{
get
{
return this.mIsReadOnlyReason;
}
protected set
{
if (this.mIsReadOnlyReason != value)
{
this.mIsReadOnlyReason = value;
this.RaisePropertyChanged("IsReadOnlyReason");
}
}
}
#endregion IsReadOnly
#region SaveCommand
RelayCommand _saveCommand = null;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand((p) => OnSave(p), (p) => CanSave(p));
}
return _saveCommand;
}
}
private bool CanSave(object parameter)
{
return IsDirty;
}
private void OnSave(object parameter)
{
Workspace.This.Save(this, false);
}
#endregion
#region SaveAsCommand
RelayCommand _saveAsCommand = null;
public ICommand SaveAsCommand
{
get
{
if (_saveAsCommand == null)
{
_saveAsCommand = new RelayCommand((p) => OnSaveAs(p), (p) => CanSaveAs(p));
}
return _saveAsCommand;
}
}
private bool CanSaveAs(object parameter)
{
return true;
}
private void OnSaveAs(object parameter)
{
Workspace.This.Save(this, true);
}
#endregion
#region CloseCommand
RelayCommand _closeCommand = null;
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
{
_closeCommand = new RelayCommand((p) => OnClose(), (p) => CanClose());
}
return _closeCommand;
}
}
private bool CanClose()
{
return true;
}
private void OnClose()
{
Workspace.This.Close(this);
}
#endregion
#region HighlightingDefinition
private IHighlightingDefinition _highlightdef = null;
public IHighlightingDefinition HighlightDef
{
get { return this._highlightdef; }
set
{
if (this._highlightdef != value)
{
this._highlightdef = value;
RaisePropertyChanged("HighlightDef");
IsDirty = true;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Date;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Pkix
{
/// <summary>
/// Summary description for PkixParameters.
/// </summary>
public class PkixParameters
// : ICertPathParameters
{
/**
* This is the default PKIX validity model. Actually there are two variants
* of this: The PKIX model and the modified PKIX model. The PKIX model
* verifies that all involved certificates must have been valid at the
* current time. The modified PKIX model verifies that all involved
* certificates were valid at the signing time. Both are indirectly choosen
* with the {@link PKIXParameters#setDate(java.util.Date)} method, so this
* methods sets the Date when <em>all</em> certificates must have been
* valid.
*/
public const int PkixValidityModel = 0;
/**
* This model uses the following validity model. Each certificate must have
* been valid at the moment where is was used. That means the end
* certificate must have been valid at the time the signature was done. The
* CA certificate which signed the end certificate must have been valid,
* when the end certificate was signed. The CA (or Root CA) certificate must
* have been valid, when the CA certificate was signed and so on. So the
* {@link PKIXParameters#setDate(java.util.Date)} method sets the time, when
* the <em>end certificate</em> must have been valid. <p/> It is used e.g.
* in the German signature law.
*/
public const int ChainValidityModel = 1;
private ISet trustAnchors;
private DateTimeObject date;
private IList certPathCheckers;
private bool revocationEnabled = true;
private ISet initialPolicies;
//private bool checkOnlyEECertificateCrl = false;
private bool explicitPolicyRequired = false;
private bool anyPolicyInhibited = false;
private bool policyMappingInhibited = false;
private bool policyQualifiersRejected = true;
private IX509Selector certSelector;
private IList stores;
private IX509Selector selector;
private bool additionalLocationsEnabled;
private IList additionalStores;
private ISet trustedACIssuers;
private ISet necessaryACAttributes;
private ISet prohibitedACAttributes;
private ISet attrCertCheckers;
private int validityModel = PkixValidityModel;
private bool useDeltas = false;
/**
* Creates an instance of PKIXParameters with the specified Set of
* most-trusted CAs. Each element of the set is a TrustAnchor.<br />
* <br />
* Note that the Set is copied to protect against subsequent modifications.
*
* @param trustAnchors
* a Set of TrustAnchors
*
* @exception InvalidAlgorithmParameterException
* if the specified Set is empty
* <code>(trustAnchors.isEmpty() == true)</code>
* @exception NullPointerException
* if the specified Set is <code>null</code>
* @exception ClassCastException
* if any of the elements in the Set are not of type
* <code>java.security.cert.TrustAnchor</code>
*/
public PkixParameters(
ISet trustAnchors)
{
SetTrustAnchors(trustAnchors);
this.initialPolicies = new HashSet();
this.certPathCheckers = Platform.CreateArrayList();
this.stores = Platform.CreateArrayList();
this.additionalStores = Platform.CreateArrayList();
this.trustedACIssuers = new HashSet();
this.necessaryACAttributes = new HashSet();
this.prohibitedACAttributes = new HashSet();
this.attrCertCheckers = new HashSet();
}
// // TODO implement for other keystores (see Java build)?
// /**
// * Creates an instance of <code>PKIXParameters</code> that
// * populates the set of most-trusted CAs from the trusted
// * certificate entries contained in the specified <code>KeyStore</code>.
// * Only keystore entries that contain trusted <code>X509Certificates</code>
// * are considered; all other certificate types are ignored.
// *
// * @param keystore a <code>KeyStore</code> from which the set of
// * most-trusted CAs will be populated
// * @throws KeyStoreException if the keystore has not been initialized
// * @throws InvalidAlgorithmParameterException if the keystore does
// * not contain at least one trusted certificate entry
// * @throws NullPointerException if the keystore is <code>null</code>
// */
// public PkixParameters(
// Pkcs12Store keystore)
//// throws KeyStoreException, InvalidAlgorithmParameterException
// {
// if (keystore == null)
// throw new ArgumentNullException("keystore");
// ISet trustAnchors = new HashSet();
// foreach (string alias in keystore.Aliases)
// {
// if (keystore.IsCertificateEntry(alias))
// {
// X509CertificateEntry x509Entry = keystore.GetCertificate(alias);
// trustAnchors.Add(new TrustAnchor(x509Entry.Certificate, null));
// }
// }
// SetTrustAnchors(trustAnchors);
//
// this.initialPolicies = new HashSet();
// this.certPathCheckers = new ArrayList();
// this.stores = new ArrayList();
// this.additionalStores = new ArrayList();
// this.trustedACIssuers = new HashSet();
// this.necessaryACAttributes = new HashSet();
// this.prohibitedACAttributes = new HashSet();
// this.attrCertCheckers = new HashSet();
// }
public virtual bool IsRevocationEnabled
{
get { return revocationEnabled; }
set { revocationEnabled = value; }
}
public virtual bool IsExplicitPolicyRequired
{
get { return explicitPolicyRequired; }
set { this.explicitPolicyRequired = value; }
}
public virtual bool IsAnyPolicyInhibited
{
get { return anyPolicyInhibited; }
set { this.anyPolicyInhibited = value; }
}
public virtual bool IsPolicyMappingInhibited
{
get { return policyMappingInhibited; }
set { this.policyMappingInhibited = value; }
}
public virtual bool IsPolicyQualifiersRejected
{
get { return policyQualifiersRejected; }
set { this.policyQualifiersRejected = value; }
}
//public bool IsCheckOnlyEECertificateCrl
//{
// get { return this.checkOnlyEECertificateCrl; }
// set { this.checkOnlyEECertificateCrl = value; }
//}
public virtual DateTimeObject Date
{
get { return this.date; }
set { this.date = value; }
}
// Returns a Set of the most-trusted CAs.
public virtual ISet GetTrustAnchors()
{
return new HashSet(this.trustAnchors);
}
// Sets the set of most-trusted CAs.
// Set is copied to protect against subsequent modifications.
public virtual void SetTrustAnchors(
ISet tas)
{
if (tas == null)
throw new ArgumentNullException("value");
if (tas.IsEmpty)
throw new ArgumentException("non-empty set required", "value");
// Explicit copy to enforce type-safety
this.trustAnchors = new HashSet();
foreach (TrustAnchor ta in tas)
{
if (ta != null)
{
trustAnchors.Add(ta);
}
}
}
/**
* Returns the required constraints on the target certificate. The
* constraints are returned as an instance of CertSelector. If
* <code>null</code>, no constraints are defined.<br />
* <br />
* Note that the CertSelector returned is cloned to protect against
* subsequent modifications.
*
* @return a CertSelector specifying the constraints on the target
* certificate (or <code>null</code>)
*
* @see #setTargetCertConstraints(CertSelector)
*/
public virtual X509CertStoreSelector GetTargetCertConstraints()
{
if (certSelector == null)
{
return null;
}
return (X509CertStoreSelector)certSelector.Clone();
}
/**
* Sets the required constraints on the target certificate. The constraints
* are specified as an instance of CertSelector. If null, no constraints are
* defined.<br />
* <br />
* Note that the CertSelector specified is cloned to protect against
* subsequent modifications.
*
* @param selector
* a CertSelector specifying the constraints on the target
* certificate (or <code>null</code>)
*
* @see #getTargetCertConstraints()
*/
public virtual void SetTargetCertConstraints(
IX509Selector selector)
{
if (selector == null)
{
certSelector = null;
}
else
{
certSelector = (IX509Selector)selector.Clone();
}
}
/**
* Returns an immutable Set of initial policy identifiers (OID strings),
* indicating that any one of these policies would be acceptable to the
* certificate user for the purposes of certification path processing. The
* default return value is an empty <code>Set</code>, which is
* interpreted as meaning that any policy would be acceptable.
*
* @return an immutable <code>Set</code> of initial policy OIDs in String
* format, or an empty <code>Set</code> (implying any policy is
* acceptable). Never returns <code>null</code>.
*
* @see #setInitialPolicies(java.util.Set)
*/
public virtual ISet GetInitialPolicies()
{
ISet returnSet = initialPolicies;
// TODO Can it really be null?
if (initialPolicies == null)
{
returnSet = new HashSet();
}
return new HashSet(returnSet);
}
/**
* Sets the <code>Set</code> of initial policy identifiers (OID strings),
* indicating that any one of these policies would be acceptable to the
* certificate user for the purposes of certification path processing. By
* default, any policy is acceptable (i.e. all policies), so a user that
* wants to allow any policy as acceptable does not need to call this
* method, or can call it with an empty <code>Set</code> (or
* <code>null</code>).<br />
* <br />
* Note that the Set is copied to protect against subsequent modifications.<br />
* <br />
*
* @param initialPolicies
* a Set of initial policy OIDs in String format (or
* <code>null</code>)
*
* @exception ClassCastException
* if any of the elements in the set are not of type String
*
* @see #getInitialPolicies()
*/
public virtual void SetInitialPolicies(
ISet initialPolicies)
{
this.initialPolicies = new HashSet();
if (initialPolicies != null)
{
foreach (string obj in initialPolicies)
{
if (obj != null)
{
this.initialPolicies.Add(obj);
}
}
}
}
/**
* Sets a <code>List</code> of additional certification path checkers. If
* the specified List contains an object that is not a PKIXCertPathChecker,
* it is ignored.<br />
* <br />
* Each <code>PKIXCertPathChecker</code> specified implements additional
* checks on a certificate. Typically, these are checks to process and
* verify private extensions contained in certificates. Each
* <code>PKIXCertPathChecker</code> should be instantiated with any
* initialization parameters needed to execute the check.<br />
* <br />
* This method allows sophisticated applications to extend a PKIX
* <code>CertPathValidator</code> or <code>CertPathBuilder</code>. Each
* of the specified PKIXCertPathCheckers will be called, in turn, by a PKIX
* <code>CertPathValidator</code> or <code>CertPathBuilder</code> for
* each certificate processed or validated.<br />
* <br />
* Regardless of whether these additional PKIXCertPathCheckers are set, a
* PKIX <code>CertPathValidator</code> or <code>CertPathBuilder</code>
* must perform all of the required PKIX checks on each certificate. The one
* exception to this rule is if the RevocationEnabled flag is set to false
* (see the {@link #setRevocationEnabled(boolean) setRevocationEnabled}
* method).<br />
* <br />
* Note that the List supplied here is copied and each PKIXCertPathChecker
* in the list is cloned to protect against subsequent modifications.
*
* @param checkers
* a List of PKIXCertPathCheckers. May be null, in which case no
* additional checkers will be used.
* @exception ClassCastException
* if any of the elements in the list are not of type
* <code>java.security.cert.PKIXCertPathChecker</code>
* @see #getCertPathCheckers()
*/
public virtual void SetCertPathCheckers(IList checkers)
{
certPathCheckers = Platform.CreateArrayList();
if (checkers != null)
{
foreach (PkixCertPathChecker obj in checkers)
{
certPathCheckers.Add(obj.Clone());
}
}
}
/**
* Returns the List of certification path checkers. Each PKIXCertPathChecker
* in the returned IList is cloned to protect against subsequent modifications.
*
* @return an immutable List of PKIXCertPathCheckers (may be empty, but not
* <code>null</code>)
*
* @see #setCertPathCheckers(java.util.List)
*/
public virtual IList GetCertPathCheckers()
{
IList checkers = Platform.CreateArrayList();
foreach (PkixCertPathChecker obj in certPathCheckers)
{
checkers.Add(obj.Clone());
}
return checkers;
}
/**
* Adds a <code>PKIXCertPathChecker</code> to the list of certification
* path checkers. See the {@link #setCertPathCheckers setCertPathCheckers}
* method for more details.
* <p>
* Note that the <code>PKIXCertPathChecker</code> is cloned to protect
* against subsequent modifications.</p>
*
* @param checker a <code>PKIXCertPathChecker</code> to add to the list of
* checks. If <code>null</code>, the checker is ignored (not added to list).
*/
public virtual void AddCertPathChecker(
PkixCertPathChecker checker)
{
if (checker != null)
{
certPathCheckers.Add(checker.Clone());
}
}
public virtual object Clone()
{
// FIXME Check this whole method against the Java implementation!
PkixParameters parameters = new PkixParameters(GetTrustAnchors());
parameters.SetParams(this);
return parameters;
// PkixParameters obj = new PkixParameters(new HashSet());
//// (PkixParameters) this.MemberwiseClone();
// obj.x509Stores = new ArrayList(x509Stores);
// obj.certPathCheckers = new ArrayList(certPathCheckers);
//
// //Iterator iter = certPathCheckers.iterator();
// //obj.certPathCheckers = new ArrayList();
// //while (iter.hasNext())
// //{
// // obj.certPathCheckers.add(((PKIXCertPathChecker)iter.next())
// // .clone());
// //}
// //if (initialPolicies != null)
// //{
// // obj.initialPolicies = new HashSet(initialPolicies);
// //}
//// if (trustAnchors != null)
//// {
//// obj.trustAnchors = new HashSet(trustAnchors);
//// }
//// if (certSelector != null)
//// {
//// obj.certSelector = (X509CertStoreSelector) certSelector.Clone();
//// }
// return obj;
}
/**
* Method to support <code>Clone()</code> under J2ME.
* <code>super.Clone()</code> does not exist and fields are not copied.
*
* @param params Parameters to set. If this are
* <code>ExtendedPkixParameters</code> they are copied to.
*/
protected virtual void SetParams(
PkixParameters parameters)
{
Date = parameters.Date;
SetCertPathCheckers(parameters.GetCertPathCheckers());
IsAnyPolicyInhibited = parameters.IsAnyPolicyInhibited;
IsExplicitPolicyRequired = parameters.IsExplicitPolicyRequired;
IsPolicyMappingInhibited = parameters.IsPolicyMappingInhibited;
IsRevocationEnabled = parameters.IsRevocationEnabled;
SetInitialPolicies(parameters.GetInitialPolicies());
IsPolicyQualifiersRejected = parameters.IsPolicyQualifiersRejected;
SetTargetCertConstraints(parameters.GetTargetCertConstraints());
SetTrustAnchors(parameters.GetTrustAnchors());
validityModel = parameters.validityModel;
useDeltas = parameters.useDeltas;
additionalLocationsEnabled = parameters.additionalLocationsEnabled;
selector = parameters.selector == null ? null
: (IX509Selector) parameters.selector.Clone();
stores = Platform.CreateArrayList(parameters.stores);
additionalStores = Platform.CreateArrayList(parameters.additionalStores);
trustedACIssuers = new HashSet(parameters.trustedACIssuers);
prohibitedACAttributes = new HashSet(parameters.prohibitedACAttributes);
necessaryACAttributes = new HashSet(parameters.necessaryACAttributes);
attrCertCheckers = new HashSet(parameters.attrCertCheckers);
}
/**
* Whether delta CRLs should be used for checking the revocation status.
* Defaults to <code>false</code>.
*/
public virtual bool IsUseDeltasEnabled
{
get { return useDeltas; }
set { useDeltas = value; }
}
/**
* The validity model.
* @see #CHAIN_VALIDITY_MODEL
* @see #PKIX_VALIDITY_MODEL
*/
public virtual int ValidityModel
{
get { return validityModel; }
set { validityModel = value; }
}
/**
* Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute
* certificates or cross certificates.
* <p>
* The <code>IList</code> is cloned.
* </p>
*
* @param stores A list of stores to use.
* @see #getStores
* @throws ClassCastException if an element of <code>stores</code> is not
* a {@link Store}.
*/
public virtual void SetStores(
IList stores)
{
if (stores == null)
{
this.stores = Platform.CreateArrayList();
}
else
{
foreach (object obj in stores)
{
if (!(obj is IX509Store))
{
throw new InvalidCastException(
"All elements of list must be of type " + typeof(IX509Store).FullName);
}
}
this.stores = Platform.CreateArrayList(stores);
}
}
/**
* Adds a Bouncy Castle {@link Store} to find CRLs, certificates, attribute
* certificates or cross certificates.
* <p>
* This method should be used to add local stores, like collection based
* X.509 stores, if available. Local stores should be considered first,
* before trying to use additional (remote) locations, because they do not
* need possible additional network traffic.
* </p><p>
* If <code>store</code> is <code>null</code> it is ignored.
* </p>
*
* @param store The store to add.
* @see #getStores
*/
public virtual void AddStore(
IX509Store store)
{
if (store != null)
{
stores.Add(store);
}
}
/**
* Adds an additional Bouncy Castle {@link Store} to find CRLs, certificates,
* attribute certificates or cross certificates.
* <p>
* You should not use this method. This method is used for adding additional
* X.509 stores, which are used to add (remote) locations, e.g. LDAP, found
* during X.509 object processing, e.g. in certificates or CRLs. This method
* is used in PKIX certification path processing.
* </p><p>
* If <code>store</code> is <code>null</code> it is ignored.
* </p>
*
* @param store The store to add.
* @see #getStores()
*/
public virtual void AddAdditionalStore(
IX509Store store)
{
if (store != null)
{
additionalStores.Add(store);
}
}
/**
* Returns an <code>IList</code> of additional Bouncy Castle
* <code>Store</code>s used for finding CRLs, certificates, attribute
* certificates or cross certificates.
*
* @return an immutable <code>IList</code> of additional Bouncy Castle
* <code>Store</code>s. Never <code>null</code>.
*
* @see #addAddionalStore(Store)
*/
public virtual IList GetAdditionalStores()
{
return Platform.CreateArrayList(additionalStores);
}
/**
* Returns an <code>IList</code> of Bouncy Castle
* <code>Store</code>s used for finding CRLs, certificates, attribute
* certificates or cross certificates.
*
* @return an immutable <code>IList</code> of Bouncy Castle
* <code>Store</code>s. Never <code>null</code>.
*
* @see #setStores(IList)
*/
public virtual IList GetStores()
{
return Platform.CreateArrayList(stores);
}
/**
* Returns if additional {@link X509Store}s for locations like LDAP found
* in certificates or CRLs should be used.
*
* @return Returns <code>true</code> if additional stores are used.
*/
public virtual bool IsAdditionalLocationsEnabled
{
get { return additionalLocationsEnabled; }
}
/**
* Sets if additional {@link X509Store}s for locations like LDAP found in
* certificates or CRLs should be used.
*
* @param enabled <code>true</code> if additional stores are used.
*/
public virtual void SetAdditionalLocationsEnabled(
bool enabled)
{
additionalLocationsEnabled = enabled;
}
/**
* Returns the required constraints on the target certificate or attribute
* certificate. The constraints are returned as an instance of
* <code>IX509Selector</code>. If <code>null</code>, no constraints are
* defined.
*
* <p>
* The target certificate in a PKIX path may be a certificate or an
* attribute certificate.
* </p><p>
* Note that the <code>IX509Selector</code> returned is cloned to protect
* against subsequent modifications.
* </p>
* @return a <code>IX509Selector</code> specifying the constraints on the
* target certificate or attribute certificate (or <code>null</code>)
* @see #setTargetConstraints
* @see X509CertStoreSelector
* @see X509AttributeCertStoreSelector
*/
public virtual IX509Selector GetTargetConstraints()
{
if (selector != null)
{
return (IX509Selector) selector.Clone();
}
else
{
return null;
}
}
/**
* Sets the required constraints on the target certificate or attribute
* certificate. The constraints are specified as an instance of
* <code>IX509Selector</code>. If <code>null</code>, no constraints are
* defined.
* <p>
* The target certificate in a PKIX path may be a certificate or an
* attribute certificate.
* </p><p>
* Note that the <code>IX509Selector</code> specified is cloned to protect
* against subsequent modifications.
* </p>
*
* @param selector a <code>IX509Selector</code> specifying the constraints on
* the target certificate or attribute certificate (or
* <code>null</code>)
* @see #getTargetConstraints
* @see X509CertStoreSelector
* @see X509AttributeCertStoreSelector
*/
public virtual void SetTargetConstraints(IX509Selector selector)
{
if (selector != null)
{
this.selector = (IX509Selector) selector.Clone();
}
else
{
this.selector = null;
}
}
/**
* Returns the trusted attribute certificate issuers. If attribute
* certificates is verified the trusted AC issuers must be set.
* <p>
* The returned <code>ISet</code> consists of <code>TrustAnchor</code>s.
* </p><p>
* The returned <code>ISet</code> is immutable. Never <code>null</code>
* </p>
*
* @return Returns an immutable set of the trusted AC issuers.
*/
public virtual ISet GetTrustedACIssuers()
{
return new HashSet(trustedACIssuers);
}
/**
* Sets the trusted attribute certificate issuers. If attribute certificates
* is verified the trusted AC issuers must be set.
* <p>
* The <code>trustedACIssuers</code> must be a <code>ISet</code> of
* <code>TrustAnchor</code>
* </p><p>
* The given set is cloned.
* </p>
*
* @param trustedACIssuers The trusted AC issuers to set. Is never
* <code>null</code>.
* @throws ClassCastException if an element of <code>stores</code> is not
* a <code>TrustAnchor</code>.
*/
public virtual void SetTrustedACIssuers(
ISet trustedACIssuers)
{
if (trustedACIssuers == null)
{
this.trustedACIssuers = new HashSet();
}
else
{
foreach (object obj in trustedACIssuers)
{
if (!(obj is TrustAnchor))
{
throw new InvalidCastException("All elements of set must be "
+ "of type " + typeof(TrustAnchor).Name + ".");
}
}
this.trustedACIssuers = new HashSet(trustedACIssuers);
}
}
/**
* Returns the necessary attributes which must be contained in an attribute
* certificate.
* <p>
* The returned <code>ISet</code> is immutable and contains
* <code>String</code>s with the OIDs.
* </p>
*
* @return Returns the necessary AC attributes.
*/
public virtual ISet GetNecessaryACAttributes()
{
return new HashSet(necessaryACAttributes);
}
/**
* Sets the necessary which must be contained in an attribute certificate.
* <p>
* The <code>ISet</code> must contain <code>String</code>s with the
* OIDs.
* </p><p>
* The set is cloned.
* </p>
*
* @param necessaryACAttributes The necessary AC attributes to set.
* @throws ClassCastException if an element of
* <code>necessaryACAttributes</code> is not a
* <code>String</code>.
*/
public virtual void SetNecessaryACAttributes(
ISet necessaryACAttributes)
{
if (necessaryACAttributes == null)
{
this.necessaryACAttributes = new HashSet();
}
else
{
foreach (object obj in necessaryACAttributes)
{
if (!(obj is string))
{
throw new InvalidCastException("All elements of set must be "
+ "of type string.");
}
}
this.necessaryACAttributes = new HashSet(necessaryACAttributes);
}
}
/**
* Returns the attribute certificates which are not allowed.
* <p>
* The returned <code>ISet</code> is immutable and contains
* <code>String</code>s with the OIDs.
* </p>
*
* @return Returns the prohibited AC attributes. Is never <code>null</code>.
*/
public virtual ISet GetProhibitedACAttributes()
{
return new HashSet(prohibitedACAttributes);
}
/**
* Sets the attribute certificates which are not allowed.
* <p>
* The <code>ISet</code> must contain <code>String</code>s with the
* OIDs.
* </p><p>
* The set is cloned.
* </p>
*
* @param prohibitedACAttributes The prohibited AC attributes to set.
* @throws ClassCastException if an element of
* <code>prohibitedACAttributes</code> is not a
* <code>String</code>.
*/
public virtual void SetProhibitedACAttributes(
ISet prohibitedACAttributes)
{
if (prohibitedACAttributes == null)
{
this.prohibitedACAttributes = new HashSet();
}
else
{
foreach (object obj in prohibitedACAttributes)
{
if (!(obj is String))
{
throw new InvalidCastException("All elements of set must be "
+ "of type string.");
}
}
this.prohibitedACAttributes = new HashSet(prohibitedACAttributes);
}
}
/**
* Returns the attribute certificate checker. The returned set contains
* {@link PKIXAttrCertChecker}s and is immutable.
*
* @return Returns the attribute certificate checker. Is never
* <code>null</code>.
*/
public virtual ISet GetAttrCertCheckers()
{
return new HashSet(attrCertCheckers);
}
/**
* Sets the attribute certificate checkers.
* <p>
* All elements in the <code>ISet</code> must a {@link PKIXAttrCertChecker}.
* </p>
* <p>
* The given set is cloned.
* </p>
*
* @param attrCertCheckers The attribute certificate checkers to set. Is
* never <code>null</code>.
* @throws ClassCastException if an element of <code>attrCertCheckers</code>
* is not a <code>PKIXAttrCertChecker</code>.
*/
public virtual void SetAttrCertCheckers(
ISet attrCertCheckers)
{
if (attrCertCheckers == null)
{
this.attrCertCheckers = new HashSet();
}
else
{
foreach (object obj in attrCertCheckers)
{
if (!(obj is PkixAttrCertChecker))
{
throw new InvalidCastException("All elements of set must be "
+ "of type " + typeof(PkixAttrCertChecker).FullName + ".");
}
}
this.attrCertCheckers = new HashSet(attrCertCheckers);
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'StatusPerkawinan'
// Generated by LLBLGen v1.21.2003.712 Final on: Thursday, October 11, 2007, 2:03:11 AM
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace BkNet.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'StatusPerkawinan'.
/// </summary>
public class StatusPerkawinan : DBInteractionBase
{
#region Class Member Declarations
private SqlBoolean _published;
private SqlDateTime _createdDate, _modifiedDate;
private SqlInt32 _createdBy, _modifiedBy, _ordering, _id;
private SqlString _kode, _nama, _keterangan;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public StatusPerkawinan()
{
// Nothing for now.
}
/// <summary>
/// Purpose: IsExist method. This method will check Exsisting data from database.
/// </summary>
/// <returns></returns>
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist == 1;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (Int32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (Int32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (Int32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>Id</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy</LI>
/// <LI>ModifiedDate</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("StatusPerkawinan");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (Int32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_SelectOne' reported the ErrorCode: " + _errorCode);
}
if (toReturn.Rows.Count > 0)
{
_id = (Int32)toReturn.Rows[0]["Id"];
_kode = (string)toReturn.Rows[0]["Kode"];
_nama = (string)toReturn.Rows[0]["Nama"];
_keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"];
_published = (bool)toReturn.Rows[0]["Published"];
_ordering = (Int32)toReturn.Rows[0]["Ordering"];
_createdBy = (Int32)toReturn.Rows[0]["CreatedBy"];
_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
_modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"];
_modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"];
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("StatusPerkawinan");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (Int32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: GetList method. This method will Select all rows from the table where is active.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable GetList()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[StatusPerkawinan_GetList]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("StatusPerkawinan");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if (_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'StatusPerkawinan_GetList' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch (Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("StatusPerkawinan::GetList::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 Id
{
get
{
return _id;
}
set
{
SqlInt32 idTmp = (SqlInt32)value;
if (idTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Id", "Id can't be NULL");
}
_id = value;
}
}
public SqlString Kode
{
get
{
return _kode;
}
set
{
SqlString kodeTmp = (SqlString)value;
if (kodeTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL");
}
_kode = value;
}
}
public SqlString Nama
{
get
{
return _nama;
}
set
{
SqlString namaTmp = (SqlString)value;
if (namaTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL");
}
_nama = value;
}
}
public SqlString Keterangan
{
get
{
return _keterangan;
}
set
{
_keterangan = value;
}
}
public SqlBoolean Published
{
get
{
return _published;
}
set
{
_published = value;
}
}
public SqlInt32 Ordering
{
get
{
return _ordering;
}
set
{
SqlInt32 orderingTmp = (SqlInt32)value;
if (orderingTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL");
}
_ordering = value;
}
}
public SqlInt32 CreatedBy
{
get
{
return _createdBy;
}
set
{
SqlInt32 createdByTmp = (SqlInt32)value;
if (createdByTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL");
}
_createdBy = value;
}
}
public SqlDateTime CreatedDate
{
get
{
return _createdDate;
}
set
{
SqlDateTime createdDateTmp = (SqlDateTime)value;
if (createdDateTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL");
}
_createdDate = value;
}
}
public SqlInt32 ModifiedBy
{
get
{
return _modifiedBy;
}
set
{
_modifiedBy = value;
}
}
public SqlDateTime ModifiedDate
{
get
{
return _modifiedDate;
}
set
{
_modifiedDate = value;
}
}
#endregion
}
}
| |
using System;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime
{
/// <summary>
/// This interface is for use with the Orleans timers.
/// </summary>
internal interface ITimebound
{
/// <summary>
/// This method is called by the timer when the time out is reached.
/// </summary>
void OnTimeout();
TimeSpan RequestedTimeout();
}
internal class CallbackData : ITimebound, IDisposable
{
private readonly Action<Message, TaskCompletionSource<object>> callback;
private readonly Func<Message, bool> resendFunc;
private readonly Action<Message> unregister;
private readonly TaskCompletionSource<object> context;
private readonly IMessagingConfiguration config;
private bool alreadyFired;
private TimeSpan timeout;
private SafeTimer timer;
private ITimeInterval timeSinceIssued;
private static readonly Logger logger = LogManager.GetLogger("CallbackData");
public Message Message { get; set; } // might hold metadata used by response pipeline
public CallbackData(
Action<Message, TaskCompletionSource<object>> callback,
Func<Message, bool> resendFunc,
TaskCompletionSource<object> ctx,
Message msg,
Action<Message> unregisterDelegate,
IMessagingConfiguration config)
{
// We are never called without a callback func, but best to double check.
if (callback == null) throw new ArgumentNullException(nameof(callback));
// We are never called without a resend func, but best to double check.
if (resendFunc == null) throw new ArgumentNullException(nameof(resendFunc));
this.callback = callback;
this.resendFunc = resendFunc;
context = ctx;
Message = msg;
unregister = unregisterDelegate;
alreadyFired = false;
this.config = config;
}
/// <summary>
/// Start this callback timer
/// </summary>
/// <param name="time">Timeout time</param>
public void StartTimer(TimeSpan time)
{
if (time < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(time), "The timeout parameter is negative.");
timeout = time;
if (StatisticsCollector.CollectApplicationRequestsStats)
{
timeSinceIssued = TimeIntervalFactory.CreateTimeInterval(true);
timeSinceIssued.Start();
}
TimeSpan firstPeriod = timeout;
TimeSpan repeatPeriod = Constants.INFINITE_TIMESPAN; // Single timeout period --> No repeat
if (config.ResendOnTimeout && config.MaxResendCount > 0)
{
firstPeriod = repeatPeriod = timeout.Divide(config.MaxResendCount + 1);
}
// Start time running
DisposeTimer();
timer = new SafeTimer(TimeoutCallback, null, firstPeriod, repeatPeriod);
}
private void TimeoutCallback(object obj)
{
OnTimeout();
}
public void OnTimeout()
{
if (alreadyFired)
return;
var msg = Message; // Local working copy
string messageHistory = msg.GetTargetHistory();
string errorMsg = $"Response did not arrive on time in {timeout} for message: {msg}. Target History is: {messageHistory}.";
logger.Warn(ErrorCode.Runtime_Error_100157, "{0} About to break its promise.", errorMsg);
var error = Message.CreatePromptExceptionResponse(msg, new TimeoutException(errorMsg));
OnFail(msg, error, "OnTimeout - Resend {0} for {1}", true);
}
public void OnTargetSiloFail()
{
if (alreadyFired)
return;
var msg = Message;
var messageHistory = msg.GetTargetHistory();
string errorMsg =
$"The target silo became unavailable for message: {msg}. Target History is: {messageHistory}. See {Constants.TroubleshootingHelpLink} for troubleshooting help.";
logger.Warn(ErrorCode.Runtime_Error_100157, "{0} About to break its promise.", errorMsg);
var error = Message.CreatePromptExceptionResponse(msg, new SiloUnavailableException(errorMsg));
OnFail(msg, error, "On silo fail - Resend {0} for {1}");
}
public void DoCallback(Message response)
{
if (alreadyFired)
return;
lock (this)
{
if (alreadyFired)
return;
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.Transient)
{
if (resendFunc(Message))
{
return;
}
}
alreadyFired = true;
DisposeTimer();
if (StatisticsCollector.CollectApplicationRequestsStats)
{
timeSinceIssued.Stop();
}
unregister?.Invoke(Message);
}
if (StatisticsCollector.CollectApplicationRequestsStats)
{
ApplicationRequestsStatisticsGroup.OnAppRequestsEnd(timeSinceIssued.Elapsed);
}
// do callback outside the CallbackData lock. Just not a good practice to hold a lock for this unrelated operation.
callback(response, context);
}
public void Dispose()
{
DisposeTimer();
GC.SuppressFinalize(this);
}
private void DisposeTimer()
{
try
{
var tmp = timer;
if (tmp != null)
{
timer = null;
tmp.Dispose();
}
}
catch (Exception) { } // Ignore any problems with Dispose
}
private void OnFail(Message msg, Message error, string resendLogMessageFormat, bool isOnTimeout = false)
{
lock (this)
{
if (alreadyFired)
return;
if (config.ResendOnTimeout && resendFunc(msg))
{
if (logger.IsVerbose) logger.Verbose(resendLogMessageFormat, msg.ResendCount, msg);
return;
}
alreadyFired = true;
DisposeTimer();
if (StatisticsCollector.CollectApplicationRequestsStats)
{
timeSinceIssued.Stop();
}
unregister?.Invoke(Message);
}
if (StatisticsCollector.CollectApplicationRequestsStats)
{
ApplicationRequestsStatisticsGroup.OnAppRequestsEnd(timeSinceIssued.Elapsed);
if (isOnTimeout)
{
ApplicationRequestsStatisticsGroup.OnAppRequestsTimedOut();
}
}
callback(error, context);
}
public TimeSpan RequestedTimeout()
{
return timeout;
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using Mono.Cecil;
namespace Mono.Collections.Generic {
public class Collection<T> : IList<T>, IList {
internal T [] items;
internal int size;
int version;
public int Count {
get { return size; }
}
public T this [int index] {
get {
if (index >= size)
throw new ArgumentOutOfRangeException ();
return items [index];
}
set {
CheckIndex (index);
if (index == size)
throw new ArgumentOutOfRangeException ();
OnSet (value, index);
items [index] = value;
}
}
public int Capacity {
get { return items.Length; }
set {
if (value < 0 || value < size)
throw new ArgumentOutOfRangeException ();
Resize (value);
}
}
bool ICollection<T>.IsReadOnly {
get { return false; }
}
bool IList.IsFixedSize {
get { return false; }
}
bool IList.IsReadOnly {
get { return false; }
}
object IList.this [int index] {
get { return this [index]; }
set {
CheckIndex (index);
try {
this [index] = (T) value;
return;
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
throw new ArgumentException ();
}
}
int ICollection.Count {
get { return Count; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
public Collection ()
{
items = Empty<T>.Array;
}
public Collection (int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException ();
items = new T [capacity];
}
public Collection (ICollection<T> items)
{
if (items == null)
throw new ArgumentNullException ("items");
this.items = new T [items.Count];
items.CopyTo (this.items, 0);
this.size = this.items.Length;
}
public void Add (T item)
{
if (size == items.Length)
Grow (1);
OnAdd (item, size);
items [size++] = item;
version++;
}
public bool Contains (T item)
{
return IndexOf (item) != -1;
}
public int IndexOf (T item)
{
return Array.IndexOf (items, item, 0, size);
}
public void Insert (int index, T item)
{
CheckIndex (index);
if (size == items.Length)
Grow (1);
OnInsert (item, index);
Shift (index, 1);
items [index] = item;
version++;
}
public void RemoveAt (int index)
{
if (index < 0 || index >= size)
throw new ArgumentOutOfRangeException ();
var item = items [index];
OnRemove (item, index);
Shift (index, -1);
Array.Clear (items, size, 1);
version++;
}
public bool Remove (T item)
{
var index = IndexOf (item);
if (index == -1)
return false;
OnRemove (item, index);
Shift (index, -1);
Array.Clear (items, size, 1);
version++;
return true;
}
public void Clear ()
{
OnClear ();
Array.Clear (items, 0, size);
size = 0;
version++;
}
public void CopyTo (T [] array, int arrayIndex)
{
Array.Copy (items, 0, array, arrayIndex, size);
}
public T [] ToArray ()
{
var array = new T [size];
Array.Copy (items, 0, array, 0, size);
return array;
}
void CheckIndex (int index)
{
if (index < 0 || index > size)
throw new ArgumentOutOfRangeException ();
}
void Shift (int start, int delta)
{
if (delta < 0)
start -= delta;
if (start < size)
Array.Copy (items, start, items, start + delta, size - start);
size += delta;
if (delta < 0)
Array.Clear (items, size, -delta);
}
protected virtual void OnAdd (T item, int index)
{
}
protected virtual void OnInsert (T item, int index)
{
}
protected virtual void OnSet (T item, int index)
{
}
protected virtual void OnRemove (T item, int index)
{
}
protected virtual void OnClear ()
{
}
internal virtual void Grow (int desired)
{
int new_size = size + desired;
if (new_size <= items.Length)
return;
const int default_capacity = 4;
new_size = System.Math.Max (
System.Math.Max (items.Length * 2, default_capacity),
new_size);
Resize (new_size);
}
protected void Resize (int new_size)
{
if (new_size == size)
return;
if (new_size < size)
throw new ArgumentOutOfRangeException ();
items = items.Resize (new_size);
}
int IList.Add (object value)
{
try {
Add ((T) value);
return size - 1;
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
throw new ArgumentException ();
}
void IList.Clear ()
{
Clear ();
}
bool IList.Contains (object value)
{
return ((IList) this).IndexOf (value) > -1;
}
int IList.IndexOf (object value)
{
try {
return IndexOf ((T) value);
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
return -1;
}
void IList.Insert (int index, object value)
{
CheckIndex (index);
try {
Insert (index, (T) value);
return;
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
throw new ArgumentException ();
}
void IList.Remove (object value)
{
try {
Remove ((T) value);
} catch (InvalidCastException) {
} catch (NullReferenceException) {
}
}
void IList.RemoveAt (int index)
{
RemoveAt (index);
}
void ICollection.CopyTo (Array array, int index)
{
Array.Copy (items, 0, array, index, size);
}
public Enumerator GetEnumerator ()
{
return new Enumerator (this);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return new Enumerator (this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator ()
{
return new Enumerator (this);
}
public struct Enumerator : IEnumerator<T>, IDisposable {
Collection<T> collection;
T current;
int next;
readonly int version;
public T Current {
get { return current; }
}
object IEnumerator.Current {
get {
CheckState ();
if (next <= 0)
throw new InvalidOperationException ();
return current;
}
}
internal Enumerator (Collection<T> collection)
: this ()
{
this.collection = collection;
this.version = collection.version;
}
public bool MoveNext ()
{
CheckState ();
if (next < 0)
return false;
if (next < collection.size) {
current = collection.items [next++];
return true;
}
next = -1;
return false;
}
public void Reset ()
{
CheckState ();
next = 0;
}
void CheckState ()
{
if (collection == null)
throw new ObjectDisposedException (GetType ().FullName);
if (version != collection.version)
throw new InvalidOperationException ();
}
public void Dispose ()
{
collection = null;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace fyiReporting.RDL
{
///<summary>
/// StyleInfo (borders, fonts, background, padding, ...)
///</summary>
public class StyleInfo: ICloneable
{
// note: all sizes are expressed as points
// _BorderColor
/// <summary>
/// Color of the left border
/// </summary>
public Color BColorLeft; // (Color) Color of the left border
/// <summary>
/// Color of the right border
/// </summary>
public Color BColorRight; // (Color) Color of the right border
/// <summary>
/// Color of the top border
/// </summary>
public Color BColorTop; // (Color) Color of the top border
/// <summary>
/// Color of the bottom border
/// </summary>
public Color BColorBottom; // (Color) Color of the bottom border
// _BorderStyle
/// <summary>
/// Style of the left border
/// </summary>
public BorderStyleEnum BStyleLeft; // (Enum BorderStyle) Style of the left border
/// <summary>
/// Style of the left border
/// </summary>
public BorderStyleEnum BStyleRight; // (Enum BorderStyle) Style of the left border
/// <summary>
/// Style of the top border
/// </summary>
public BorderStyleEnum BStyleTop; // (Enum BorderStyle) Style of the top border
/// <summary>
/// Style of the bottom border
/// </summary>
public BorderStyleEnum BStyleBottom; // (Enum BorderStyle) Style of the bottom border
// _BorderWdith
/// <summary>
/// Width of the left border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthLeft; //(Size) Width of the left border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the right border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthRight; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the right border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthTop; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the bottom border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthBottom; //(Size) Width of the bottom border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Color of the background
/// </summary>
public Color BackgroundColor; //(Color) Color of the background
public string BackgroundColorText; //(Textual Color) Color of the background
/// <summary>
/// The type of background gradient
/// </summary>
public BackgroundGradientTypeEnum BackgroundGradientType; // The type of background gradient
/// <summary>
/// End color for the background gradient.
/// </summary>
/// <summary>
/// The type of background pattern
/// </summary>
public patternTypeEnum PatternType;
public Color BackgroundGradientEndColor; //(Color) End color for the background gradient.
/// <summary>
/// A background image for the report item.
/// </summary>
public PageImage BackgroundImage; // A background image for the report item.
/// <summary>
/// Font style Default: Normal
/// </summary>
public FontStyleEnum FontStyle; // (Enum FontStyle) Font style Default: Normal
/// <summary>
/// Name of the font family Default: Arial
/// </summary>
private string _FontFamily; //(string)Name of the font family Default: Arial -- allow comma separated value?
/// <summary>
/// Point size of the font
/// </summary>
public float FontSize; //(Size) Point size of the font
/// <summary>
/// Thickness of the font
/// </summary>
public FontWeightEnum FontWeight; //(Enum FontWeight) Thickness of the font
/// <summary>
/// Cell format in Excel07 Default: General
/// </summary>
public string _Format; //WRP 28102008 Cell format string
/// <summary>
/// Special text formatting Default: none
/// </summary>
public TextDecorationEnum TextDecoration; // (Enum TextDecoration) Special text formatting Default: none
/// <summary>
/// Horizontal alignment of the text Default: General
/// </summary>
public TextAlignEnum TextAlign; // (Enum TextAlign) Horizontal alignment of the text Default: General
/// <summary>
/// Vertical alignment of the text Default: Top
/// </summary>
public VerticalAlignEnum VerticalAlign; // (Enum VerticalAlign) Vertical alignment of the text Default: Top
/// <summary>
/// The foreground color Default: Black
/// </summary>
public Color Color; // (Color) The foreground color Default: Black
public string ColorText; // (Color-text)
/// <summary>
/// Padding between the left edge of the report item.
/// </summary>
public float PaddingLeft; // (Size)Padding between the left edge of the report item.
/// <summary>
/// Padding between the right edge of the report item.
/// </summary>
public float PaddingRight; // (Size) Padding between the right edge of the report item.
/// <summary>
/// Padding between the top edge of the report item.
/// </summary>
public float PaddingTop; // (Size) Padding between the top edge of the report item.
/// <summary>
/// Padding between the bottom edge of the report item.
/// </summary>
public float PaddingBottom; // (Size) Padding between the bottom edge of the report item.
/// <summary>
/// Height of a line of text.
/// </summary>
public float LineHeight; // (Size) Height of a line of text
/// <summary>
/// Indicates whether text is written left-to-right (default)
/// </summary>
public DirectionEnum Direction; // (Enum Direction) Indicates whether text is written left-to-right (default)
/// <summary>
/// Indicates the writing mode; e.g. left right top bottom or top bottom left right.
/// </summary>
public WritingModeEnum WritingMode; // (Enum WritingMode) Indicates whether text is written
/// <summary>
/// The primary language of the text.
/// </summary>
public string Language; // (Language) The primary language of the text.
/// <summary>
/// Unused.
/// </summary>
public UnicodeBiDirectionalEnum UnicodeBiDirectional; // (Enum UnicodeBiDirection)
/// <summary>
/// Calendar to use.
/// </summary>
public CalendarEnum Calendar; // (Enum Calendar)
/// <summary>
/// The digit format to use.
/// </summary>
public string NumeralLanguage; // (Language) The digit format to use as described by its
/// <summary>
/// The variant of the digit format to use.
/// </summary>
public int NumeralVariant; //(Integer) The variant of the digit format to use.
/// <summary>
/// Constructor using all defaults for the style.
/// </summary>
public StyleInfo()
{
BColorLeft = BColorRight = BColorTop = BColorBottom = System.Drawing.Color.Black; // (Color) Color of the bottom border
BStyleLeft = BStyleRight = BStyleTop = BStyleBottom = BorderStyleEnum.None;
// _BorderWdith
BWidthLeft = BWidthRight = BWidthTop = BWidthBottom = 1;
BackgroundColor = System.Drawing.Color.Empty;
BackgroundColorText = string.Empty;
BackgroundGradientType = BackgroundGradientTypeEnum.None;
BackgroundGradientEndColor = System.Drawing.Color.Empty;
BackgroundImage = null;
FontStyle = FontStyleEnum.Normal;
_FontFamily = "Arial";
//WRP 291008 numFmtId should be 0 (Zero) for General format - will be interpreted as a string
//It has default values in Excel07 as per ECMA-376 standard (SEction 3.8.30) for Office Open XML Excel07
_Format = "General";
FontSize = 10;
FontWeight = FontWeightEnum.Normal;
PatternType = patternTypeEnum.None;
TextDecoration = TextDecorationEnum.None;
TextAlign = TextAlignEnum.General;
VerticalAlign = VerticalAlignEnum.Top;
Color = System.Drawing.Color.Black;
ColorText = "Black";
PaddingLeft = PaddingRight = PaddingTop = PaddingBottom = 0;
LineHeight = 0;
Direction = DirectionEnum.LTR;
WritingMode = WritingModeEnum.lr_tb;
Language = "en-US";
UnicodeBiDirectional = UnicodeBiDirectionalEnum.Normal;
Calendar = CalendarEnum.Gregorian;
NumeralLanguage = Language;
NumeralVariant=1;
}
/// <summary>
/// Name of the font family Default: Arial
/// </summary>
public string FontFamily
{
get
{
int i = _FontFamily.IndexOf(",");
return i > 0? _FontFamily.Substring(0, i): _FontFamily;
}
set { _FontFamily = value; }
}
/// <summary>
/// Name of the font family Default: Arial. Support list of families separated by ','.
/// </summary>
public string FontFamilyFull
{
get {return _FontFamily;}
}
/// <summary>
/// Gets the FontFamily instance using the FontFamily string. This supports lists of fonts.
/// </summary>
/// <returns></returns>
public FontFamily GetFontFamily()
{
return GetFontFamily(_FontFamily);
}
/// <summary>
/// Gets the FontFamily instance using the passed face name. This supports lists of fonts.
/// </summary>
/// <returns></returns>
static public FontFamily GetFontFamily(string fface)
{
string[] choices = fface.Split(',');
FontFamily ff=null;
foreach (string val in choices)
{
try
{
string font=null;
// TODO: should be better way than to hard code; could put in config file??
switch (val.Trim().ToLower())
{
case "serif":
font = "Times New Roman";
break;
case "sans-serif":
font = "Arial";
break;
case "cursive":
font = "Comic Sans MS";
break;
case "fantasy":
font = "Impact";
break;
case "monospace":
case "courier":
font = "Courier New";
break;
default:
font = val;
break;
}
ff = new FontFamily(font);
if (ff != null)
break;
}
catch {} // if font doesn't exist we will go to the next
}
if (ff == null)
ff = new FontFamily("Arial");
return ff;
}
/// <summary>
/// True if font is bold.
/// </summary>
/// <returns></returns>
public bool IsFontBold()
{
switch(FontWeight)
{
case FontWeightEnum.Bold:
case FontWeightEnum.Bolder:
case FontWeightEnum.W500:
case FontWeightEnum.W600:
case FontWeightEnum.W700:
case FontWeightEnum.W800:
case FontWeightEnum.W900:
return true;
default:
return false;
}
}
/// <summary>
/// Gets the enumerated font weight.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
static public FontWeightEnum GetFontWeight(string v, FontWeightEnum def)
{
FontWeightEnum fw;
switch(v.ToLower())
{
case "Lighter":
fw = FontWeightEnum.Lighter;
break;
case "Normal":
fw = FontWeightEnum.Normal;
break;
case "bold":
fw = FontWeightEnum.Bold;
break;
case "bolder":
fw = FontWeightEnum.Bolder;
break;
case "500":
fw = FontWeightEnum.W500;
break;
case "600":
fw = FontWeightEnum.W600;
break;
case "700":
fw = FontWeightEnum.W700;
break;
case "800":
fw = FontWeightEnum.W800;
break;
case "900":
fw = FontWeightEnum.W900;
break;
default:
fw = def;
break;
}
return fw;
}
/// <summary>
/// Returns the font style (normal or italic).
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static FontStyleEnum GetFontStyle(string v, FontStyleEnum def)
{
FontStyleEnum f;
switch (v.ToLower())
{
case "normal":
f = FontStyleEnum.Normal;
break;
case "italic":
f = FontStyleEnum.Italic;
break;
default:
f = def;
break;
}
return f;
}
/// <summary>
/// Gets the background gradient type.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
static public BackgroundGradientTypeEnum GetBackgroundGradientType(string v, BackgroundGradientTypeEnum def)
{
BackgroundGradientTypeEnum gt;
switch(v.ToLower())
{
case "none":
gt = BackgroundGradientTypeEnum.None;
break;
case "leftright":
gt = BackgroundGradientTypeEnum.LeftRight;
break;
case "topbottom":
gt = BackgroundGradientTypeEnum.TopBottom;
break;
case "center":
gt = BackgroundGradientTypeEnum.Center;
break;
case "diagonalleft":
gt = BackgroundGradientTypeEnum.DiagonalLeft;
break;
case "diagonalright":
gt = BackgroundGradientTypeEnum.DiagonalRight;
break;
case "horizontalcenter":
gt = BackgroundGradientTypeEnum.HorizontalCenter;
break;
case "verticalcenter":
gt = BackgroundGradientTypeEnum.VerticalCenter;
break;
default:
gt = def;
break;
}
return gt;
}
/// <summary>
/// Gets the text decoration.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static TextDecorationEnum GetTextDecoration(string v, TextDecorationEnum def)
{
TextDecorationEnum td;
switch (v.ToLower())
{
case "underline":
td = TextDecorationEnum.Underline;
break;
case "overline":
td = TextDecorationEnum.Overline;
break;
case "linethrough":
td = TextDecorationEnum.LineThrough;
break;
case "none":
td = TextDecorationEnum.None;
break;
default:
td = def;
break;
}
return td;
}
/// <summary>
/// Gets the text alignment.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static TextAlignEnum GetTextAlign(string v, TextAlignEnum def)
{
TextAlignEnum ta;
switch(v.ToLower())
{
case "left":
ta = TextAlignEnum.Left;
break;
case "right":
ta = TextAlignEnum.Right;
break;
case "center":
ta = TextAlignEnum.Center;
break;
case "general":
ta = TextAlignEnum.General;
break;
default:
ta = def;
break;
}
return ta;
}
/// <summary>
/// Gets the vertical alignment.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static VerticalAlignEnum GetVerticalAlign(string v, VerticalAlignEnum def)
{
VerticalAlignEnum va;
switch (v.ToLower())
{
case "top":
va = VerticalAlignEnum.Top;
break;
case "middle":
va = VerticalAlignEnum.Middle;
break;
case "bottom":
va = VerticalAlignEnum.Bottom;
break;
default:
va = def;
break;
}
return va;
}
/// <summary>
/// Gets the direction of the text.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static DirectionEnum GetDirection(string v, DirectionEnum def)
{
DirectionEnum d;
switch(v.ToLower())
{
case "ltr":
d = DirectionEnum.LTR;
break;
case "rtl":
d = DirectionEnum.RTL;
break;
default:
d = def;
break;
}
return d;
}
/// <summary>
/// Gets the writing mode; e.g. left right top bottom or top bottom left right.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static WritingModeEnum GetWritingMode(string v, WritingModeEnum def)
{
WritingModeEnum w;
switch(v.ToLower())
{
case "lr-tb":
w = WritingModeEnum.lr_tb;
break;
case "tb-rl":
w = WritingModeEnum.tb_rl;
break;
default:
w = def;
break;
}
return w;
}
/// <summary>
/// Gets the unicode BiDirectional.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static UnicodeBiDirectionalEnum GetUnicodeBiDirectional(string v, UnicodeBiDirectionalEnum def)
{
UnicodeBiDirectionalEnum u;
switch (v.ToLower())
{
case "normal":
u = UnicodeBiDirectionalEnum.Normal;
break;
case "embed":
u = UnicodeBiDirectionalEnum.Embed;
break;
case "bidi-override":
u = UnicodeBiDirectionalEnum.BiDi_Override;
break;
default:
u = def;
break;
}
return u;
}
/// <summary>
/// Gets the calendar (e.g. Gregorian, GregorianArabic, and so on)
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static CalendarEnum GetCalendar(string v, CalendarEnum def)
{
CalendarEnum c;
switch (v.ToLower())
{
case "gregorian":
c = CalendarEnum.Gregorian;
break;
case "gregorianarabic":
c = CalendarEnum.GregorianArabic;
break;
case "gregorianmiddleeastfrench":
c = CalendarEnum.GregorianMiddleEastFrench;
break;
case "gregoriantransliteratedenglish":
c = CalendarEnum.GregorianTransliteratedEnglish;
break;
case "gregoriantransliteratedfrench":
c = CalendarEnum.GregorianTransliteratedFrench;
break;
case "gregorianusenglish":
c = CalendarEnum.GregorianUSEnglish;
break;
case "hebrew":
c = CalendarEnum.Hebrew;
break;
case "hijri":
c = CalendarEnum.Hijri;
break;
case "japanese":
c = CalendarEnum.Japanese;
break;
case "korea":
c = CalendarEnum.Korea;
break;
case "taiwan":
c = CalendarEnum.Taiwan;
break;
case "thaibuddhist":
c = CalendarEnum.ThaiBuddhist;
break;
default:
c = def;
break;
}
return c;
}
// WRP 301008 return Excel07 format code as defined in section 3.8.30 of the ECMA-376 standard for Office Open XML Excel07 file formats
public static int GetFormatCode (string val)
{
switch (val)
{
case "General":
return 0;
case "0":
return 1;
case "0.00":
return 2;
case "#,##0":
return 3;
case "#,##0.00":
return 4;
case "0%":
return 9;
case "0.00%":
return 10;
case "0.00E+00":
return 11;
case "# ?/?":
return 12;
case " # ??/??":
return 13;
case "mm-dd-yy":
return 14;
case "d-mmm-yy":
return 15;
case "d-mmm":
return 16;
case "mmm-yy":
return 17;
case "h:mm AM/PM":
return 18;
case "h:mm:ss AM/PM":
return 19;
case "h:mm":
return 20;
case "h:mm:ss":
return 21;
case "m/d/yy h:mm":
return 22;
case "#,##0 ;(#,##0)":
return 37;
case "#,##0 ;[Red](#,##0)":
return 38;
case "#,##0.00;(#,##0.00)":
return 39;
case "#,##0.00;[Red](#,##0.00)":
return 40;
case "mm:ss":
return 45;
case "[h]:mm:ss":
return 46;
case "mmss.0":
return 47;
case "##0.0E+0":
return 48;
case "@":
return 49;
default:
return 999;
}
}
public static patternTypeEnum GetPatternType(System.Drawing.Drawing2D.HatchStyle hs)
{
switch (hs)
{
case HatchStyle.BackwardDiagonal:
return patternTypeEnum.BackwardDiagonal;
case HatchStyle.Cross:
return patternTypeEnum.Cross;
case HatchStyle.DarkDownwardDiagonal:
return patternTypeEnum.DarkDownwardDiagonal;
case HatchStyle.DarkHorizontal:
return patternTypeEnum.DarkHorizontal;
case HatchStyle.Vertical:
return patternTypeEnum.Vertical;
case HatchStyle.LargeConfetti:
return patternTypeEnum.LargeConfetti;
case HatchStyle.OutlinedDiamond:
return patternTypeEnum.OutlinedDiamond;
case HatchStyle.SmallConfetti:
return patternTypeEnum.SmallConfetti;
case HatchStyle.HorizontalBrick:
return patternTypeEnum.HorizontalBrick;
case HatchStyle.LargeCheckerBoard:
return patternTypeEnum.CheckerBoard;
case HatchStyle.SolidDiamond:
return patternTypeEnum.SolidDiamond;
case HatchStyle.DiagonalBrick:
return patternTypeEnum.DiagonalBrick;
default:
return patternTypeEnum.None;
}
}
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
/// <summary>
/// The types of patterns supported.
/// </summary>
public enum patternTypeEnum
{
None,
LargeConfetti,
Cross,
DarkDownwardDiagonal,
OutlinedDiamond,
DarkHorizontal,
SmallConfetti,
HorizontalBrick,
CheckerBoard,
Vertical,
SolidDiamond,
DiagonalBrick,
BackwardDiagonal
}
/// <summary>
/// The types of background gradients supported.
/// </summary>
public enum BackgroundGradientTypeEnum
{
/// <summary>
/// No gradient
/// </summary>
None,
/// <summary>
/// Left Right gradient
/// </summary>
LeftRight,
/// <summary>
/// Top Bottom gradient
/// </summary>
TopBottom,
/// <summary>
/// Center gradient
/// </summary>
Center,
/// <summary>
/// Diagonal Left gradient
/// </summary>
DiagonalLeft,
/// <summary>
/// Diagonal Right gradient
/// </summary>
DiagonalRight,
/// <summary>
/// Horizontal Center gradient
/// </summary>
HorizontalCenter,
/// <summary>
/// Vertical Center
/// </summary>
VerticalCenter
}
/// <summary>
/// Font styles supported
/// </summary>
public enum FontStyleEnum
{
/// <summary>
/// Normal font
/// </summary>
Normal,
/// <summary>
/// Italic font
/// </summary>
Italic
}
/// <summary>
/// Potential font weights
/// </summary>
public enum FontWeightEnum
{
/// <summary>
/// Lighter font
/// </summary>
Lighter,
/// <summary>
/// Normal font
/// </summary>
Normal,
/// <summary>
/// Bold font
/// </summary>
Bold,
/// <summary>
/// Bolder font
/// </summary>
Bolder,
/// <summary>
/// W100 font
/// </summary>
W100,
/// <summary>
/// W200 font
/// </summary>
W200,
/// <summary>
/// W300 font
/// </summary>
W300,
/// <summary>
/// W400 font
/// </summary>
W400,
/// <summary>
/// W500 font
/// </summary>
W500,
/// <summary>
/// W600 font
/// </summary>
W600,
/// <summary>
/// W700 font
/// </summary>
W700,
/// <summary>
/// W800 font
/// </summary>
W800,
/// <summary>
/// W900 font
/// </summary>
W900
}
public enum TextDecorationEnum
{
Underline,
Overline,
LineThrough,
None
}
public enum TextAlignEnum
{
Left,
Center,
Right,
General
}
public enum VerticalAlignEnum
{
Top,
Middle,
Bottom
}
public enum DirectionEnum
{
LTR, // left to right
RTL // right to left
}
public enum WritingModeEnum
{
lr_tb, // left right - top bottom
tb_rl // top bottom - right left
}
public enum UnicodeBiDirectionalEnum
{
Normal,
Embed,
BiDi_Override
}
public enum CalendarEnum
{
Gregorian,
GregorianArabic,
GregorianMiddleEastFrench,
GregorianTransliteratedEnglish,
GregorianTransliteratedFrench,
GregorianUSEnglish,
Hebrew,
Hijri,
Japanese,
Korea,
Taiwan,
ThaiBuddhist
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>SearchTermView</c> resource.</summary>
public sealed partial class SearchTermViewName : gax::IResourceName, sys::IEquatable<SearchTermViewName>
{
/// <summary>The possible contents of <see cref="SearchTermViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>.
/// </summary>
CustomerCampaignAdGroupQuery = 1,
}
private static gax::PathTemplate s_customerCampaignAdGroupQuery = new gax::PathTemplate("customers/{customer_id}/searchTermViews/{campaign_id_ad_group_id_query}");
/// <summary>Creates a <see cref="SearchTermViewName"/> 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="SearchTermViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SearchTermViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SearchTermViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SearchTermViewName"/> with the pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SearchTermViewName"/> constructed from the provided ids.</returns>
public static SearchTermViewName FromCustomerCampaignAdGroupQuery(string customerId, string campaignId, string adGroupId, string queryId) =>
new SearchTermViewName(ResourceNameType.CustomerCampaignAdGroupQuery, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), queryId: gax::GaxPreconditions.CheckNotNullOrEmpty(queryId, nameof(queryId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SearchTermViewName"/> with pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SearchTermViewName"/> with pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string adGroupId, string queryId) =>
FormatCustomerCampaignAdGroupQuery(customerId, campaignId, adGroupId, queryId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SearchTermViewName"/> with pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SearchTermViewName"/> with pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>.
/// </returns>
public static string FormatCustomerCampaignAdGroupQuery(string customerId, string campaignId, string adGroupId, string queryId) =>
s_customerCampaignAdGroupQuery.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(queryId, nameof(queryId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="SearchTermViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="searchTermViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SearchTermViewName"/> if successful.</returns>
public static SearchTermViewName Parse(string searchTermViewName) => Parse(searchTermViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SearchTermViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="searchTermViewName">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="SearchTermViewName"/> if successful.</returns>
public static SearchTermViewName Parse(string searchTermViewName, bool allowUnparsed) =>
TryParse(searchTermViewName, allowUnparsed, out SearchTermViewName 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="SearchTermViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="searchTermViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SearchTermViewName"/>, 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 searchTermViewName, out SearchTermViewName result) =>
TryParse(searchTermViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SearchTermViewName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="searchTermViewName">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="SearchTermViewName"/>, 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 searchTermViewName, bool allowUnparsed, out SearchTermViewName result)
{
gax::GaxPreconditions.CheckNotNull(searchTermViewName, nameof(searchTermViewName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignAdGroupQuery.TryParseName(searchTermViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignAdGroupQuery(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(searchTermViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private SearchTermViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string campaignId = null, string customerId = null, string queryId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CampaignId = campaignId;
CustomerId = customerId;
QueryId = queryId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SearchTermViewName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/searchTermViews/{campaign_id}~{ad_group_id}~{query}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="queryId">The <c>Query</c> ID. Must not be <c>null</c> or empty.</param>
public SearchTermViewName(string customerId, string campaignId, string adGroupId, string queryId) : this(ResourceNameType.CustomerCampaignAdGroupQuery, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), queryId: gax::GaxPreconditions.CheckNotNullOrEmpty(queryId, nameof(queryId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Query</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string QueryId { 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.CustomerCampaignAdGroupQuery: return s_customerCampaignAdGroupQuery.Expand(CustomerId, $"{CampaignId}~{AdGroupId}~{QueryId}");
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 SearchTermViewName);
/// <inheritdoc/>
public bool Equals(SearchTermViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SearchTermViewName a, SearchTermViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SearchTermViewName a, SearchTermViewName b) => !(a == b);
}
public partial class SearchTermView
{
/// <summary>
/// <see cref="SearchTermViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal SearchTermViewName ResourceNameAsSearchTermViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : SearchTermViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedRegionHealthCheckServicesClientSnippets
{
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteRegionHealthCheckServiceRequest, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
DeleteRegionHealthCheckServiceRequest request = new DeleteRegionHealthCheckServiceRequest
{
RequestId = "",
Region = "",
Project = "",
HealthCheckService = "",
};
// Make the request
lro::Operation<Operation, Operation> response = regionHealthCheckServicesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionHealthCheckServicesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteRegionHealthCheckServiceRequest, CallSettings)
// Additional: DeleteAsync(DeleteRegionHealthCheckServiceRequest, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
DeleteRegionHealthCheckServiceRequest request = new DeleteRegionHealthCheckServiceRequest
{
RequestId = "",
Region = "",
Project = "",
HealthCheckService = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await regionHealthCheckServicesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionHealthCheckServicesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string healthCheckService = "";
// Make the request
lro::Operation<Operation, Operation> response = regionHealthCheckServicesClient.Delete(project, region, healthCheckService);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionHealthCheckServicesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string healthCheckService = "";
// Make the request
lro::Operation<Operation, Operation> response = await regionHealthCheckServicesClient.DeleteAsync(project, region, healthCheckService);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionHealthCheckServicesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetRegionHealthCheckServiceRequest, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
GetRegionHealthCheckServiceRequest request = new GetRegionHealthCheckServiceRequest
{
Region = "",
Project = "",
HealthCheckService = "",
};
// Make the request
HealthCheckService response = regionHealthCheckServicesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetRegionHealthCheckServiceRequest, CallSettings)
// Additional: GetAsync(GetRegionHealthCheckServiceRequest, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
GetRegionHealthCheckServiceRequest request = new GetRegionHealthCheckServiceRequest
{
Region = "",
Project = "",
HealthCheckService = "",
};
// Make the request
HealthCheckService response = await regionHealthCheckServicesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string healthCheckService = "";
// Make the request
HealthCheckService response = regionHealthCheckServicesClient.Get(project, region, healthCheckService);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string healthCheckService = "";
// Make the request
HealthCheckService response = await regionHealthCheckServicesClient.GetAsync(project, region, healthCheckService);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertRegionHealthCheckServiceRequest, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
InsertRegionHealthCheckServiceRequest request = new InsertRegionHealthCheckServiceRequest
{
RequestId = "",
Region = "",
Project = "",
HealthCheckServiceResource = new HealthCheckService(),
};
// Make the request
lro::Operation<Operation, Operation> response = regionHealthCheckServicesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionHealthCheckServicesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertRegionHealthCheckServiceRequest, CallSettings)
// Additional: InsertAsync(InsertRegionHealthCheckServiceRequest, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
InsertRegionHealthCheckServiceRequest request = new InsertRegionHealthCheckServiceRequest
{
RequestId = "",
Region = "",
Project = "",
HealthCheckServiceResource = new HealthCheckService(),
};
// Make the request
lro::Operation<Operation, Operation> response = await regionHealthCheckServicesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionHealthCheckServicesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, HealthCheckService, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
HealthCheckService healthCheckServiceResource = new HealthCheckService();
// Make the request
lro::Operation<Operation, Operation> response = regionHealthCheckServicesClient.Insert(project, region, healthCheckServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionHealthCheckServicesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, HealthCheckService, CallSettings)
// Additional: InsertAsync(string, string, HealthCheckService, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
HealthCheckService healthCheckServiceResource = new HealthCheckService();
// Make the request
lro::Operation<Operation, Operation> response = await regionHealthCheckServicesClient.InsertAsync(project, region, healthCheckServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionHealthCheckServicesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListRegionHealthCheckServicesRequest, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
ListRegionHealthCheckServicesRequest request = new ListRegionHealthCheckServicesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<HealthCheckServicesList, HealthCheckService> response = regionHealthCheckServicesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (HealthCheckService item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (HealthCheckServicesList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheckService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheckService> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheckService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListRegionHealthCheckServicesRequest, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
ListRegionHealthCheckServicesRequest request = new ListRegionHealthCheckServicesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<HealthCheckServicesList, HealthCheckService> response = regionHealthCheckServicesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((HealthCheckService item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((HealthCheckServicesList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheckService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheckService> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheckService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedEnumerable<HealthCheckServicesList, HealthCheckService> response = regionHealthCheckServicesClient.List(project, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (HealthCheckService item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (HealthCheckServicesList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheckService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheckService> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheckService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedAsyncEnumerable<HealthCheckServicesList, HealthCheckService> response = regionHealthCheckServicesClient.ListAsync(project, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((HealthCheckService item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((HealthCheckServicesList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheckService item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheckService> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheckService item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchRegionHealthCheckServiceRequest, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
PatchRegionHealthCheckServiceRequest request = new PatchRegionHealthCheckServiceRequest
{
RequestId = "",
Region = "",
Project = "",
HealthCheckService = "",
HealthCheckServiceResource = new HealthCheckService(),
};
// Make the request
lro::Operation<Operation, Operation> response = regionHealthCheckServicesClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionHealthCheckServicesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchRegionHealthCheckServiceRequest, CallSettings)
// Additional: PatchAsync(PatchRegionHealthCheckServiceRequest, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
PatchRegionHealthCheckServiceRequest request = new PatchRegionHealthCheckServiceRequest
{
RequestId = "",
Region = "",
Project = "",
HealthCheckService = "",
HealthCheckServiceResource = new HealthCheckService(),
};
// Make the request
lro::Operation<Operation, Operation> response = await regionHealthCheckServicesClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionHealthCheckServicesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, string, HealthCheckService, CallSettings)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = RegionHealthCheckServicesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string healthCheckService = "";
HealthCheckService healthCheckServiceResource = new HealthCheckService();
// Make the request
lro::Operation<Operation, Operation> response = regionHealthCheckServicesClient.Patch(project, region, healthCheckService, healthCheckServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionHealthCheckServicesClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, string, HealthCheckService, CallSettings)
// Additional: PatchAsync(string, string, string, HealthCheckService, CancellationToken)
// Create client
RegionHealthCheckServicesClient regionHealthCheckServicesClient = await RegionHealthCheckServicesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string healthCheckService = "";
HealthCheckService healthCheckServiceResource = new HealthCheckService();
// Make the request
lro::Operation<Operation, Operation> response = await regionHealthCheckServicesClient.PatchAsync(project, region, healthCheckService, healthCheckServiceResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionHealthCheckServicesClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Camera1Animation1
{
Demo demo;
PhysicsScene scene;
string instanceIndexName;
string sphereName;
string cursorName;
string cursorAName;
string cursorBName;
string shotName;
string shotBaseName;
string shotLightName;
string yellowName;
string hitName;
string defaultName;
Shape sphere;
PhysicsObject[] shotTab;
bool enableShotTab;
int shotCount;
DemoMouseState oldMouseState;
DemoKeyboardState oldKeyboardState;
Vector3 position;
Vector3 direction;
Matrix4 rotation;
Matrix4 cameraRotation;
Matrix4 projection;
Matrix4 view;
Vector3 listenerPosition;
Vector3 listenerTopDirection;
Vector3 listenerFrontDirection;
Vector3 hitPosition;
Vector3 rollPosition;
Vector3 slidePosition;
Vector3 backgroundPosition;
float hitVolume;
float rollVolume;
float slideVolume;
float backgroundVolume;
float listenerRange;
Vector2 mousePosition;
Random random;
DemoListener listener;
DemoEmitter emitter;
DemoSoundGroup shotSoundGroup;
DemoSound shotSound;
Vector3 vectorZero;
Matrix4 matrixIdentity;
Quaternion quaternionIdentity;
public Camera1Animation1(Demo demo, int instanceIndex)
{
this.demo = demo;
instanceIndexName = " " + instanceIndex.ToString();
sphereName = "Sphere";
cursorName = "Cursor";
cursorAName = "Cursor A";
cursorBName = "Cursor B";
shotName = "Camera 1 Shot" + instanceIndexName + " ";
shotBaseName = "Camera 1 Shot Object" + instanceIndexName + " ";
shotLightName = "Camera 1 Shot Light" + instanceIndexName + " ";
yellowName = "Yellow";
hitName = "Hit";
defaultName = "Default";
shotTab = new PhysicsObject[10];
random = new Random();
listener = new DemoListener();
emitter = new DemoEmitter();
vectorZero = Vector3.Zero;
matrixIdentity = Matrix4.Identity;
quaternionIdentity = Quaternion.Identity;
}
public void Initialize(PhysicsScene scene)
{
this.scene = scene;
}
public void SetControllers()
{
sphere = scene.Factory.ShapeManager.Find("Sphere");
oldMouseState = demo.GetMouseState();
oldKeyboardState = demo.GetKeyboardState();
shotCount = -1;
enableShotTab = false;
for (int i = 0; i < shotTab.Length; i++)
shotTab[i] = null;
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Find("Camera 1" + instanceIndexName);
if (objectBase != null)
{
objectBase.UserControllers.TransformMethods += new SimulateMethod(MoveCursor);
objectBase.UserControllers.PostTransformMethods += new SimulateMethod(Move);
}
}
public void RefreshControllers()
{
oldMouseState = demo.GetMouseState();
oldKeyboardState = demo.GetKeyboardState();
}
public void MoveCursor(SimulateMethodArgs args)
{
PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);
if (!objectBase.Camera.Enabled) return;
if (!objectBase.Camera.Active) return;
float time = (float)args.Time;
bool mouseButton = false;
float mouseScrollWheel = 0.0f;
DemoMouseState mouseState = demo.GetMouseState();
mousePosition.X = mouseState.X;
mousePosition.Y = mouseState.Y;
mouseScrollWheel = mouseState.Wheel;
mouseButton = mouseState[MouseButton.Left];
bool hitMenu = false;
if (demo.EnableMenu)
hitMenu = (demo.MenuScene.MenuAnimation1.CurrentSwitch != null);
objectBase.Camera.View.GetViewMatrix(ref view);
objectBase.Camera.Projection.GetProjectionMatrix(ref projection);
CursorController cursorController = objectBase.InternalControllers.CursorController;
cursorController.SetViewport(0, 0, demo.WindowWidth, demo.WindowHeight, 0.0f, 1.0f);
cursorController.SetViewMatrix(ref view);
cursorController.SetProjectionMatrix(ref projection);
cursorController.SetMousePosition(ref mousePosition);
cursorController.MouseButton = mouseButton && !hitMenu;
cursorController.MouseScrollWheel = mouseScrollWheel;
cursorController.DragWheelSpeed = 50.0f;
cursorController.WindowActive = true;
cursorController.Update();
}
public void Move(SimulateMethodArgs args)
{
PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);
if (!objectBase.Camera.Enabled) return;
if (!objectBase.Camera.Active) return;
float time = (float)args.Time;
Vector3 deltaRotation = vectorZero;
Vector3 deltaTranslation = vectorZero;
float rotationSpeed = 8.0f;
float translationSpeed = 8.0f;
float soundPositionFactor = 0.1f;
bool enableShot = false;
DemoMouseState mouseState = demo.GetMouseState();
DemoKeyboardState keyboardState = demo.GetKeyboardState();
if (mouseState[MouseButton.Right])
{
deltaRotation.Y += MathHelper.DegreesToRadians(rotationSpeed * (mouseState.X - oldMouseState.X) * time);
deltaRotation.X += MathHelper.DegreesToRadians(rotationSpeed * (mouseState.Y - oldMouseState.Y) * time);
}
mousePosition.X = mouseState.X;
mousePosition.Y = mouseState.Y;
if (mouseState[MouseButton.Middle] && !oldMouseState[MouseButton.Middle])
enableShot = true;
if ((keyboardState[Key.ControlRight] && !oldKeyboardState[Key.ControlRight]) ||
(keyboardState[Key.ControlLeft] && !oldKeyboardState[Key.ControlLeft]))
enableShot = true;
PhysicsObject cursorA = scene.Factory.PhysicsObjectManager.Find(cursorAName);
PhysicsObject cursorB = scene.Factory.PhysicsObjectManager.Find(cursorBName);
if (!demo.EnableMenu)
{
if (cursorA != null)
cursorA.EnableDrawing = true;
if (cursorB != null)
cursorB.EnableDrawing = true;
}
else
{
if (cursorA != null)
cursorA.EnableDrawing = false;
if (cursorB != null)
cursorB.EnableDrawing = false;
}
if (keyboardState[Key.W])
deltaTranslation.Z += translationSpeed * time;
if (keyboardState[Key.S])
deltaTranslation.Z -= translationSpeed * time;
if (keyboardState[Key.D])
deltaTranslation.X += translationSpeed * time;
if (keyboardState[Key.A])
deltaTranslation.X -= translationSpeed * time;
oldMouseState = mouseState;
oldKeyboardState = keyboardState;
if (deltaRotation.LengthSquared != 0.0f)
{
Vector3 euler = vectorZero;
objectBase.Camera.GetEuler(ref euler);
Vector3.Add(ref euler, ref deltaRotation, out euler);
objectBase.Camera.SetEuler(ref euler);
Matrix4 rotationX, rotationY;
Matrix4.CreateRotationX(-euler.X, out rotationX);
Matrix4.CreateRotationY(-euler.Y, out rotationY);
Matrix4.Mult(ref rotationY, ref rotationX, out cameraRotation);
objectBase.Camera.SetRotation(ref cameraRotation);
objectBase.MainWorldTransform.SetTransposeRotation(ref cameraRotation);
objectBase.RecalculateMainTransform();
}
if (deltaTranslation.LengthSquared != 0.0f)
{
objectBase.MainWorldTransform.GetRotation(ref rotation);
Vector3.TransformVector(ref deltaTranslation, ref rotation, out direction);
objectBase.MainWorldTransform.GetPosition(ref position);
Vector3.Add(ref position, ref direction, out position);
objectBase.MainWorldTransform.SetPosition(ref position);
objectBase.RecalculateMainTransform();
}
objectBase.Camera.Projection.CreatePerspectiveLH(1.0f, 11000.0f, 70.0f, demo.WindowWidth, demo.WindowHeight);
objectBase.MainWorldTransform.GetPosition(ref position);
objectBase.Camera.GetTransposeRotation(ref cameraRotation);
objectBase.Camera.View.CreateLookAtLH(ref position, ref cameraRotation, 0.0f);
objectBase.Camera.UpdateFrustum();
objectBase.Camera.View.GetViewMatrix(ref view);
objectBase.Camera.Projection.GetProjectionMatrix(ref projection);
Vector3 rayPosition, rayDirection;
rayPosition = rayDirection = vectorZero;
objectBase.UnProjectToRay(ref mousePosition, 0, 0, demo.WindowWidth, demo.WindowHeight, 0.0f, 1.0f, ref view, ref matrixIdentity, ref projection, ref rayPosition, ref rayDirection);
PhysicsObject cursor = scene.Factory.PhysicsObjectManager.Find(cursorName);
if (cursor != null)
{
Vector3 cursorPosition = vectorZero;
Matrix4 cursorLocalRotation = matrixIdentity;
Matrix4 cursorWorldRotation = matrixIdentity;
cursor.InitLocalTransform.GetPosition(ref cursorPosition);
cursor.InitLocalTransform.GetRotation(ref cursorLocalRotation);
cursor.MainWorldTransform.GetRotation(ref cursorWorldRotation);
objectBase.Camera.GetTransposeRotation(ref cameraRotation);
Matrix4.Mult(ref cursorLocalRotation, ref cameraRotation, out rotation);
Vector3.TransformVector(ref cursorPosition, ref cursorWorldRotation, out position);
cursor.MainWorldTransform.SetRotation(ref rotation);
Vector3.Add(ref position, ref rayPosition, out position);
Vector3.Add(ref position, ref rayDirection, out position);
cursor.MainWorldTransform.SetPosition(ref position);
cursor.RecalculateMainTransform();
}
CursorController cursorController = objectBase.InternalControllers.CursorController;
if (cursorController.IsDragging)
{
if (cursorController.HitPhysicsObject.Integral.IsStatic && (cursorController.HitPhysicsObject.Shape != null) && (cursorController.HitPhysicsObject.Shape.ShapePrimitive != null) && (cursorController.HitPhysicsObject.Shape.ShapePrimitive.ShapePrimitiveType == ShapePrimitiveType.TriangleMesh))
{
Vector3 cursorStartPosition = vectorZero;
Vector3 cursorEndPosition = vectorZero;
cursorController.GetAnchor1(ref cursorStartPosition);
cursorController.GetAnchor2(ref cursorEndPosition);
Vector3.Subtract(ref cursorEndPosition, ref cursorStartPosition, out direction);
if (direction.LengthSquared != 0.0f)
{
cursorController.HitPhysicsObject.MainWorldTransform.GetPosition(ref cursorStartPosition);
Vector3.Add(ref cursorStartPosition, ref direction, out cursorStartPosition);
cursorController.HitPhysicsObject.MainWorldTransform.SetPosition(ref cursorStartPosition);
cursorController.HitPhysicsObject.RecalculateMainTransform();
}
}
}
objectBase.MainWorldTransform.GetPosition(ref listenerPosition);
objectBase.Camera.GetTransposeRotation(ref rotation);
Vector3.Multiply(ref listenerPosition, soundPositionFactor, out position);
listenerTopDirection.X = rotation.Row1.X;
listenerTopDirection.Y = rotation.Row1.Y;
listenerTopDirection.Z = rotation.Row1.Z;
listenerFrontDirection.X = rotation.Row2.X;
listenerFrontDirection.Y = rotation.Row2.Y;
listenerFrontDirection.Z = rotation.Row2.Z;
listener.Position = position;
listener.TopDirection = listenerTopDirection;
listener.FrontDirection = listenerFrontDirection;
listenerRange = objectBase.Sound.Range;
if (enableShot)
{
Vector3 shotScale, shotColor;
shotCount = (shotCount + 1) % shotTab.Length;
string shotCountName = shotCount.ToString();
PhysicsObject shot = scene.Factory.PhysicsObjectManager.FindOrCreate(shotName + shotCountName);
PhysicsObject shotBase = scene.Factory.PhysicsObjectManager.FindOrCreate(shotBaseName + shotCountName);
PhysicsObject shotLight = scene.Factory.PhysicsObjectManager.FindOrCreate(shotLightName + shotCountName);
shot.AddChildPhysicsObject(shotBase);
shot.AddChildPhysicsObject(shotLight);
shotTab[shotCount] = shotBase;
enableShotTab = true;
shotScale = shotColor = vectorZero;
shotScale.X = shotScale.Y = shotScale.Z = 0.5f;
Vector3.Multiply(ref rayDirection, 300.0f, out rayDirection);
shot.InitLocalTransform.SetRotation(ref matrixIdentity);
shot.InitLocalTransform.SetPosition(ref rayPosition);
shot.InitLocalTransform.SetLinearVelocity(ref rayDirection);
shot.InitLocalTransform.SetAngularVelocity(ref vectorZero);
shot.MaxSimulationFrameCount = 200;
shot.EnableRemovePhysicsObjectsFromManagerAfterMaxSimulationFrameCount = false;
//shot.EnableLocalGravity = true;
shotBase.Shape = sphere;
shotBase.UserDataStr = sphereName;
shotBase.InitLocalTransform.SetScale(ref shotScale);
shotBase.Integral.SetDensity(10.0f);
shotBase.Material.RigidGroup = true;
shotBase.EnableBreakRigidGroup = false;
shotBase.EnableCollisions = true;
shotBase.DisableCollision(objectBase, true);
shotBase.MaxDisableCollisionFrameCount = 50;
shotBase.CreateSound(true);
shotLight.Shape = sphere;
shotLight.UserDataStr = sphereName;
shotLight.CreateLight(true);
shotLight.Light.Type = PhysicsLightType.Point;
shotLight.Light.Range = 20.0f;
shotColor.X = (float)Math.Max(random.NextDouble(), random.NextDouble());
shotColor.Y = (float)Math.Max(random.NextDouble(), random.NextDouble());
shotColor.Z = (float)Math.Max(random.NextDouble(), random.NextDouble());
shotLight.Light.SetDiffuse(ref shotColor);
shotLight.InitLocalTransform.SetScale(20.0f);
shotLight.Material.UserDataStr = yellowName;
shotLight.Material.RigidGroup = true;
shotLight.EnableBreakRigidGroup = false;
shotLight.EnableCollisions = false;
shotLight.EnableCursorInteraction = false;
shotLight.EnableAddToCameraDrawTransparentPhysicsObjects = false;
scene.UpdateFromInitLocalTransform(shot);
shotSoundGroup = demo.SoundGroups[hitName];
shotSoundGroup.MaxHitRepeatTime = 0.0f;
if (shotSound == null)
shotSound = shotSoundGroup.GetSound(objectBase.Sound, listener, emitter);
shotSound.Update(time);
Vector3.Multiply(ref rayPosition, soundPositionFactor, out shotSound.HitPosition);
shotSound.HitVolume = 1.0f;
shotSound.FrontDirection.X = rotation.Row2.X;
shotSound.FrontDirection.Y = rotation.Row2.Y;
shotSound.FrontDirection.Z = rotation.Row2.Z;
demo.SoundQueue.EnqueueSound(shotSound);
}
else
{
PhysicsObject shotBase;
DemoSound shotBaseSound;
if (shotSound != null)
{
shotSound.Update(time);
if (shotSound.Stop())
{
shotSound.SoundGroup.SetSound(shotSound);
shotSound = null;
}
}
if (enableShotTab)
{
enableShotTab = false;
for (int i = 0; i < shotTab.Length; i++)
{
shotBase = shotTab[i];
if (shotBase != null)
{
if (shotBase.Sound.UserDataObj != null)
{
enableShotTab = true;
shotBaseSound = (DemoSound)shotBase.Sound.UserDataObj;
shotBaseSound.Update(time);
if (shotBaseSound.Stop())
{
shotBaseSound.SoundGroup.SetSound(shotBaseSound);
shotBase.Sound.UserDataObj = null;
shotTab[i] = null;
}
}
}
}
}
}
objectBase.Camera.UpdatePhysicsObjects(true, true, true);
objectBase.Camera.SortDrawPhysicsObjects(PhysicsCameraSortOrderType.DrawPriorityShapePrimitiveType);
objectBase.Camera.SortTransparentPhysicsObjects(PhysicsCameraSortOrderType.DrawPriorityShapePrimitiveType);
objectBase.Camera.SortLightPhysicsObjects(PhysicsCameraSortOrderType.DrawPriorityShapePrimitiveType);
PhysicsObject currentPhysicsObject;
PhysicsSound currentSound;
DemoSoundGroup soundGroup;
DemoSound sound;
if (demo.SoundQueue.SoundCount > 0)
return;
for (int i = 0; i < scene.TotalPhysicsObjectCount; i++)
{
if (demo.SoundQueue.SoundCount >= demo.SoundQueue.MaxSoundCount)
break;
currentPhysicsObject = scene.GetPhysicsObject(i);
currentSound = !currentPhysicsObject.EnableSoundFromRigidGroupOwner ? currentPhysicsObject.Sound : currentPhysicsObject.RigidGroupOwner.Sound;
if (currentSound == null)
continue;
if (!currentSound.Enabled)
continue;
if (currentSound.UserDataStr == null)
soundGroup = demo.SoundGroups[defaultName];
else
soundGroup = demo.SoundGroups[currentSound.UserDataStr];
if (currentPhysicsObject.IsSleeping && (currentSound.UserDataObj == null) && !soundGroup.EnableBackground)
continue;
if (currentPhysicsObject.GetSoundData(ref listenerPosition, listenerRange, soundGroup.EnableHit, soundGroup.EnableRoll, soundGroup.EnableSlide, soundGroup.EnableBackground, currentSound.BackgroundVolumeVelocityModulation, ref hitPosition, ref rollPosition, ref slidePosition, ref backgroundPosition, ref hitVolume, ref rollVolume, ref slideVolume, ref backgroundVolume))
{
if (currentSound.UserDataObj == null)
{
sound = soundGroup.GetSound(currentSound, listener, emitter);
currentSound.UserDataObj = sound;
}
else
{
sound = (DemoSound)currentSound.UserDataObj;
}
sound.Update(time);
currentPhysicsObject.MainWorldTransform.GetTransposeRotation(ref rotation);
Vector3.Multiply(ref hitPosition, soundPositionFactor, out sound.HitPosition);
Vector3.Multiply(ref rollPosition, soundPositionFactor, out sound.RollPosition);
Vector3.Multiply(ref slidePosition, soundPositionFactor, out sound.SlidePosition);
Vector3.Multiply(ref backgroundPosition, soundPositionFactor, out sound.BackgroundPosition);
sound.HitVolume = hitVolume;
sound.RollVolume = rollVolume;
sound.SlideVolume = slideVolume;
sound.BackgroundVolume = backgroundVolume;
sound.FrontDirection.X = rotation.Row2.X;
sound.FrontDirection.Y = rotation.Row2.Y;
sound.FrontDirection.Z = rotation.Row2.Z;
demo.SoundQueue.EnqueueSound(sound);
}
else
{
if (currentSound.UserDataObj != null)
{
sound = (DemoSound)currentSound.UserDataObj;
sound.Update(time);
if (sound.Stop())
{
soundGroup.SetSound(sound);
currentSound.UserDataObj = null;
}
}
}
}
}
}
}
| |
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
using System.Text;
using erl.Oracle.TnsNames.Antlr4.Runtime;
using erl.Oracle.TnsNames.Antlr4.Runtime.Misc;
using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen;
namespace erl.Oracle.TnsNames.Antlr4.Runtime
{
public class UnbufferedTokenStream : ITokenStream
{
private ITokenSource _tokenSource;
/// <summary>A moving window buffer of the data being scanned.</summary>
/// <remarks>
/// A moving window buffer of the data being scanned. While there's a marker,
/// we keep adding to buffer. Otherwise,
/// <see cref="Consume()">consume()</see>
/// resets so
/// we start filling at index 0 again.
/// </remarks>
protected internal IToken[] tokens;
/// <summary>
/// The number of tokens currently in
/// <see cref="tokens">tokens</see>
/// .
/// <p>This is not the buffer capacity, that's
/// <c>tokens.length</c>
/// .</p>
/// </summary>
protected internal int n;
/// <summary>
/// 0..n-1 index into
/// <see cref="tokens">tokens</see>
/// of next token.
/// <p>The
/// <c>LT(1)</c>
/// token is
/// <c>tokens[p]</c>
/// . If
/// <c>p == n</c>
/// , we are
/// out of buffered tokens.</p>
/// </summary>
protected internal int p = 0;
/// <summary>
/// Count up with
/// <see cref="Mark()">mark()</see>
/// and down with
/// <see cref="Release(int)">release()</see>
/// . When we
/// <c>release()</c>
/// the last mark,
/// <c>numMarkers</c>
/// reaches 0 and we reset the buffer. Copy
/// <c>tokens[p]..tokens[n-1]</c>
/// to
/// <c>tokens[0]..tokens[(n-1)-p]</c>
/// .
/// </summary>
protected internal int numMarkers = 0;
/// <summary>
/// This is the
/// <c>LT(-1)</c>
/// token for the current position.
/// </summary>
protected internal IToken lastToken;
/// <summary>
/// When
/// <c>numMarkers > 0</c>
/// , this is the
/// <c>LT(-1)</c>
/// token for the
/// first token in
/// <see cref="tokens"/>
/// . Otherwise, this is
/// <see langword="null"/>
/// .
/// </summary>
protected internal IToken lastTokenBufferStart;
/// <summary>Absolute token index.</summary>
/// <remarks>
/// Absolute token index. It's the index of the token about to be read via
/// <c>LT(1)</c>
/// . Goes from 0 to the number of tokens in the entire stream,
/// although the stream size is unknown before the end is reached.
/// <p>This value is used to set the token indexes if the stream provides tokens
/// that implement
/// <see cref="IWritableToken"/>
/// .</p>
/// </remarks>
protected internal int currentTokenIndex = 0;
public UnbufferedTokenStream(ITokenSource tokenSource)
: this(tokenSource, 256)
{
}
public UnbufferedTokenStream(ITokenSource tokenSource, int bufferSize)
{
this.TokenSource = tokenSource;
this.tokens = new IToken[bufferSize];
n = 0;
Fill(1);
}
// prime the pump
public virtual IToken Get(int i)
{
int bufferStartIndex = GetBufferStartIndex();
if (i < bufferStartIndex || i >= bufferStartIndex + n)
{
throw new ArgumentOutOfRangeException("get(" + i + ") outside buffer: " + bufferStartIndex + ".." + (bufferStartIndex + n));
}
return tokens[i - bufferStartIndex];
}
public virtual IToken LT(int i)
{
if (i == -1)
{
return lastToken;
}
Sync(i);
int index = p + i - 1;
if (index < 0)
{
throw new ArgumentOutOfRangeException("LT(" + i + ") gives negative index");
}
if (index >= n)
{
System.Diagnostics.Debug.Assert(n > 0 && tokens[n - 1].Type == TokenConstants.EOF);
return tokens[n - 1];
}
return tokens[index];
}
public virtual int LA(int i)
{
return LT(i).Type;
}
public virtual ITokenSource TokenSource
{
get
{
return _tokenSource;
}
set
{
_tokenSource = value;
}
}
[return: NotNull]
public virtual string GetText()
{
return string.Empty;
}
[return: NotNull]
public virtual string GetText(RuleContext ctx)
{
return GetText(ctx.SourceInterval);
}
[return: NotNull]
public virtual string GetText(IToken start, IToken stop)
{
if (start != null && stop != null)
{
return GetText(Interval.Of(start.TokenIndex, stop.TokenIndex));
}
throw new NotSupportedException("The specified start and stop symbols are not supported.");
}
public virtual void Consume()
{
if (LA(1) == TokenConstants.EOF)
{
throw new InvalidOperationException("cannot consume EOF");
}
// buf always has at least tokens[p==0] in this method due to ctor
lastToken = tokens[p];
// track last token for LT(-1)
// if we're at last token and no markers, opportunity to flush buffer
if (p == n - 1 && numMarkers == 0)
{
n = 0;
p = -1;
// p++ will leave this at 0
lastTokenBufferStart = lastToken;
}
p++;
currentTokenIndex++;
Sync(1);
}
/// <summary>
/// Make sure we have 'need' elements from current position
/// <see cref="p">p</see>
/// . Last valid
/// <c>p</c>
/// index is
/// <c>tokens.length-1</c>
/// .
/// <c>p+need-1</c>
/// is the tokens index 'need' elements
/// ahead. If we need 1 element,
/// <c>(p+1-1)==p</c>
/// must be less than
/// <c>tokens.length</c>
/// .
/// </summary>
protected internal virtual void Sync(int want)
{
int need = (p + want - 1) - n + 1;
// how many more elements we need?
if (need > 0)
{
Fill(need);
}
}
/// <summary>
/// Add
/// <paramref name="n"/>
/// elements to the buffer. Returns the number of tokens
/// actually added to the buffer. If the return value is less than
/// <paramref name="n"/>
/// ,
/// then EOF was reached before
/// <paramref name="n"/>
/// tokens could be added.
/// </summary>
protected internal virtual int Fill(int n)
{
for (int i = 0; i < n; i++)
{
if (this.n > 0 && tokens[this.n - 1].Type == TokenConstants.EOF)
{
return i;
}
IToken t = TokenSource.NextToken();
Add(t);
}
return n;
}
protected internal virtual void Add(IToken t)
{
if (n >= tokens.Length)
{
tokens = Arrays.CopyOf(tokens, tokens.Length * 2);
}
if (t is IWritableToken)
{
((IWritableToken)t).TokenIndex = GetBufferStartIndex() + n;
}
tokens[n++] = t;
}
/// <summary>Return a marker that we can release later.</summary>
/// <remarks>
/// Return a marker that we can release later.
/// <p>The specific marker value used for this class allows for some level of
/// protection against misuse where
/// <c>seek()</c>
/// is called on a mark or
/// <c>release()</c>
/// is called in the wrong order.</p>
/// </remarks>
public virtual int Mark()
{
if (numMarkers == 0)
{
lastTokenBufferStart = lastToken;
}
int mark = -numMarkers - 1;
numMarkers++;
return mark;
}
public virtual void Release(int marker)
{
int expectedMark = -numMarkers;
if (marker != expectedMark)
{
throw new InvalidOperationException("release() called with an invalid marker.");
}
numMarkers--;
if (numMarkers == 0)
{
// can we release buffer?
if (p > 0)
{
// Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs
// p is last valid token; move nothing if p==n as we have no valid char
System.Array.Copy(tokens, p, tokens, 0, n - p);
// shift n-p tokens from p to 0
n = n - p;
p = 0;
}
lastTokenBufferStart = lastToken;
}
}
public virtual int Index
{
get
{
return currentTokenIndex;
}
}
public virtual void Seek(int index)
{
// seek to absolute index
if (index == currentTokenIndex)
{
return;
}
if (index > currentTokenIndex)
{
Sync(index - currentTokenIndex);
index = Math.Min(index, GetBufferStartIndex() + n - 1);
}
int bufferStartIndex = GetBufferStartIndex();
int i = index - bufferStartIndex;
if (i < 0)
{
throw new ArgumentException("cannot seek to negative index " + index);
}
else
{
if (i >= n)
{
throw new NotSupportedException("seek to index outside buffer: " + index + " not in " + bufferStartIndex + ".." + (bufferStartIndex + n));
}
}
p = i;
currentTokenIndex = index;
if (p == 0)
{
lastToken = lastTokenBufferStart;
}
else
{
lastToken = tokens[p - 1];
}
}
public virtual int Size
{
get
{
throw new NotSupportedException("Unbuffered stream cannot know its size");
}
}
public virtual string SourceName
{
get
{
return TokenSource.SourceName;
}
}
[return: NotNull]
public virtual string GetText(Interval interval)
{
int bufferStartIndex = GetBufferStartIndex();
int bufferStopIndex = bufferStartIndex + tokens.Length - 1;
int start = interval.a;
int stop = interval.b;
if (start < bufferStartIndex || stop > bufferStopIndex)
{
throw new NotSupportedException("interval " + interval + " not in token buffer window: " + bufferStartIndex + ".." + bufferStopIndex);
}
int a = start - bufferStartIndex;
int b = stop - bufferStartIndex;
StringBuilder buf = new StringBuilder();
for (int i = a; i <= b; i++)
{
IToken t = tokens[i];
buf.Append(t.Text);
}
return buf.ToString();
}
protected internal int GetBufferStartIndex()
{
return currentTokenIndex - p;
}
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedModuloNullableTests
{
#region Test methods
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableByte(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableInt(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableLong(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableShort(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableULong(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUShort(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLiftedModuloNullableNumberTest(bool useInterpreter)
{
Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableNumber(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Helpers
public static byte ModuloNullableByte(byte a, byte b)
{
return (byte)(a % b);
}
public static char ModuloNullableChar(char a, char b)
{
return (char)(a % b);
}
public static decimal ModuloNullableDecimal(decimal a, decimal b)
{
return (decimal)(a % b);
}
public static double ModuloNullableDouble(double a, double b)
{
return (double)(a % b);
}
public static float ModuloNullableFloat(float a, float b)
{
return (float)(a % b);
}
public static int ModuloNullableInt(int a, int b)
{
return (int)(a % b);
}
public static long ModuloNullableLong(long a, long b)
{
return (long)(a % b);
}
public static sbyte ModuloNullableSByte(sbyte a, sbyte b)
{
return (sbyte)(a % b);
}
public static short ModuloNullableShort(short a, short b)
{
return (short)(a % b);
}
public static uint ModuloNullableUInt(uint a, uint b)
{
return (uint)(a % b);
}
public static ulong ModuloNullableULong(ulong a, ulong b)
{
return (ulong)(a % b);
}
public static ushort ModuloNullableUShort(ushort a, ushort b)
{
return (ushort)(a % b);
}
#endregion
#region Test verifiers
private static void VerifyModuloNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Modulo(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableByte")));
Func<byte?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((byte?)(a % b), f());
}
private static void VerifyModuloNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Modulo(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableChar")));
Func<char?> f = e.Compile(useInterpreter);
if (a.HasValue && b == '\0')
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((char?)(a % b), f());
}
private static void VerifyModuloNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Modulo(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableDecimal")));
Func<decimal?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Modulo(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableDouble")));
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Modulo(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableFloat")));
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Modulo(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableInt")));
Func<int?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (a == int.MinValue && b == -1)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Modulo(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableLong")));
Func<long?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (a == long.MinValue && b == -1)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Modulo(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableSByte")));
Func<sbyte?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((sbyte?)(a % b), f());
}
private static void VerifyModuloNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Modulo(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableShort")));
Func<short?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((short?)(a % b), f());
}
private static void VerifyModuloNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Modulo(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableUInt")));
Func<uint?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Modulo(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableULong")));
Func<ulong?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a % b, f());
}
private static void VerifyModuloNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Modulo(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableUShort")));
Func<ushort?> f = e.Compile(useInterpreter);
if (a.HasValue && b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((ushort?)(a % b), f());
}
private static void VerifyModuloNullableNumber(Number? a, Number? b, bool useInterpreter)
{
Expression<Func<Number?>> e =
Expression.Lambda<Func<Number?>>(
Expression.Modulo(
Expression.Constant(a, typeof(Number?)),
Expression.Constant(b, typeof(Number?))));
Assert.Equal(typeof(Number?), e.Body.Type);
Func<Number?> f = e.Compile(useInterpreter);
if (a.HasValue && b == new Number(0))
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a % b, f());
}
#endregion
}
}
| |
using System;
using UIKit;
using Foundation;
using JSQMessagesViewController;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Text;
using System.Collections;
namespace XamarinChat
{
public class User
{
public string Id { get; set; }
public string DisplayName { get; set; }
}
public class ChatPageViewController : MessagesViewController
{
MessagesBubbleImage outgoingBubbleImageData, incomingBubbleImageData;
MessagesAvatarImage outgoingAvatar, incomingAvatar;
List<Message> messages = new List<Message>();
int messageCount = 0;
private HttpClient _client;
private Conversation _lastConversation;
string DirectLineKey = "[DirectLineKey]";
//Tracking of which user said what
User sender = new User { Id = "2CC8343", DisplayName = "You" };
User friend = new User { Id = "BADB229", DisplayName = "Xamarin Bot" };
//Holds the entire message history for a given session
MessageSet ms = new MessageSet();
public override async void ViewDidLoad()
{
base.ViewDidLoad();
//CollectionView.BackgroundColor = new UIColor(red:0.39f, green:0.33f, blue:0.50f, alpha:1.0f);
//CollectionView.BackgroundColor = new UIColor(red: 0.04f, green: 0.11f, blue: 0.32f, alpha: 1.0f);
Title = "Xamarin Shopping Bot";
this.NavigationController.NavigationBar.TintColor = new UIColor(red: 0.04f, green: 0.11f, blue: 0.32f, alpha: 1.0f);
//instantiate an HTTPClient, and set properties to our DirectLine bot
_client = new HttpClient();
_client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector",
DirectLineKey);
var response = await _client.GetAsync("/api/tokens/");
if (response.IsSuccessStatusCode)
{
var conversation = new Conversation();
HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(conversation), Encoding.UTF8,
"application/json");
response = await _client.PostAsync("/api/conversations/", contentPost);
if (response.IsSuccessStatusCode)
{
var conversationInfo = await response.Content.ReadAsStringAsync();
_lastConversation = JsonConvert.DeserializeObject<Conversation>(conversationInfo);
}
}
// You must set your senderId and display name
SenderId = sender.Id;
SenderDisplayName = sender.DisplayName;
UIImage av = FromUrl("https://raw.githubusercontent.com/Microsoft/XamarinAzure_ShoppingDemoApp/master/Shopping.DemoApp.iOS/Resources/Images.xcassets/AppIcons.appiconset/Icon-83.5%402x.png");
// These MessagesBubbleImages will be used in the GetMessageBubbleImageData override
var bubbleFactory = new MessagesBubbleImageFactory();
outgoingBubbleImageData = bubbleFactory.CreateOutgoingMessagesBubbleImage(UIColorExtensions.MessageBubbleLightGrayColor);
//incomingBubbleImageData = bubbleFactory.CreateIncomingMessagesBubbleImage(new UIColor(red: 0.31f, green: 0.00f, blue: 0.28f, alpha: 1.0f));
incomingBubbleImageData = bubbleFactory.CreateIncomingMessagesBubbleImage(new UIColor(red: 0.51f, green: 0.18f, blue: 0.51f, alpha: 1.0f));
incomingAvatar = new MessagesAvatarImage(av, av, av);
//incomingAvatar.AvatarImage = UIImage.FromBundle("headshot");
outgoingAvatar = new MessagesAvatarImage(av, av, av);
// Remove the AccessoryButton as we will not be sending pics
InputToolbar.ContentView.LeftBarButtonItem = null;
// Remove the Avatars
//CollectionView.CollectionViewLayout.IncomingAvatarViewSize = CoreGraphics.CGSize.Empty;
//CollectionView.CollectionViewLayout.OutgoingAvatarViewSize = CoreGraphics.CGSize.Empty;
// Load some messagees to start
messages.Add(new Message(friend.Id, friend.DisplayName, NSDate.DistantPast, "Welcome to the Xamarin Shop! How may I help you?"));
FinishReceivingMessage(true);
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
var cell = base.GetCell(collectionView, indexPath) as MessagesCollectionViewCell;
// Override GetCell to make modifications to the cell
// In this case darken the text for the sender
var message = messages[indexPath.Row];
if (message.SenderId == SenderId)
cell.TextView.TextColor = UIColor.Black;
return cell;
}
static UIImage FromUrl(string uri)
{
var img = new UIImage();
using (var url = new NSUrl(uri))
using (var data = NSData.FromUrl(url))
img = UIImage.LoadFromData(data);
//return UIImage.LoadFromData(data);
return img;
}
public override nint GetItemsCount(UICollectionView collectionView, nint section)
{
return messages.Count;
}
public override IMessageData GetMessageData(MessagesCollectionView collectionView, NSIndexPath indexPath)
{
return messages[indexPath.Row];
}
public override IMessageBubbleImageDataSource GetMessageBubbleImageData(MessagesCollectionView collectionView, NSIndexPath indexPath)
{
var message = messages[indexPath.Row];
if (message.SenderId == SenderId)
return outgoingBubbleImageData;
return incomingBubbleImageData;
}
public override IMessageAvatarImageDataSource GetAvatarImageData(MessagesCollectionView collectionView, NSIndexPath indexPath)
{
var message = messages[indexPath.Row];
if (message.SenderId == SenderId)
return incomingAvatar;
return outgoingAvatar;
}
public override async void PressedSendButton(UIButton button, string text, string senderId, string senderDisplayName, NSDate date)
{
//Clear the text and play a send sound
InputToolbar.ContentView.TextView.Text = "";
InputToolbar.ContentView.RightBarButtonItem.Enabled = false;
SystemSoundPlayer.PlayMessageSentSound();
//set message details and add to the message queue
var message = new Message("2CC8343", "You", NSDate.Now, text);
messages.Add(message);
FinishReceivingMessage(true);
//Show typing indicator to add to the natual feel of the bot
ShowTypingIndicator = true;
//send message to bot and await the message set
ms = await SendMessage(text);
//iterate through our message set, and print new messasges from the bot
while (ms.messages.Length > messageCount)
{
if (ms.messages[messageCount].from == "XamarinBot")
{
ScrollToBottom(true);
SystemSoundPlayer.PlayMessageReceivedSound();
var messageBot = new Message(friend.Id, friend.DisplayName, NSDate.Now, ms.messages[messageCount].text);
messages.Add(messageBot);
FinishReceivingMessage(true);
InputToolbar.ContentView.RightBarButtonItem.Enabled = true;
}
messageCount++;
}
}
public async Task<MessageSet> SendMessage(string messageText)
{
try
{
var messageToSend = new BotMessage() { text = messageText, conversationId = _lastConversation.conversationId };
var contentPost = new StringContent(JsonConvert.SerializeObject(messageToSend), Encoding.UTF8, "application/json");
var conversationUrl = "https://directline.botframework.com/api/conversations/" + _lastConversation.conversationId + "/messages/";
var response = await _client.PostAsync(conversationUrl, contentPost);
var messageInfo = await response.Content.ReadAsStringAsync();
var messagesReceived = await _client.GetAsync(conversationUrl);
var messagesReceivedData = await messagesReceived.Content.ReadAsStringAsync();
var messages = JsonConvert.DeserializeObject<MessageSet>(messagesReceivedData);
return messages;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
}
public class MessageSet
{
public BotMessage[] messages { get; set; }
public string watermark { get; set; }
public string eTag { get; set; }
}
public class BotMessage
{
public string id { get; set; }
public string conversationId { get; set; }
public DateTime created { get; set; }
public string from { get; set; }
public string text { get; set; }
public string channelData { get; set; }
public string[] images { get; set; }
public Attachment[] attachments { get; set; }
public string eTag { get; set; }
}
public class Attachment
{
public string url { get; set; }
public string contentType { get; set; }
}
public class Conversation
{
public string conversationId { get; set; }
public string token { get; set; }
public string eTag { get; set; }
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DrawingContextDrawingContextWalker.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.PresentationCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Diagnostics;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Security;
using System.Security.Permissions;
namespace System.Windows.Media
{
/// <summary>
/// DrawingContextDrawingContextWalker is a DrawingContextWalker
/// that forwards all of it's calls to a DrawingContext.
/// </summary>
internal partial class DrawingContextDrawingContextWalker: DrawingContextWalker
{
/// <summary>
/// DrawLine -
/// Draws a line with the specified pen.
/// Note that this API does not accept a Brush, as there is no area to fill.
/// </summary>
/// <param name="pen"> The Pen with which to stroke the line. </param>
/// <param name="point0"> The start Point for the line. </param>
/// <param name="point1"> The end Point for the line. </param>
public override void DrawLine(
Pen pen,
Point point0,
Point point1)
{
_drawingContext.DrawLine(
pen,
point0,
point1
);
}
/// <summary>
/// DrawLine -
/// Draws a line with the specified pen.
/// Note that this API does not accept a Brush, as there is no area to fill.
/// </summary>
/// <param name="pen"> The Pen with which to stroke the line. </param>
/// <param name="point0"> The start Point for the line. </param>
/// <param name="point0Animations"> Optional AnimationClock for point0. </param>
/// <param name="point1"> The end Point for the line. </param>
/// <param name="point1Animations"> Optional AnimationClock for point1. </param>
public override void DrawLine(
Pen pen,
Point point0,
AnimationClock point0Animations,
Point point1,
AnimationClock point1Animations)
{
_drawingContext.DrawLine(
pen,
point0,
point0Animations,
point1,
point1Animations
);
}
/// <summary>
/// DrawRectangle -
/// Draw a rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
public override void DrawRectangle(
Brush brush,
Pen pen,
Rect rectangle)
{
_drawingContext.DrawRectangle(
brush,
pen,
rectangle
);
}
/// <summary>
/// DrawRectangle -
/// Draw a rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
public override void DrawRectangle(
Brush brush,
Pen pen,
Rect rectangle,
AnimationClock rectangleAnimations)
{
_drawingContext.DrawRectangle(
brush,
pen,
rectangle,
rectangleAnimations
);
}
/// <summary>
/// DrawRoundedRectangle -
/// Draw a rounded rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
/// <param name="radiusX">
/// The radius in the X dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Width/2]
/// </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Height/2].
/// </param>
public override void DrawRoundedRectangle(
Brush brush,
Pen pen,
Rect rectangle,
Double radiusX,
Double radiusY)
{
_drawingContext.DrawRoundedRectangle(
brush,
pen,
rectangle,
radiusX,
radiusY
);
}
/// <summary>
/// DrawRoundedRectangle -
/// Draw a rounded rectangle with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the rectangle.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the rectangle.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="rectangle"> The Rect to fill and/or stroke. </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
/// <param name="radiusX">
/// The radius in the X dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Width/2]
/// </param>
/// <param name="radiusXAnimations"> Optional AnimationClock for radiusX. </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the rounded corners of this
/// rounded Rect. This value will be clamped to the range [0..rectangle.Height/2].
/// </param>
/// <param name="radiusYAnimations"> Optional AnimationClock for radiusY. </param>
public override void DrawRoundedRectangle(
Brush brush,
Pen pen,
Rect rectangle,
AnimationClock rectangleAnimations,
Double radiusX,
AnimationClock radiusXAnimations,
Double radiusY,
AnimationClock radiusYAnimations)
{
_drawingContext.DrawRoundedRectangle(
brush,
pen,
rectangle,
rectangleAnimations,
radiusX,
radiusXAnimations,
radiusY,
radiusYAnimations
);
}
/// <summary>
/// DrawEllipse -
/// Draw an ellipse with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the ellipse.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the ellipse.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="center">
/// The center of the ellipse to fill and/or stroke.
/// </param>
/// <param name="radiusX">
/// The radius in the X dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
public override void DrawEllipse(
Brush brush,
Pen pen,
Point center,
Double radiusX,
Double radiusY)
{
_drawingContext.DrawEllipse(
brush,
pen,
center,
radiusX,
radiusY
);
}
/// <summary>
/// DrawEllipse -
/// Draw an ellipse with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the ellipse.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the ellipse.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="center">
/// The center of the ellipse to fill and/or stroke.
/// </param>
/// <param name="centerAnimations"> Optional AnimationClock for center. </param>
/// <param name="radiusX">
/// The radius in the X dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
/// <param name="radiusXAnimations"> Optional AnimationClock for radiusX. </param>
/// <param name="radiusY">
/// The radius in the Y dimension of the ellipse.
/// The absolute value of the radius provided will be used.
/// </param>
/// <param name="radiusYAnimations"> Optional AnimationClock for radiusY. </param>
public override void DrawEllipse(
Brush brush,
Pen pen,
Point center,
AnimationClock centerAnimations,
Double radiusX,
AnimationClock radiusXAnimations,
Double radiusY,
AnimationClock radiusYAnimations)
{
_drawingContext.DrawEllipse(
brush,
pen,
center,
centerAnimations,
radiusX,
radiusXAnimations,
radiusY,
radiusYAnimations
);
}
/// <summary>
/// DrawGeometry -
/// Draw a Geometry with the provided Brush and/or Pen.
/// If both the Brush and Pen are null this call is a no-op.
/// </summary>
/// <param name="brush">
/// The Brush with which to fill the Geometry.
/// This is optional, and can be null, in which case no fill is performed.
/// </param>
/// <param name="pen">
/// The Pen with which to stroke the Geometry.
/// This is optional, and can be null, in which case no stroke is performed.
/// </param>
/// <param name="geometry"> The Geometry to fill and/or stroke. </param>
public override void DrawGeometry(
Brush brush,
Pen pen,
Geometry geometry)
{
_drawingContext.DrawGeometry(
brush,
pen,
geometry
);
}
/// <summary>
/// DrawImage -
/// Draw an Image into the region specified by the Rect.
/// The Image will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an ImageBrush via
/// DrawRectangle.
/// </summary>
/// <param name="imageSource"> The ImageSource to draw. </param>
/// <param name="rectangle">
/// The Rect into which the ImageSource will be fit.
/// </param>
public override void DrawImage(
ImageSource imageSource,
Rect rectangle)
{
_drawingContext.DrawImage(
imageSource,
rectangle
);
}
/// <summary>
/// DrawImage -
/// Draw an Image into the region specified by the Rect.
/// The Image will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an ImageBrush via
/// DrawRectangle.
/// </summary>
/// <param name="imageSource"> The ImageSource to draw. </param>
/// <param name="rectangle">
/// The Rect into which the ImageSource will be fit.
/// </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
public override void DrawImage(
ImageSource imageSource,
Rect rectangle,
AnimationClock rectangleAnimations)
{
_drawingContext.DrawImage(
imageSource,
rectangle,
rectangleAnimations
);
}
/// <summary>
/// DrawGlyphRun -
/// Draw a GlyphRun
/// </summary>
/// <param name="foregroundBrush">
/// Foreground brush to draw the GlyphRun with.
/// </param>
/// <param name="glyphRun"> The GlyphRun to draw. </param>
public override void DrawGlyphRun(
Brush foregroundBrush,
GlyphRun glyphRun)
{
_drawingContext.DrawGlyphRun(
foregroundBrush,
glyphRun
);
}
/// <summary>
/// DrawDrawing -
/// Draw a Drawing by appending a sub-Drawing to the current Drawing.
/// </summary>
/// <param name="drawing"> The drawing to draw. </param>
public override void DrawDrawing(
Drawing drawing)
{
_drawingContext.DrawDrawing(
drawing
);
}
/// <summary>
/// DrawVideo -
/// Draw a Video into the region specified by the Rect.
/// The Video will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an VideoBrush via
/// DrawRectangle.
/// </summary>
/// <param name="player"> The MediaPlayer to draw. </param>
/// <param name="rectangle"> The Rect into which the media will be fit. </param>
public override void DrawVideo(
MediaPlayer player,
Rect rectangle)
{
_drawingContext.DrawVideo(
player,
rectangle
);
}
/// <summary>
/// DrawVideo -
/// Draw a Video into the region specified by the Rect.
/// The Video will potentially be stretched and distorted to fit the Rect.
/// For more fine grained control, consider filling a Rect with an VideoBrush via
/// DrawRectangle.
/// </summary>
/// <param name="player"> The MediaPlayer to draw. </param>
/// <param name="rectangle"> The Rect into which the media will be fit. </param>
/// <param name="rectangleAnimations"> Optional AnimationClock for rectangle. </param>
public override void DrawVideo(
MediaPlayer player,
Rect rectangle,
AnimationClock rectangleAnimations)
{
_drawingContext.DrawVideo(
player,
rectangle,
rectangleAnimations
);
}
/// <summary>
/// PushClip -
/// Push a clip region, which will apply to all drawing primitives until the
/// corresponding Pop call.
/// </summary>
/// <param name="clipGeometry"> The Geometry to which we will clip. </param>
public override void PushClip(
Geometry clipGeometry)
{
_drawingContext.PushClip(
clipGeometry
);
}
/// <summary>
/// PushOpacityMask -
/// Push an opacity mask which will blend the composite of all drawing primitives added
/// until the corresponding Pop call.
/// </summary>
/// <param name="opacityMask"> The opacity mask </param>
public override void PushOpacityMask(
Brush opacityMask)
{
_drawingContext.PushOpacityMask(
opacityMask
);
}
/// <summary>
/// PushOpacity -
/// Push an opacity which will blend the composite of all drawing primitives added
/// until the corresponding Pop call.
/// </summary>
/// <param name="opacity">
/// The opacity with which to blend - 0 is transparent, 1 is opaque.
/// </param>
public override void PushOpacity(
Double opacity)
{
_drawingContext.PushOpacity(
opacity
);
}
/// <summary>
/// PushOpacity -
/// Push an opacity which will blend the composite of all drawing primitives added
/// until the corresponding Pop call.
/// </summary>
/// <param name="opacity">
/// The opacity with which to blend - 0 is transparent, 1 is opaque.
/// </param>
/// <param name="opacityAnimations"> Optional AnimationClock for opacity. </param>
public override void PushOpacity(
Double opacity,
AnimationClock opacityAnimations)
{
_drawingContext.PushOpacity(
opacity,
opacityAnimations
);
}
/// <summary>
/// PushTransform -
/// Push a Transform which will apply to all drawing operations until the corresponding
/// Pop.
/// </summary>
/// <param name="transform"> The Transform to push. </param>
public override void PushTransform(
Transform transform)
{
_drawingContext.PushTransform(
transform
);
}
/// <summary>
/// PushGuidelineSet -
/// Push a set of guidelines which will apply to all drawing operations until the
/// corresponding Pop.
/// </summary>
/// <param name="guidelines"> The GuidelineSet to push. </param>
public override void PushGuidelineSet(
GuidelineSet guidelines)
{
_drawingContext.PushGuidelineSet(
guidelines
);
}
/// <summary>
/// PushGuidelineY1 -
/// Explicitly push one horizontal guideline.
/// </summary>
/// <param name="coordinate"> The coordinate of leading guideline. </param>
internal override void PushGuidelineY1(
Double coordinate)
{
_drawingContext.PushGuidelineY1(
coordinate
);
}
/// <summary>
/// PushGuidelineY2 -
/// Explicitly push a pair of horizontal guidelines.
/// </summary>
/// <param name="leadingCoordinate">
/// The coordinate of leading guideline.
/// </param>
/// <param name="offsetToDrivenCoordinate">
/// The offset from leading guideline to driven guideline.
/// </param>
internal override void PushGuidelineY2(
Double leadingCoordinate,
Double offsetToDrivenCoordinate)
{
_drawingContext.PushGuidelineY2(
leadingCoordinate,
offsetToDrivenCoordinate
);
}
/// <summary>
/// PushEffect -
/// Push a BitmapEffect which will apply to all drawing operations until the
/// corresponding Pop.
/// </summary>
/// <param name="effect"> The BitmapEffect to push. </param>
/// <param name="effectInput"> The BitmapEffectInput. </param>
[Obsolete(MS.Internal.Media.VisualTreeUtils.BitmapEffectObsoleteMessage)]
public override void PushEffect(
BitmapEffect effect,
BitmapEffectInput effectInput)
{
_drawingContext.PushEffect(
effect,
effectInput
);
}
/// <summary>
/// Pop
/// </summary>
public override void Pop(
)
{
_drawingContext.Pop(
);
}
}
}
| |
// ============================================================
// RRDSharp: Managed implementation of RRDTool for .NET/Mono
// ============================================================
//
// Project Info: http://sourceforge.net/projects/rrdsharp/
// Project Lead: Julio David Quintana (david@quintana.org)
//
// Distributed under terms of the LGPL:
//
// This library is free software; you can redistribute it and/or modify it under the terms
// of the GNU Lesser General Public License as published by the Free Software Foundation;
// either version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with this
// library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
// Boston, MA 02111-1307, USA.
using System;
using System.IO;
using System.Text;
using System.Threading;
namespace stRrd.Core
{
/// <summary>
/// Class to represent RRD file on the disk.
/// </summary>
public class RrdFile
{
internal static readonly int MODE_NORMAL = 0;
internal static readonly int MODE_RESTORE = 1;
internal static readonly int MODE_CREATE = 2;
internal static readonly FileAccess ACCESS_READ_WRITE = FileAccess.ReadWrite;
internal static readonly FileAccess ACCESS_READ_ONLY = FileAccess.Read;
static readonly int LOCK_DELAY = 100; // 0.1 sec
static int lockMode = RrdDb.NO_LOCKS;
private FileStream fs;
private BinaryWriter fileOut;
private BinaryReader fileIn;
private bool safeMode = true;
private string filePath;
private bool fileLock = false;
private int rrdMode;
private long nextPointer = 0L;
internal RrdFile(string filePath, int rrdMode, bool readOnly)
{
this.filePath = filePath;
this.rrdMode = rrdMode;
this.fs = new FileStream(filePath, FileMode.OpenOrCreate, (readOnly? ACCESS_READ_ONLY : ACCESS_READ_WRITE));
this.fileOut = new BinaryWriter(fs, Encoding.Unicode);
this.fileIn = new BinaryReader(fs, Encoding.Unicode);
LockFile();
}
/// <summary>
///
/// </summary>
public void Close()
{
UnlockFile();
if (fs != null)
{
fs.Close();
fileOut.Close();
fileIn.Close();
}
}
private void LockFile()
{
if(lockMode == RrdDb.WAIT_IF_LOCKED || lockMode == RrdDb.EXCEPTION_IF_LOCKED)
{
do {
try
{
fs.Lock(0,fs.Length);
fileLock = true;
}
catch (IOException)
{
}
// could not obtain lock
if(lockMode == RrdDb.WAIT_IF_LOCKED)
{
// wait a little, than try again
Thread.Sleep(LOCK_DELAY);
}
else
{
throw new IOException("Access denied. " +
"File [" + filePath + "] already locked");
}
} while(fileLock == false);
}
}
private void UnlockFile()
{
if(fileLock != false)
{
fs.Unlock(0,fs.Length);
fileLock = false;
}
}
/// <summary>
///
/// </summary>
~RrdFile()
{
Close();
}
internal void TruncateFile()
{
fs.SetLength(nextPointer);
}
internal bool IsEndReached()
{
return nextPointer == fs.Length;
}
internal void Allocate(RrdPrimitive primitive, int byteCount)
{
primitive.Pointer = nextPointer;
primitive.ByteCount = byteCount;
nextPointer += byteCount;
}
internal void Seek(long pointer)
{
fs.Seek(pointer, SeekOrigin.Begin);
}
internal int Read(ref byte[] data)
{
int bytesRead = 0;
fileIn.ReadBytes(data.Length);
bytesRead = data.Length;
return bytesRead;
}
internal int ReadInt()
{
int result = fileIn.ReadInt32();
fileIn.ReadByte();
return result;
}
internal long ReadLong()
{
long result = (long)fileIn.ReadInt64();
return result;
}
internal double[] ReadDouble(int count)
{
double[] results = new double[count];
try
{
for (int i = 0; i < count; i++)
{
results[i] = (double)fileIn.ReadDouble();
}
}
catch (IOException)
{
throw new IOException("End of file reached");
}
return results;
}
internal double ReadDouble()
{
double result = (double)fileIn.ReadDouble();
return result;
}
internal char ReadChar()
{
char result = (char)fileIn.ReadChar();
return result;
}
internal void Write(byte[] data)
{
fileOut.Write(data);
}
internal void WriteInt(int data)
{
fileOut.Write(data);
}
internal void WriteLong(long data)
{
fileOut.Write(data);
}
internal void WriteDouble(double data)
{
fileOut.Write(data);
}
internal void WriteDouble(double val, int count)
{
for (int i = 0; i < count; i++)
{
fileOut.Write(val);
}
}
internal void WriteChar(char data)
{
fileOut.Write(data);
}
internal bool SafeMode
{
get
{
return safeMode;
}
set
{
this.safeMode = value;
}
}
/// <summary>
///
/// </summary>
public string FilePath
{
get
{
return filePath;
}
}
/// <summary>
///
/// </summary>
public long FileSize
{
get
{
return fs.Length;
}
}
internal static int LockMode
{
get
{
return lockMode;
}
set
{
RrdFile.lockMode = value;
}
}
internal int RrdMode
{
get
{
return rrdMode;
}
set
{
this.rrdMode = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
using System.Threading;
namespace System.Text
{
internal class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
internal BaseCodePageEncoding encoding = null;
internal char[] arrayBestFit = null;
internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding)
{
// Need to load our replacement characters table.
encoding = _encoding;
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalEncoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(Object value)
{
InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback;
if (that != null)
{
return (encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return encoding.CodePage;
}
}
internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
{
// Our variables
private char _cBestFit = '\0';
private InternalEncoderBestFitFallback _oFallback;
private int _iCount = -1;
private int _iSize;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
{
_oFallback = fallback;
if (_oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (_oFallback.arrayBestFit == null)
_oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData();
}
}
}
// Fallback methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
_iCount = _iSize = 1;
_cBestFit = TryBestFit(charUnknown);
if (_cBestFit == '\0')
_cBestFit = '?';
return true;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
Contract.EndContractBlock();
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
_cBestFit = '?';
_iCount = _iSize = 2;
return true;
}
// Default version is overridden in EncoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_iCount == int.MaxValue)
{
_iCount = -1;
return '\0';
}
// Return the best fit character
return _cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (_iCount >= 0)
_iCount++;
// Return true if we could do it.
return (_iCount >= 0 && _iCount <= _iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (_iCount > 0) ? _iCount : 0;
}
}
// Clear the buffer
[System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe void Reset()
{
_iCount = -1;
}
// private helper methods
private char TryBestFit(char cUnknown)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = _oFallback.arrayBestFit.Length;
int index;
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because we want to be on word boundaries.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = _oFallback.arrayBestFit[index];
if (cTest == cUnknown)
{
// We found it
Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback.arrayBestFit[index + 1];
}
else if (cTest < cUnknown)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (_oFallback.arrayBestFit[index] == cUnknown)
{
// We found it
Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IconifyXamarin.Material
{
public class MaterialIcons : IIcon
{
public const char md_3d_rotation = '\ue84d';
public const char md_access_alarm = '\ue190';
public const char md_access_alarms = '\ue191';
public const char md_access_time = '\ue192';
public const char md_accessibility = '\ue84e';
public const char md_account_balance = '\ue84f';
public const char md_account_balance_wallet = '\ue850';
public const char md_account_box = '\ue851';
public const char md_account_circle = '\ue853';
public const char md_adb = '\ue60e';
public const char md_add = '\ue145';
public const char md_add_alarm = '\ue193';
public const char md_add_alert = '\ue003';
public const char md_add_box = '\ue146';
public const char md_add_circle = '\ue147';
public const char md_add_circle_outline = '\ue148';
public const char md_add_shopping_cart = '\ue854';
public const char md_add_to_photos = '\ue39d';
public const char md_adjust = '\ue39e';
public const char md_airline_seat_flat = '\ue630';
public const char md_airline_seat_flat_angled = '\ue631';
public const char md_airline_seat_individual_suite = '\ue632';
public const char md_airline_seat_legroom_extra = '\ue633';
public const char md_airline_seat_legroom_normal = '\ue634';
public const char md_airline_seat_legroom_reduced = '\ue635';
public const char md_airline_seat_recline_extra = '\ue636';
public const char md_airline_seat_recline_normal = '\ue637';
public const char md_airplanemode_active = '\ue195';
public const char md_airplanemode_inactive = '\ue194';
public const char md_airplay = '\ue055';
public const char md_alarm = '\ue855';
public const char md_alarm_add = '\ue856';
public const char md_alarm_off = '\ue857';
public const char md_alarm_on = '\ue858';
public const char md_album = '\ue019';
public const char md_android = '\ue859';
public const char md_announcement = '\ue85a';
public const char md_apps = '\ue5c3';
public const char md_archive = '\ue149';
public const char md_arrow_back = '\ue5c4';
public const char md_arrow_drop_down = '\ue5c5';
public const char md_arrow_drop_down_circle = '\ue5c6';
public const char md_arrow_drop_up = '\ue5c7';
public const char md_arrow_forward = '\ue5c8';
public const char md_aspect_ratio = '\ue85b';
public const char md_assessment = '\ue85c';
public const char md_assignment = '\ue85d';
public const char md_assignment_ind = '\ue85e';
public const char md_assignment_late = '\ue85f';
public const char md_assignment_return = '\ue860';
public const char md_assignment_returned = '\ue861';
public const char md_assignment_turned_in = '\ue862';
public const char md_assistant = '\ue39f';
public const char md_assistant_photo = '\ue3a0';
public const char md_attach_file = '\ue226';
public const char md_attach_money = '\ue227';
public const char md_attachment = '\ue2bc';
public const char md_audiotrack = '\ue3a1';
public const char md_autorenew = '\ue863';
public const char md_av_timer = '\ue01b';
public const char md_backspace = '\ue14a';
public const char md_backup = '\ue864';
public const char md_battery_alert = '\ue19c';
public const char md_battery_charging_full = '\ue1a3';
public const char md_battery_full = '\ue1a4';
public const char md_battery_std = '\ue1a5';
public const char md_battery_unknown = '\ue1a6';
public const char md_beenhere = '\ue52d';
public const char md_block = '\ue14b';
public const char md_bluetooth = '\ue1a7';
public const char md_bluetooth_audio = '\ue60f';
public const char md_bluetooth_connected = '\ue1a8';
public const char md_bluetooth_disabled = '\ue1a9';
public const char md_bluetooth_searching = '\ue1aa';
public const char md_blur_circular = '\ue3a2';
public const char md_blur_linear = '\ue3a3';
public const char md_blur_off = '\ue3a4';
public const char md_blur_on = '\ue3a5';
public const char md_book = '\ue865';
public const char md_bookmark = '\ue866';
public const char md_bookmark_border = '\ue867';
public const char md_border_all = '\ue228';
public const char md_border_bottom = '\ue229';
public const char md_border_clear = '\ue22a';
public const char md_border_color = '\ue22b';
public const char md_border_horizontal = '\ue22c';
public const char md_border_inner = '\ue22d';
public const char md_border_left = '\ue22e';
public const char md_border_outer = '\ue22f';
public const char md_border_right = '\ue230';
public const char md_border_style = '\ue231';
public const char md_border_top = '\ue232';
public const char md_border_vertical = '\ue233';
public const char md_brightness_1 = '\ue3a6';
public const char md_brightness_2 = '\ue3a7';
public const char md_brightness_3 = '\ue3a8';
public const char md_brightness_4 = '\ue3a9';
public const char md_brightness_5 = '\ue3aa';
public const char md_brightness_6 = '\ue3ab';
public const char md_brightness_7 = '\ue3ac';
public const char md_brightness_auto = '\ue1ab';
public const char md_brightness_high = '\ue1ac';
public const char md_brightness_low = '\ue1ad';
public const char md_brightness_medium = '\ue1ae';
public const char md_broken_image = '\ue3ad';
public const char md_brush = '\ue3ae';
public const char md_bug_report = '\ue868';
public const char md_build = '\ue869';
public const char md_business = '\ue0af';
public const char md_cached = '\ue86a';
public const char md_cake = '\ue7e9';
public const char md_call = '\ue0b0';
public const char md_call_end = '\ue0b1';
public const char md_call_made = '\ue0b2';
public const char md_call_merge = '\ue0b3';
public const char md_call_missed = '\ue0b4';
public const char md_call_received = '\ue0b5';
public const char md_call_split = '\ue0b6';
public const char md_camera = '\ue3af';
public const char md_camera_alt = '\ue3b0';
public const char md_camera_enhance = '\ue8fc';
public const char md_camera_front = '\ue3b1';
public const char md_camera_rear = '\ue3b2';
public const char md_camera_roll = '\ue3b3';
public const char md_cancel = '\ue5c9';
public const char md_card_giftcard = '\ue8f6';
public const char md_card_membership = '\ue8f7';
public const char md_card_travel = '\ue8f8';
public const char md_cast = '\ue307';
public const char md_cast_connected = '\ue308';
public const char md_center_focus_strong = '\ue3b4';
public const char md_center_focus_weak = '\ue3b5';
public const char md_change_history = '\ue86b';
public const char md_chat = '\ue0b7';
public const char md_chat_bubble = '\ue0ca';
public const char md_chat_bubble_outline = '\ue0cb';
public const char md_check = '\ue5ca';
public const char md_check_box = '\ue834';
public const char md_check_box_outline_blank = '\ue835';
public const char md_check_circle = '\ue86c';
public const char md_chevron_left = '\ue5cb';
public const char md_chevron_right = '\ue5cc';
public const char md_chrome_reader_mode = '\ue86d';
public const char md_class = '\ue86e';
public const char md_clear = '\ue14c';
public const char md_clear_all = '\ue0b8';
public const char md_close = '\ue5cd';
public const char md_closed_caption = '\ue01c';
public const char md_cloud = '\ue2bd';
public const char md_cloud_circle = '\ue2be';
public const char md_cloud_done = '\ue2bf';
public const char md_cloud_download = '\ue2c0';
public const char md_cloud_off = '\ue2c1';
public const char md_cloud_queue = '\ue2c2';
public const char md_cloud_upload = '\ue2c3';
public const char md_code = '\ue86f';
public const char md_collections = '\ue3b6';
public const char md_collections_bookmark = '\ue431';
public const char md_color_lens = '\ue3b7';
public const char md_colorize = '\ue3b8';
public const char md_comment = '\ue0b9';
public const char md_compare = '\ue3b9';
public const char md_computer = '\ue30a';
public const char md_confirmation_number = '\ue638';
public const char md_contact_phone = '\ue0cf';
public const char md_contacts = '\ue0ba';
public const char md_content_copy = '\ue14d';
public const char md_content_cut = '\ue14e';
public const char md_content_paste = '\ue14f';
public const char md_control_point = '\ue3ba';
public const char md_control_point_duplicate = '\ue3bb';
public const char md_create = '\ue150';
public const char md_credit_card = '\ue870';
public const char md_crop = '\ue3be';
public const char md_crop_16_9 = '\ue3bc';
public const char md_crop_3_2 = '\ue3bd';
public const char md_crop_5_4 = '\ue3bf';
public const char md_crop_7_5 = '\ue3c0';
public const char md_crop_din = '\ue3c1';
public const char md_crop_free = '\ue3c2';
public const char md_crop_landscape = '\ue3c3';
public const char md_crop_original = '\ue3c4';
public const char md_crop_portrait = '\ue3c5';
public const char md_crop_square = '\ue3c6';
public const char md_dashboard = '\ue871';
public const char md_data_usage = '\ue1af';
public const char md_dehaze = '\ue3c7';
public const char md_delete = '\ue872';
public const char md_description = '\ue873';
public const char md_desktop_mac = '\ue30b';
public const char md_desktop_windows = '\ue30c';
public const char md_details = '\ue3c8';
public const char md_developer_board = '\ue30d';
public const char md_developer_mode = '\ue1b0';
public const char md_device_hub = '\ue335';
public const char md_devices = '\ue1b1';
public const char md_dialer_sip = '\ue0bb';
public const char md_dialpad = '\ue0bc';
public const char md_directions = '\ue52e';
public const char md_directions_bike = '\ue52f';
public const char md_directions_boat = '\ue532';
public const char md_directions_bus = '\ue530';
public const char md_directions_car = '\ue531';
public const char md_directions_railway = '\ue534';
public const char md_directions_run = '\ue566';
public const char md_directions_subway = '\ue533';
public const char md_directions_transit = '\ue535';
public const char md_directions_walk = '\ue536';
public const char md_disc_full = '\ue610';
public const char md_dns = '\ue875';
public const char md_do_not_disturb = '\ue612';
public const char md_do_not_disturb_alt = '\ue611';
public const char md_dock = '\ue30e';
public const char md_domain = '\ue7ee';
public const char md_done = '\ue876';
public const char md_done_all = '\ue877';
public const char md_drafts = '\ue151';
public const char md_drive_eta = '\ue613';
public const char md_dvr = '\ue1b2';
public const char md_edit = '\ue3c9';
public const char md_eject = '\ue8fb';
public const char md_email = '\ue0be';
public const char md_equalizer = '\ue01d';
public const char md_error = '\ue000';
public const char md_error_outline = '\ue001';
public const char md_event = '\ue878';
public const char md_event_available = '\ue614';
public const char md_event_busy = '\ue615';
public const char md_event_note = '\ue616';
public const char md_event_seat = '\ue903';
public const char md_exit_to_app = '\ue879';
public const char md_expand_less = '\ue5ce';
public const char md_expand_more = '\ue5cf';
public const char md_explicit = '\ue01e';
public const char md_explore = '\ue87a';
public const char md_exposure = '\ue3ca';
public const char md_exposure_neg_1 = '\ue3cb';
public const char md_exposure_neg_2 = '\ue3cc';
public const char md_exposure_plus_1 = '\ue3cd';
public const char md_exposure_plus_2 = '\ue3ce';
public const char md_exposure_zero = '\ue3cf';
public const char md_extension = '\ue87b';
public const char md_face = '\ue87c';
public const char md_fast_forward = '\ue01f';
public const char md_fast_rewind = '\ue020';
public const char md_favorite = '\ue87d';
public const char md_favorite_border = '\ue87e';
public const char md_feedback = '\ue87f';
public const char md_file_download = '\ue2c4';
public const char md_file_upload = '\ue2c6';
public const char md_filter = '\ue3d3';
public const char md_filter_1 = '\ue3d0';
public const char md_filter_2 = '\ue3d1';
public const char md_filter_3 = '\ue3d2';
public const char md_filter_4 = '\ue3d4';
public const char md_filter_5 = '\ue3d5';
public const char md_filter_6 = '\ue3d6';
public const char md_filter_7 = '\ue3d7';
public const char md_filter_8 = '\ue3d8';
public const char md_filter_9 = '\ue3d9';
public const char md_filter_9_plus = '\ue3da';
public const char md_filter_b_and_w = '\ue3db';
public const char md_filter_center_focus = '\ue3dc';
public const char md_filter_drama = '\ue3dd';
public const char md_filter_frames = '\ue3de';
public const char md_filter_hdr = '\ue3df';
public const char md_filter_list = '\ue152';
public const char md_filter_none = '\ue3e0';
public const char md_filter_tilt_shift = '\ue3e2';
public const char md_filter_vintage = '\ue3e3';
public const char md_find_in_page = '\ue880';
public const char md_find_replace = '\ue881';
public const char md_flag = '\ue153';
public const char md_flare = '\ue3e4';
public const char md_flash_auto = '\ue3e5';
public const char md_flash_off = '\ue3e6';
public const char md_flash_on = '\ue3e7';
public const char md_flight = '\ue539';
public const char md_flight_land = '\ue904';
public const char md_flight_takeoff = '\ue905';
public const char md_flip = '\ue3e8';
public const char md_flip_to_back = '\ue882';
public const char md_flip_to_front = '\ue883';
public const char md_folder = '\ue2c7';
public const char md_folder_open = '\ue2c8';
public const char md_folder_shared = '\ue2c9';
public const char md_folder_special = '\ue617';
public const char md_font_download = '\ue167';
public const char md_format_align_center = '\ue234';
public const char md_format_align_justify = '\ue235';
public const char md_format_align_left = '\ue236';
public const char md_format_align_right = '\ue237';
public const char md_format_bold = '\ue238';
public const char md_format_clear = '\ue239';
public const char md_format_color_fill = '\ue23a';
public const char md_format_color_reset = '\ue23b';
public const char md_format_color_text = '\ue23c';
public const char md_format_indent_decrease = '\ue23d';
public const char md_format_indent_increase = '\ue23e';
public const char md_format_italic = '\ue23f';
public const char md_format_line_spacing = '\ue240';
public const char md_format_list_bulleted = '\ue241';
public const char md_format_list_numbered = '\ue242';
public const char md_format_paint = '\ue243';
public const char md_format_quote = '\ue244';
public const char md_format_size = '\ue245';
public const char md_format_strikethrough = '\ue246';
public const char md_format_textdirection_l_to_r = '\ue247';
public const char md_format_textdirection_r_to_l = '\ue248';
public const char md_format_underlined = '\ue249';
public const char md_forum = '\ue0bf';
public const char md_forward = '\ue154';
public const char md_forward_10 = '\ue056';
public const char md_forward_30 = '\ue057';
public const char md_forward_5 = '\ue058';
public const char md_fullscreen = '\ue5d0';
public const char md_fullscreen_exit = '\ue5d1';
public const char md_functions = '\ue24a';
public const char md_gamepad = '\ue30f';
public const char md_games = '\ue021';
public const char md_gesture = '\ue155';
public const char md_get_app = '\ue884';
public const char md_gif = '\ue908';
public const char md_gps_fixed = '\ue1b3';
public const char md_gps_not_fixed = '\ue1b4';
public const char md_gps_off = '\ue1b5';
public const char md_grade = '\ue885';
public const char md_gradient = '\ue3e9';
public const char md_grain = '\ue3ea';
public const char md_graphic_eq = '\ue1b8';
public const char md_grid_off = '\ue3eb';
public const char md_grid_on = '\ue3ec';
public const char md_group = '\ue7ef';
public const char md_group_add = '\ue7f0';
public const char md_group_work = '\ue886';
public const char md_hd = '\ue052';
public const char md_hdr_off = '\ue3ed';
public const char md_hdr_on = '\ue3ee';
public const char md_hdr_strong = '\ue3f1';
public const char md_hdr_weak = '\ue3f2';
public const char md_headset = '\ue310';
public const char md_headset_mic = '\ue311';
public const char md_healing = '\ue3f3';
public const char md_hearing = '\ue023';
public const char md_help = '\ue887';
public const char md_help_outline = '\ue8fd';
public const char md_high_quality = '\ue024';
public const char md_highlight_off = '\ue888';
public const char md_history = '\ue889';
public const char md_home = '\ue88a';
public const char md_hotel = '\ue53a';
public const char md_hourglass_empty = '\ue88b';
public const char md_hourglass_full = '\ue88c';
public const char md_http = '\ue902';
public const char md_https = '\ue88d';
public const char md_image = '\ue3f4';
public const char md_image_aspect_ratio = '\ue3f5';
public const char md_import_export = '\ue0c3';
public const char md_inbox = '\ue156';
public const char md_indeterminate_check_box = '\ue909';
public const char md_info = '\ue88e';
public const char md_info_outline = '\ue88f';
public const char md_input = '\ue890';
public const char md_insert_chart = '\ue24b';
public const char md_insert_comment = '\ue24c';
public const char md_insert_drive_file = '\ue24d';
public const char md_insert_emoticon = '\ue24e';
public const char md_insert_invitation = '\ue24f';
public const char md_insert_link = '\ue250';
public const char md_insert_photo = '\ue251';
public const char md_invert_colors = '\ue891';
public const char md_invert_colors_off = '\ue0c4';
public const char md_iso = '\ue3f6';
public const char md_keyboard = '\ue312';
public const char md_keyboard_arrow_down = '\ue313';
public const char md_keyboard_arrow_left = '\ue314';
public const char md_keyboard_arrow_right = '\ue315';
public const char md_keyboard_arrow_up = '\ue316';
public const char md_keyboard_backspace = '\ue317';
public const char md_keyboard_capslock = '\ue318';
public const char md_keyboard_hide = '\ue31a';
public const char md_keyboard_return = '\ue31b';
public const char md_keyboard_tab = '\ue31c';
public const char md_keyboard_voice = '\ue31d';
public const char md_label = '\ue892';
public const char md_label_outline = '\ue893';
public const char md_landscape = '\ue3f7';
public const char md_language = '\ue894';
public const char md_laptop = '\ue31e';
public const char md_laptop_chromebook = '\ue31f';
public const char md_laptop_mac = '\ue320';
public const char md_laptop_windows = '\ue321';
public const char md_launch = '\ue895';
public const char md_layers = '\ue53b';
public const char md_layers_clear = '\ue53c';
public const char md_leak_add = '\ue3f8';
public const char md_leak_remove = '\ue3f9';
public const char md_lens = '\ue3fa';
public const char md_library_add = '\ue02e';
public const char md_library_books = '\ue02f';
public const char md_library_music = '\ue030';
public const char md_link = '\ue157';
public const char md_list = '\ue896';
public const char md_live_help = '\ue0c6';
public const char md_live_tv = '\ue639';
public const char md_local_activity = '\ue53f';
public const char md_local_airport = '\ue53d';
public const char md_local_atm = '\ue53e';
public const char md_local_bar = '\ue540';
public const char md_local_cafe = '\ue541';
public const char md_local_car_wash = '\ue542';
public const char md_local_convenience_store = '\ue543';
public const char md_local_dining = '\ue556';
public const char md_local_drink = '\ue544';
public const char md_local_florist = '\ue545';
public const char md_local_gas_station = '\ue546';
public const char md_local_grocery_store = '\ue547';
public const char md_local_hospital = '\ue548';
public const char md_local_hotel = '\ue549';
public const char md_local_laundry_service = '\ue54a';
public const char md_local_library = '\ue54b';
public const char md_local_mall = '\ue54c';
public const char md_local_movies = '\ue54d';
public const char md_local_offer = '\ue54e';
public const char md_local_parking = '\ue54f';
public const char md_local_pharmacy = '\ue550';
public const char md_local_phone = '\ue551';
public const char md_local_pizza = '\ue552';
public const char md_local_play = '\ue553';
public const char md_local_post_office = '\ue554';
public const char md_local_printshop = '\ue555';
public const char md_local_see = '\ue557';
public const char md_local_shipping = '\ue558';
public const char md_local_taxi = '\ue559';
public const char md_location_city = '\ue7f1';
public const char md_location_disabled = '\ue1b6';
public const char md_location_off = '\ue0c7';
public const char md_location_on = '\ue0c8';
public const char md_location_searching = '\ue1b7';
public const char md_lock = '\ue897';
public const char md_lock_open = '\ue898';
public const char md_lock_outline = '\ue899';
public const char md_looks = '\ue3fc';
public const char md_looks_3 = '\ue3fb';
public const char md_looks_4 = '\ue3fd';
public const char md_looks_5 = '\ue3fe';
public const char md_looks_6 = '\ue3ff';
public const char md_looks_one = '\ue400';
public const char md_looks_two = '\ue401';
public const char md_loop = '\ue028';
public const char md_loupe = '\ue402';
public const char md_loyalty = '\ue89a';
public const char md_mail = '\ue158';
public const char md_map = '\ue55b';
public const char md_markunread = '\ue159';
public const char md_markunread_mailbox = '\ue89b';
public const char md_memory = '\ue322';
public const char md_menu = '\ue5d2';
public const char md_merge_type = '\ue252';
public const char md_message = '\ue0c9';
public const char md_mic = '\ue029';
public const char md_mic_none = '\ue02a';
public const char md_mic_off = '\ue02b';
public const char md_mms = '\ue618';
public const char md_mode_comment = '\ue253';
public const char md_mode_edit = '\ue254';
public const char md_money_off = '\ue25c';
public const char md_monochrome_photos = '\ue403';
public const char md_mood = '\ue7f2';
public const char md_mood_bad = '\ue7f3';
public const char md_more = '\ue619';
public const char md_more_horiz = '\ue5d3';
public const char md_more_vert = '\ue5d4';
public const char md_mouse = '\ue323';
public const char md_movie = '\ue02c';
public const char md_movie_creation = '\ue404';
public const char md_music_note = '\ue405';
public const char md_my_location = '\ue55c';
public const char md_nature = '\ue406';
public const char md_nature_people = '\ue407';
public const char md_navigate_before = '\ue408';
public const char md_navigate_next = '\ue409';
public const char md_navigation = '\ue55d';
public const char md_network_cell = '\ue1b9';
public const char md_network_locked = '\ue61a';
public const char md_network_wifi = '\ue1ba';
public const char md_new_releases = '\ue031';
public const char md_nfc = '\ue1bb';
public const char md_no_sim = '\ue0cc';
public const char md_not_interested = '\ue033';
public const char md_note_add = '\ue89c';
public const char md_notifications = '\ue7f4';
public const char md_notifications_active = '\ue7f7';
public const char md_notifications_none = '\ue7f5';
public const char md_notifications_off = '\ue7f6';
public const char md_notifications_paused = '\ue7f8';
public const char md_offline_pin = '\ue90a';
public const char md_ondemand_video = '\ue63a';
public const char md_open_in_browser = '\ue89d';
public const char md_open_in_new = '\ue89e';
public const char md_open_with = '\ue89f';
public const char md_pages = '\ue7f9';
public const char md_pageview = '\ue8a0';
public const char md_palette = '\ue40a';
public const char md_panorama = '\ue40b';
public const char md_panorama_fish_eye = '\ue40c';
public const char md_panorama_horizontal = '\ue40d';
public const char md_panorama_vertical = '\ue40e';
public const char md_panorama_wide_angle = '\ue40f';
public const char md_party_mode = '\ue7fa';
public const char md_pause = '\ue034';
public const char md_pause_circle_filled = '\ue035';
public const char md_pause_circle_outline = '\ue036';
public const char md_payment = '\ue8a1';
public const char md_people = '\ue7fb';
public const char md_people_outline = '\ue7fc';
public const char md_perm_camera_mic = '\ue8a2';
public const char md_perm_contact_calendar = '\ue8a3';
public const char md_perm_data_setting = '\ue8a4';
public const char md_perm_device_information = '\ue8a5';
public const char md_perm_identity = '\ue8a6';
public const char md_perm_media = '\ue8a7';
public const char md_perm_phone_msg = '\ue8a8';
public const char md_perm_scan_wifi = '\ue8a9';
public const char md_person = '\ue7fd';
public const char md_person_add = '\ue7fe';
public const char md_person_outline = '\ue7ff';
public const char md_person_pin = '\ue55a';
public const char md_personal_video = '\ue63b';
public const char md_phone = '\ue0cd';
public const char md_phone_android = '\ue324';
public const char md_phone_bluetooth_speaker = '\ue61b';
public const char md_phone_forwarded = '\ue61c';
public const char md_phone_in_talk = '\ue61d';
public const char md_phone_iphone = '\ue325';
public const char md_phone_locked = '\ue61e';
public const char md_phone_missed = '\ue61f';
public const char md_phone_paused = '\ue620';
public const char md_phonelink = '\ue326';
public const char md_phonelink_erase = '\ue0db';
public const char md_phonelink_lock = '\ue0dc';
public const char md_phonelink_off = '\ue327';
public const char md_phonelink_ring = '\ue0dd';
public const char md_phonelink_setup = '\ue0de';
public const char md_photo = '\ue410';
public const char md_photo_album = '\ue411';
public const char md_photo_camera = '\ue412';
public const char md_photo_library = '\ue413';
public const char md_photo_size_select_actual = '\ue432';
public const char md_photo_size_select_large = '\ue433';
public const char md_photo_size_select_small = '\ue434';
public const char md_picture_as_pdf = '\ue415';
public const char md_picture_in_picture = '\ue8aa';
public const char md_pin_drop = '\ue55e';
public const char md_place = '\ue55f';
public const char md_play_arrow = '\ue037';
public const char md_play_circle_filled = '\ue038';
public const char md_play_circle_outline = '\ue039';
public const char md_play_for_work = '\ue906';
public const char md_playlist_add = '\ue03b';
public const char md_plus_one = '\ue800';
public const char md_poll = '\ue801';
public const char md_polymer = '\ue8ab';
public const char md_portable_wifi_off = '\ue0ce';
public const char md_portrait = '\ue416';
public const char md_power = '\ue63c';
public const char md_power_input = '\ue336';
public const char md_power_settings_new = '\ue8ac';
public const char md_present_to_all = '\ue0df';
public const char md_print = '\ue8ad';
public const char md_public = '\ue80b';
public const char md_publish = '\ue255';
public const char md_query_builder = '\ue8ae';
public const char md_question_answer = '\ue8af';
public const char md_queue = '\ue03c';
public const char md_queue_music = '\ue03d';
public const char md_radio = '\ue03e';
public const char md_radio_button_checked = '\ue837';
public const char md_radio_button_unchecked = '\ue836';
public const char md_rate_review = '\ue560';
public const char md_receipt = '\ue8b0';
public const char md_recent_actors = '\ue03f';
public const char md_redeem = '\ue8b1';
public const char md_redo = '\ue15a';
public const char md_refresh = '\ue5d5';
public const char md_remove = '\ue15b';
public const char md_remove_circle = '\ue15c';
public const char md_remove_circle_outline = '\ue15d';
public const char md_remove_red_eye = '\ue417';
public const char md_reorder = '\ue8fe';
public const char md_repeat = '\ue040';
public const char md_repeat_one = '\ue041';
public const char md_replay = '\ue042';
public const char md_replay_10 = '\ue059';
public const char md_replay_30 = '\ue05a';
public const char md_replay_5 = '\ue05b';
public const char md_reply = '\ue15e';
public const char md_reply_all = '\ue15f';
public const char md_report = '\ue160';
public const char md_report_problem = '\ue8b2';
public const char md_restaurant_menu = '\ue561';
public const char md_restore = '\ue8b3';
public const char md_ring_volume = '\ue0d1';
public const char md_room = '\ue8b4';
public const char md_rotate_90_degrees_ccw = '\ue418';
public const char md_rotate_left = '\ue419';
public const char md_rotate_right = '\ue41a';
public const char md_router = '\ue328';
public const char md_satellite = '\ue562';
public const char md_save = '\ue161';
public const char md_scanner = '\ue329';
public const char md_schedule = '\ue8b5';
public const char md_school = '\ue80c';
public const char md_screen_lock_landscape = '\ue1be';
public const char md_screen_lock_portrait = '\ue1bf';
public const char md_screen_lock_rotation = '\ue1c0';
public const char md_screen_rotation = '\ue1c1';
public const char md_sd_card = '\ue623';
public const char md_sd_storage = '\ue1c2';
public const char md_search = '\ue8b6';
public const char md_security = '\ue32a';
public const char md_select_all = '\ue162';
public const char md_send = '\ue163';
public const char md_settings = '\ue8b8';
public const char md_settings_applications = '\ue8b9';
public const char md_settings_backup_restore = '\ue8ba';
public const char md_settings_bluetooth = '\ue8bb';
public const char md_settings_brightness = '\ue8bd';
public const char md_settings_cell = '\ue8bc';
public const char md_settings_ethernet = '\ue8be';
public const char md_settings_input_antenna = '\ue8bf';
public const char md_settings_input_component = '\ue8c0';
public const char md_settings_input_composite = '\ue8c1';
public const char md_settings_input_hdmi = '\ue8c2';
public const char md_settings_input_svideo = '\ue8c3';
public const char md_settings_overscan = '\ue8c4';
public const char md_settings_phone = '\ue8c5';
public const char md_settings_power = '\ue8c6';
public const char md_settings_remote = '\ue8c7';
public const char md_settings_system_daydream = '\ue1c3';
public const char md_settings_voice = '\ue8c8';
public const char md_share = '\ue80d';
public const char md_shop = '\ue8c9';
public const char md_shop_two = '\ue8ca';
public const char md_shopping_basket = '\ue8cb';
public const char md_shopping_cart = '\ue8cc';
public const char md_shuffle = '\ue043';
public const char md_signal_cellular_4_bar = '\ue1c8';
public const char md_signal_cellular_connected_no_internet_4_bar = '\ue1cd';
public const char md_signal_cellular_no_sim = '\ue1ce';
public const char md_signal_cellular_null = '\ue1cf';
public const char md_signal_cellular_off = '\ue1d0';
public const char md_signal_wifi_4_bar = '\ue1d8';
public const char md_signal_wifi_4_bar_lock = '\ue1d9';
public const char md_signal_wifi_off = '\ue1da';
public const char md_sim_card = '\ue32b';
public const char md_sim_card_alert = '\ue624';
public const char md_skip_next = '\ue044';
public const char md_skip_previous = '\ue045';
public const char md_slideshow = '\ue41b';
public const char md_smartphone = '\ue32c';
public const char md_sms = '\ue625';
public const char md_sms_failed = '\ue626';
public const char md_snooze = '\ue046';
public const char md_sort = '\ue164';
public const char md_sort_by_alpha = '\ue053';
public const char md_space_bar = '\ue256';
public const char md_speaker = '\ue32d';
public const char md_speaker_group = '\ue32e';
public const char md_speaker_notes = '\ue8cd';
public const char md_speaker_phone = '\ue0d2';
public const char md_spellcheck = '\ue8ce';
public const char md_star = '\ue838';
public const char md_star_border = '\ue83a';
public const char md_star_half = '\ue839';
public const char md_stars = '\ue8d0';
public const char md_stay_current_landscape = '\ue0d3';
public const char md_stay_current_portrait = '\ue0d4';
public const char md_stay_primary_landscape = '\ue0d5';
public const char md_stay_primary_portrait = '\ue0d6';
public const char md_stop = '\ue047';
public const char md_storage = '\ue1db';
public const char md_store = '\ue8d1';
public const char md_store_mall_directory = '\ue563';
public const char md_straighten = '\ue41c';
public const char md_strikethrough_s = '\ue257';
public const char md_style = '\ue41d';
public const char md_subject = '\ue8d2';
public const char md_subtitles = '\ue048';
public const char md_supervisor_account = '\ue8d3';
public const char md_surround_sound = '\ue049';
public const char md_swap_calls = '\ue0d7';
public const char md_swap_horiz = '\ue8d4';
public const char md_swap_vert = '\ue8d5';
public const char md_swap_vertical_circle = '\ue8d6';
public const char md_switch_camera = '\ue41e';
public const char md_switch_video = '\ue41f';
public const char md_sync = '\ue627';
public const char md_sync_disabled = '\ue628';
public const char md_sync_problem = '\ue629';
public const char md_system_update = '\ue62a';
public const char md_system_update_alt = '\ue8d7';
public const char md_tab = '\ue8d8';
public const char md_tab_unselected = '\ue8d9';
public const char md_tablet = '\ue32f';
public const char md_tablet_android = '\ue330';
public const char md_tablet_mac = '\ue331';
public const char md_tag_faces = '\ue420';
public const char md_tap_and_play = '\ue62b';
public const char md_terrain = '\ue564';
public const char md_text_format = '\ue165';
public const char md_textsms = '\ue0d8';
public const char md_texture = '\ue421';
public const char md_theaters = '\ue8da';
public const char md_thumb_down = '\ue8db';
public const char md_thumb_up = '\ue8dc';
public const char md_thumbs_up_down = '\ue8dd';
public const char md_time_to_leave = '\ue62c';
public const char md_timelapse = '\ue422';
public const char md_timer = '\ue425';
public const char md_timer_10 = '\ue423';
public const char md_timer_3 = '\ue424';
public const char md_timer_off = '\ue426';
public const char md_toc = '\ue8de';
public const char md_today = '\ue8df';
public const char md_toll = '\ue8e0';
public const char md_tonality = '\ue427';
public const char md_toys = '\ue332';
public const char md_track_changes = '\ue8e1';
public const char md_traffic = '\ue565';
public const char md_transform = '\ue428';
public const char md_translate = '\ue8e2';
public const char md_trending_down = '\ue8e3';
public const char md_trending_flat = '\ue8e4';
public const char md_trending_up = '\ue8e5';
public const char md_tune = '\ue429';
public const char md_turned_in = '\ue8e6';
public const char md_turned_in_not = '\ue8e7';
public const char md_tv = '\ue333';
public const char md_undo = '\ue166';
public const char md_unfold_less = '\ue5d6';
public const char md_unfold_more = '\ue5d7';
public const char md_usb = '\ue1e0';
public const char md_verified_user = '\ue8e8';
public const char md_vertical_align_bottom = '\ue258';
public const char md_vertical_align_center = '\ue259';
public const char md_vertical_align_top = '\ue25a';
public const char md_vibration = '\ue62d';
public const char md_video_library = '\ue04a';
public const char md_videocam = '\ue04b';
public const char md_videocam_off = '\ue04c';
public const char md_view_agenda = '\ue8e9';
public const char md_view_array = '\ue8ea';
public const char md_view_carousel = '\ue8eb';
public const char md_view_column = '\ue8ec';
public const char md_view_comfy = '\ue42a';
public const char md_view_compact = '\ue42b';
public const char md_view_day = '\ue8ed';
public const char md_view_headline = '\ue8ee';
public const char md_view_list = '\ue8ef';
public const char md_view_module = '\ue8f0';
public const char md_view_quilt = '\ue8f1';
public const char md_view_stream = '\ue8f2';
public const char md_view_week = '\ue8f3';
public const char md_vignette = '\ue435';
public const char md_visibility = '\ue8f4';
public const char md_visibility_off = '\ue8f5';
public const char md_voice_chat = '\ue62e';
public const char md_voicemail = '\ue0d9';
public const char md_volume_down = '\ue04d';
public const char md_volume_mute = '\ue04e';
public const char md_volume_off = '\ue04f';
public const char md_volume_up = '\ue050';
public const char md_vpn_key = '\ue0da';
public const char md_vpn_lock = '\ue62f';
public const char md_wallpaper = '\ue1bc';
public const char md_warning = '\ue002';
public const char md_watch = '\ue334';
public const char md_wb_auto = '\ue42c';
public const char md_wb_cloudy = '\ue42d';
public const char md_wb_incandescent = '\ue42e';
public const char md_wb_iridescent = '\ue436';
public const char md_wb_sunny = '\ue430';
public const char md_wc = '\ue63d';
public const char md_web = '\ue051';
public const char md_whatshot = '\ue80e';
public const char md_widgets = '\ue1bd';
public const char md_wifi = '\ue63e';
public const char md_wifi_lock = '\ue1e1';
public const char md_wifi_tethering = '\ue1e2';
public const char md_work = '\ue8f9';
public const char md_wrap_text = '\ue25b';
public const char md_youtube_searched_for = '\ue8fa';
public const char md_zoom_in = '\ue8ff';
public const char md_zoom_out = '\ue900';
public static readonly List<KeyValuePair<char, string>> Characters;
public static IIcon[] Icons { get; }
static MaterialIcons()
{
Characters = IconReflectionUtils.GetIcons<MaterialIcons>();
Icons = Characters.Select(p => new MaterialIcons(p.Value, p.Key)).Cast<IIcon>().ToArray();
}
private readonly string _key;
public MaterialIcons(string key, char @char)
{
_key = key;
Character = @char;
}
public string Key => Characters.Single(p => p.Value == _key).Value.Replace("_", "-");
public char Character { get; }
}
}
| |
//
// Reflect.cs: Creates Element classes from an instance
//
// Author:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010, Novell, Inc.
//
// Code licensed under the MIT X11 license
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UIKit;
using CoreGraphics;
using Foundation;
namespace MonoTouch.Dialog
{
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class EntryAttribute : Attribute {
public EntryAttribute () : this (null) { }
public EntryAttribute (string placeholder)
{
Placeholder = placeholder;
}
public string Placeholder;
public UIKeyboardType KeyboardType;
public UITextAutocorrectionType AutocorrectionType;
public UITextAutocapitalizationType AutocapitalizationType;
public UITextFieldViewMode ClearButtonMode;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class DateAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class TimeAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CheckboxAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class MultilineAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class HtmlAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SkipAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class PasswordAttribute : EntryAttribute {
public PasswordAttribute (string placeholder) : base (placeholder) {}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class AlignmentAttribute : Attribute {
public AlignmentAttribute (UITextAlignment alignment) {
Alignment = alignment;
}
public UITextAlignment Alignment;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class RadioSelectionAttribute : Attribute {
public string Target;
public RadioSelectionAttribute (string target)
{
Target = target;
}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class OnTapAttribute : Attribute {
public OnTapAttribute (string method)
{
Method = method;
}
public string Method;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CaptionAttribute : Attribute {
public CaptionAttribute (string caption)
{
Caption = caption;
}
public string Caption;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SectionAttribute : Attribute {
public SectionAttribute () {}
public SectionAttribute (string caption)
{
Caption = caption;
}
public SectionAttribute (string caption, string footer)
{
Caption = caption;
Footer = footer;
}
public string Caption, Footer;
}
public class RangeAttribute : Attribute {
public RangeAttribute (float low, float high)
{
Low = low;
High = high;
}
public float Low, High;
public bool ShowCaption;
}
public class BindingContext : IDisposable {
public RootElement Root;
Dictionary<Element,MemberAndInstance> mappings;
class MemberAndInstance {
public MemberAndInstance (MemberInfo mi, object o)
{
Member = mi;
Obj = o;
}
public MemberInfo Member;
public object Obj;
}
static object GetValue (MemberInfo mi, object o)
{
var fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (o);
var pi = mi as PropertyInfo;
var getMethod = pi.GetGetMethod ();
return getMethod.Invoke (o, new object [0]);
}
static void SetValue (MemberInfo mi, object o, object val)
{
var fi = mi as FieldInfo;
if (fi != null){
fi.SetValue (o, val);
return;
}
var pi = mi as PropertyInfo;
var setMethod = pi.GetSetMethod ();
setMethod.Invoke (o, new object [] { val });
}
static string MakeCaption (string name)
{
var sb = new StringBuilder (name.Length);
bool nextUp = true;
foreach (char c in name){
if (nextUp){
sb.Append (Char.ToUpper (c));
nextUp = false;
} else {
if (c == '_'){
sb.Append (' ');
continue;
}
if (Char.IsUpper (c))
sb.Append (' ');
sb.Append (c);
}
}
return sb.ToString ();
}
// Returns the type for fields and properties and null for everything else
static Type GetTypeForMember (MemberInfo mi)
{
if (mi is FieldInfo)
return ((FieldInfo) mi).FieldType;
else if (mi is PropertyInfo)
return ((PropertyInfo) mi).PropertyType;
return null;
}
public BindingContext (object callbacks, object o, string title)
{
if (o == null)
throw new ArgumentNullException ("o");
mappings = new Dictionary<Element,MemberAndInstance> ();
Root = new RootElement (title);
Populate (callbacks, o, Root);
}
void Populate (object callbacks, object o, RootElement root)
{
MemberInfo last_radio_index = null;
var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
Section section = null;
foreach (var mi in members){
Type mType = GetTypeForMember (mi);
if (mType == null)
continue;
string caption = null;
object [] attrs = mi.GetCustomAttributes (false);
bool skip = false;
foreach (var attr in attrs){
if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute)
skip = true;
else if (attr is CaptionAttribute)
caption = ((CaptionAttribute) attr).Caption;
else if (attr is SectionAttribute){
if (section != null)
root.Add (section);
var sa = attr as SectionAttribute;
section = new Section (sa.Caption, sa.Footer);
}
}
if (skip)
continue;
if (caption == null)
caption = MakeCaption (mi.Name);
if (section == null)
section = new Section ();
Element element = null;
if (mType == typeof (string)){
PasswordAttribute pa = null;
AlignmentAttribute align = null;
EntryAttribute ea = null;
object html = null;
Action invoke = null;
bool multi = false;
foreach (object attr in attrs){
if (attr is PasswordAttribute)
pa = attr as PasswordAttribute;
else if (attr is EntryAttribute)
ea = attr as EntryAttribute;
else if (attr is MultilineAttribute)
multi = true;
else if (attr is HtmlAttribute)
html = attr;
else if (attr is AlignmentAttribute)
align = attr as AlignmentAttribute;
if (attr is OnTapAttribute){
string mname = ((OnTapAttribute) attr).Method;
if (callbacks == null){
throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor");
}
var method = callbacks.GetType ().GetMethod (mname);
if (method == null)
throw new Exception ("Did not find method " + mname);
invoke = delegate {
method.Invoke (method.IsStatic ? null : callbacks, new object [0]);
};
}
}
string value = (string) GetValue (mi, o);
if (pa != null)
element = new EntryElement (caption, pa.Placeholder, value, true);
else if (ea != null)
element = new EntryElement (caption, ea.Placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode };
else if (multi)
element = new MultilineElement (caption, value);
else if (html != null)
element = new HtmlElement (caption, value);
else {
var selement = new StringElement (caption, value);
element = selement;
if (align != null)
selement.Alignment = align.Alignment;
}
if (invoke != null)
((StringElement) element).Tapped += invoke;
} else if (mType == typeof (float)){
var floatElement = new FloatElement (null, null, (float) GetValue (mi, o));
floatElement.Caption = caption;
element = floatElement;
foreach (object attr in attrs){
if (attr is RangeAttribute){
var ra = attr as RangeAttribute;
floatElement.MinValue = ra.Low;
floatElement.MaxValue = ra.High;
floatElement.ShowCaption = ra.ShowCaption;
}
}
} else if (mType == typeof (bool)){
bool checkbox = false;
foreach (object attr in attrs){
if (attr is CheckboxAttribute)
checkbox = true;
}
if (checkbox)
element = new CheckboxElement (caption, (bool) GetValue (mi, o));
else
element = new BooleanElement (caption, (bool) GetValue (mi, o));
} else if (mType == typeof (DateTime)){
var dateTime = (DateTime) GetValue (mi, o);
bool asDate = false, asTime = false;
foreach (object attr in attrs){
if (attr is DateAttribute)
asDate = true;
else if (attr is TimeAttribute)
asTime = true;
}
if (asDate)
element = new DateElement (caption, dateTime);
else if (asTime)
element = new TimeElement (caption, dateTime);
else
element = new DateTimeElement (caption, dateTime);
} else if (mType.IsEnum){
var csection = new Section ();
ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null);
int idx = 0;
int selected = 0;
foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)){
ulong v = Convert.ToUInt64 (GetValue (fi, null));
if (v == evalue)
selected = idx;
CaptionAttribute ca = Attribute.GetCustomAttribute(fi, typeof(CaptionAttribute)) as CaptionAttribute;
csection.Add (new RadioElement (ca != null ? ca.Caption : MakeCaption (fi.Name)));
idx++;
}
element = new RootElement (caption, new RadioGroup (null, selected)) { csection };
} else if (mType == typeof (UIImage)){
element = new ImageElement ((UIImage) GetValue (mi, o));
} else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)){
var csection = new Section ();
int count = 0;
if (last_radio_index == null)
throw new Exception ("IEnumerable found, but no previous int found");
foreach (var e in (IEnumerable) GetValue (mi, o)){
csection.Add (new RadioElement (e.ToString ()));
count++;
}
int selected = (int) GetValue (last_radio_index, o);
if (selected >= count || selected < 0)
selected = 0;
element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection };
last_radio_index = null;
} else if (typeof (int) == mType){
foreach (object attr in attrs){
if (attr is RadioSelectionAttribute){
last_radio_index = mi;
break;
}
}
} else {
var nested = GetValue (mi, o);
if (nested != null){
var newRoot = new RootElement (caption);
Populate (callbacks, nested, newRoot);
element = newRoot;
}
}
if (element == null)
continue;
section.Add (element);
mappings [element] = new MemberAndInstance (mi, o);
}
root.Add (section);
}
class MemberRadioGroup : RadioGroup {
public MemberInfo mi;
public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected)
{
this.mi = mi;
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing){
foreach (var element in mappings.Keys){
element.Dispose ();
}
mappings = null;
}
}
public void Fetch ()
{
foreach (var dk in mappings){
Element element = dk.Key;
MemberInfo mi = dk.Value.Member;
object obj = dk.Value.Obj;
if (element is DateTimeElement)
SetValue (mi, obj, ((DateTimeElement) element).DateValue);
else if (element is FloatElement)
SetValue (mi, obj, ((FloatElement) element).Value);
else if (element is BooleanElement)
SetValue (mi, obj, ((BooleanElement) element).Value);
else if (element is CheckboxElement)
SetValue (mi, obj, ((CheckboxElement) element).Value);
else if (element is EntryElement){
var entry = (EntryElement) element;
entry.FetchValue ();
SetValue (mi, obj, entry.Value);
} else if (element is ImageElement)
SetValue (mi, obj, ((ImageElement) element).Value);
else if (element is RootElement){
var re = element as RootElement;
if (re.group as MemberRadioGroup != null){
var group = re.group as MemberRadioGroup;
SetValue (group.mi, obj, re.RadioSelected);
} else if (re.group as RadioGroup != null){
var mType = GetTypeForMember (mi);
var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected];
SetValue (mi, obj, fi.GetValue (null));
}
}
}
}
}
}
| |
namespace Microsoft.WindowsAzure.Management.HDInsight.Framework.Rest
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
/// <summary>
/// A class to validate the interface for which a proxy would be generated for.
/// </summary>
internal static class HttpRestInterfaceValidator
{
/// <summary>
/// Writes the error message to list.
/// </summary>
/// <param name="isNotError">If set to <c>true</c> [is not error].</param>
/// <param name="errorCode">The error code.</param>
/// <param name="errorMessage">The error message.</param>
/// <param name="messages">The messages.</param>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <exception cref="Microsoft.WindowsAzure.Management.HDInsight.Framework.Rest.HttpRestInterfaceValidationException">When throwOnError is true and isNotError is false.</exception>
private static void WriteErrorMessageToList(bool isNotError, HttpRestInterfaceValidationErrorCode errorCode, string errorMessage, List<string> messages, bool throwOnError)
{
if (!isNotError)
{
messages.Add(errorMessage);
}
if (throwOnError && !isNotError)
{
throw new HttpRestInterfaceValidationException(errorCode, errorMessage);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "Not localized", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "Not localized", MessageId = "System.String.Format(System.String,System.Object,System.Object)")]
private static bool ValidateUriTemplate(UriTemplate template, string httpMethod, MethodInfo interfaceMethod, List<string> validationErrorMessages, bool throwOnError)
{
IEnumerable<string> variableNames = template.PathSegmentVariableNames.Concat(template.QueryValueVariableNames);
ParameterInfo[] parameters = interfaceMethod.GetParameters();
bool retVal = true;
foreach (string variableName in variableNames)
{
//Case insensitive comparison because this could be used within VB, and in VB the parameters have an option to case insensitive
var parameter =
parameters.SingleOrDefault(
param => param.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase));
bool variableIsBound = parameter != null;
WriteErrorMessageToList(variableIsBound, HttpRestInterfaceValidationErrorCode.MethodHasAnUnboundUriParameterInTemplate, string.Format("The operation '{0}' has a uri template variable '{1}' that does not have a matching variable name", interfaceMethod.Name, variableName), validationErrorMessages, throwOnError);
retVal &= variableIsBound;
if (parameter != null)
{
bool uriBindingParameterIsStringType = parameter.ParameterType == typeof(string);
WriteErrorMessageToList(
uriBindingParameterIsStringType,
HttpRestInterfaceValidationErrorCode
.RestInvokeAttributeHasANonStringParamUsedForUriBinding,
string.Format("The operation '{0}' has a uri template variable '{1}' that is not string type used for binding uri template variable names. You can only use string types in query strings or Uri fragments", interfaceMethod.Name, variableName), validationErrorMessages, throwOnError);
retVal &= uriBindingParameterIsStringType;
}
}
int numUnboundParametersAllowed = httpMethod == "GET" ? 0 : 1;
var unboundParameters =
interfaceMethod.GetParameters()
.Where(
param =>
!variableNames.Any(
v => v.Equals(param.Name, StringComparison.OrdinalIgnoreCase)))
.Where(v => v.ParameterType != typeof(CancellationToken)).ToList();
bool atmostonerequestparambound = unboundParameters.Count() <= numUnboundParametersAllowed;
WriteErrorMessageToList(atmostonerequestparambound,
HttpRestInterfaceValidationErrorCode
.MethodHasUnboundParameters,
string.Format(
"The operation '{0}' has uri template variables '{1}' can have at most 1 variable that is not bound to the Uri and isn't a cancellation token",
interfaceMethod.Name, string.Join(",", unboundParameters.Select(p => p.Name))),
validationErrorMessages,
throwOnError);
retVal &= atmostonerequestparambound;
bool hasLessThanEqual1CancellationToken = interfaceMethod.GetParameters().Count(p => p.ParameterType == typeof(CancellationToken)) <= 1;
WriteErrorMessageToList(hasLessThanEqual1CancellationToken,
HttpRestInterfaceValidationErrorCode.MethodHasMoreThanOneCancellationToken,
string.Format("The method '{0}' has more than one cancellation token specified in its parameter list", interfaceMethod.Name),
validationErrorMessages, throwOnError);
retVal &= hasLessThanEqual1CancellationToken;
return retVal;
}
/// <summary>
/// Validates the interface method.
/// </summary>
/// <param name="methodInfo">The method info.</param>
/// <param name="validationErrorMessages">The validation error messages.</param>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <returns>True if the method is valid.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "Not localized", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Validated by method", MessageId = "0"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "Test code", MessageId = "2#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "Test code", MessageId = "1#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Avoids repetition")]
public static bool ValidateInterfaceMethod(MethodInfo methodInfo, out List<string> validationErrorMessages, bool throwOnError = false)
{
bool retVal = true;
validationErrorMessages = new List<string>();
bool isNotGeneric = !methodInfo.GetGenericArguments().Any();
retVal &= isNotGeneric;
string methodName = methodInfo.Name;
WriteErrorMessageToList(isNotGeneric, HttpRestInterfaceValidationErrorCode.MethodContainsGenericTypeArguments, string.Format("The method '{0}' contains generic type arguments. This is not allowed!", methodInfo.Name), validationErrorMessages, throwOnError);
bool hasExactlyOneRestInvokeAttribute = methodInfo.GetCustomAttributes<HttpRestInvoke>(true).Count() == 1;
WriteErrorMessageToList(hasExactlyOneRestInvokeAttribute, HttpRestInterfaceValidationErrorCode.MethodDoesNotHaveARestInvokeAttribute, string.Format("The method '{0}' has no HttpRestInvoke attribute applied to it!", methodName), validationErrorMessages, throwOnError);
retVal &= hasExactlyOneRestInvokeAttribute;
if (retVal)
{
var httpRestInvoke = methodInfo.GetCustomAttribute<HttpRestInvoke>();
bool httpMethodIsNotNull = !String.IsNullOrEmpty(httpRestInvoke.HttpMethod);
WriteErrorMessageToList(httpMethodIsNotNull, HttpRestInterfaceValidationErrorCode.RestInvokeAttributeHasANullOrEmptyForHttpMethod, string.Format("HttpMethod argument on HttpRestInvokeAttribute on method '{0}' is null or empty . This is not allowed!", methodInfo.Name), validationErrorMessages, throwOnError);
retVal &= httpMethodIsNotNull;
if (httpMethodIsNotNull)
{
bool hasValidUritemplate = httpRestInvoke.UriTemplate != null &&
ValidateUriTemplate(new UriTemplate(httpRestInvoke.UriTemplate), httpRestInvoke.HttpMethod,
methodInfo, validationErrorMessages, throwOnError);
retVal &= hasValidUritemplate;
}
}
bool hasRequestSerializer = methodInfo.GetCustomAttributes(false).OfType<IRequestFormatter>().Any() ||
methodInfo.DeclaringType.GetCustomAttributes(false)
.OfType<IRequestFormatter>()
.Any();
bool hasResponseSerializer = methodInfo.GetCustomAttributes(false).OfType<IResponseFormatter>().Any() ||
methodInfo.DeclaringType.GetCustomAttributes(false)
.OfType<IResponseFormatter>()
.Any();
bool hasAtMost1RequestFormatterAtMethodLevel = methodInfo.GetCustomAttributes(false).OfType<IRequestFormatter>()
.Count() <= 1;
bool hasExactlyOneResponseFormatter = methodInfo.GetCustomAttributes(false).OfType<IResponseFormatter>()
.Count() <= 1;
WriteErrorMessageToList(hasRequestSerializer, HttpRestInterfaceValidationErrorCode.MethodHasNoRequestFormatter, string.Format("The method '{0}' does not have a request formatter attached to it. Either declare one globally at the interface level or for this method!", methodName), validationErrorMessages, throwOnError);
retVal &= hasRequestSerializer;
WriteErrorMessageToList(hasResponseSerializer, HttpRestInterfaceValidationErrorCode.MethodHasNoResponseFormatter, string.Format("The method '{0}' does not have a request formatter attached to it. Either declare one globally at the interface level or for this method!", methodName), validationErrorMessages, throwOnError);
retVal &= hasResponseSerializer;
WriteErrorMessageToList(hasAtMost1RequestFormatterAtMethodLevel, HttpRestInterfaceValidationErrorCode.MethodHasMoreThaneOneRequestFormatter, string.Format("The method '{0}' has more than one IRequestFormatter attached to it", methodName), validationErrorMessages, throwOnError);
retVal &= hasAtMost1RequestFormatterAtMethodLevel;
WriteErrorMessageToList(hasExactlyOneResponseFormatter, HttpRestInterfaceValidationErrorCode.MethodHasMoreThanOneResponseFormatter, string.Format("The method '{0}' has more than one IResponseFormatter attached to it", methodName), validationErrorMessages, throwOnError);
retVal &= hasExactlyOneResponseFormatter;
foreach (var parameterInfo in methodInfo.GetParameters())
{
retVal &= ValidateParameter(methodInfo, parameterInfo, validationErrorMessages, throwOnError);
}
return retVal;
}
/// <summary>
/// Returns true if the Interface method is proxy genration compliant.
/// </summary>
/// <param name="methodInfo">The method info.</param>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <returns>True if the interface method is valid.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Avoids too much repetition")]
public static bool ValidateInterfaceMethod(MethodInfo methodInfo, bool throwOnError = false)
{
List<string> errorMessages;
return ValidateInterfaceMethod(methodInfo, out errorMessages, throwOnError);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "Avoids too much repetition", MessageId = "System.String.Format(System.String,System.Object,System.Object)")]
private static bool ValidateParameter(MethodInfo methodInfo, ParameterInfo parameterInfo, List<string> validationErrorMessages, bool throwOnError = false)
{
bool retVal = true;
bool notOptional = !parameterInfo.IsOptional;
retVal &= notOptional;
WriteErrorMessageToList(notOptional, HttpRestInterfaceValidationErrorCode.MethodContainsOptParameter, string.Format("The method '{0}' contains an optional parameter '{1}' . This is not allowed!", methodInfo.Name, parameterInfo.Name), validationErrorMessages, throwOnError);
bool notOut = !parameterInfo.IsOut;
retVal &= notOut;
WriteErrorMessageToList(notOut, HttpRestInterfaceValidationErrorCode.MethodContainsOutParameter, string.Format("The method '{0}' contains an out parameter '{1}' . This is not allowed!", methodInfo.Name, parameterInfo.Name), validationErrorMessages, throwOnError);
bool notRef = !parameterInfo.ParameterType.IsByRef;
WriteErrorMessageToList(notRef, HttpRestInterfaceValidationErrorCode.MethodContainsRefParameter, string.Format("The method '{0}' contains a ref parameter '{1}' . This is not allowed!", methodInfo.Name, parameterInfo.Name), validationErrorMessages, throwOnError);
retVal &= notRef;
return retVal;
}
/// <summary>
/// Validates the interface to be conformant to automatic proxy generation.
/// </summary>
/// <typeparam name="T">An interface type.</typeparam>
/// <param name="validationErrors">The validation errors.</param>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <returns>A boolean indicating whether the interface is valid.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "Avoids too much repetition of code.", MessageId = "0#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Test code", MessageId = "2#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "HttpVerb")]
public static bool ValidateInterface<T>(out List<string> validationErrors, bool throwOnError = false)
{
return ValidateInterface(typeof(T), out validationErrors, throwOnError);
}
/// <summary>
/// Validates the interface to be conformant to automatic proxy generation.
/// </summary>
/// <param name="interfaceType">Type of the interface.</param>
/// <param name="validationErrors">The validation errors.</param>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <returns>Returns true if the interface is valid.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "Correct", MessageId = "System.String.Format(System.String,System.Object,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)", Justification = "correct")]
public static bool ValidateInterface(Type interfaceType, out List<string> validationErrors, bool throwOnError = false)
{
Contract.Requires<ArgumentNullException>(interfaceType != null);
bool retVal = true;
validationErrors = new List<string>();
string typeName = interfaceType.Name;
bool isInterface = interfaceType.IsInterface;
retVal &= isInterface;
WriteErrorMessageToList(isInterface, HttpRestInterfaceValidationErrorCode.IsNotInterfaceType, string.Format("The type '{0}' is not an interface", typeName), validationErrors, throwOnError);
bool hasHttpDefinitionAttribute = interfaceType.GetCustomAttributes(typeof(HttpRestDefinitionAttribute), false).Any();
WriteErrorMessageToList(hasHttpDefinitionAttribute, HttpRestInterfaceValidationErrorCode.InterfaceDoesNotHaveRestDefinitionAttribute, string.Format("The interface '{0}' does not have an HttpRestDefinitionAttribute attribute applied to it", typeName), validationErrors, throwOnError);
retVal &= hasHttpDefinitionAttribute;
bool doesNotInheritsFromOthers = !(interfaceType.GetInterfaces().Any() || interfaceType.BaseType != null);
WriteErrorMessageToList(doesNotInheritsFromOthers, HttpRestInterfaceValidationErrorCode.InterfaceInheritsFromOthers, String.Format("The type '{0}' inherits from other types. This not allowed", typeName), validationErrors, throwOnError);
retVal &= doesNotInheritsFromOthers;
bool doesNotContainProperties = !interfaceType.GetProperties().Any();
WriteErrorMessageToList(doesNotContainProperties, HttpRestInterfaceValidationErrorCode.InterfaceContainsPropertyDefinitions, String.Format("The type '{0}' contains property definitions. This not allowed", typeName), validationErrors, throwOnError);
retVal &= doesNotContainProperties;
HashSet<string> methodNamesSoFar = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var method in interfaceType.GetMethods().Where(meth => !meth.IsSpecialName))
{
bool interfaceDoesNotContainOverloadsForTheSameMethod = methodNamesSoFar.Add(method.Name);
WriteErrorMessageToList(interfaceDoesNotContainOverloadsForTheSameMethod, HttpRestInterfaceValidationErrorCode.InterfaceContainersOverloads,
string.Format("The interface '{0}' contains at least one overload for the following method '{1}'. This is not permitted", interfaceType.Name, method.Name), validationErrors, throwOnError);
retVal &= interfaceDoesNotContainOverloadsForTheSameMethod;
List<string> methodValidationErrors = new List<string>();
retVal &= ValidateInterfaceMethod(method, out methodValidationErrors, throwOnError);
validationErrors.AddRange(methodValidationErrors);
}
return retVal;
}
/// <summary>
/// Validates the interface.
/// </summary>
/// <typeparam name="T">Interface type.</typeparam>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <returns>True if the interface is valid.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Avoids repetition")]
public static bool ValidateInterface<T>(bool throwOnError = false)
{
List<string> errors = new List<string>();
return ValidateInterface<T>(out errors, throwOnError);
}
/// <summary>
/// Validates the interface.
/// </summary>
/// <param name="interfaceType">Type of the interface.</param>
/// <param name="throwOnError">If set to <c>true</c> [throw on error].</param>
/// <returns>Bool indicating whether the validation succeeded.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Design choice")]
public static bool ValidateInterface(Type interfaceType, bool throwOnError = false)
{
List<string> validationErrors = new List<string>();
return ValidateInterface(interfaceType, out validationErrors, throwOnError);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Text;
namespace Microsoft.Zelig.Test
{
public class Read : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// TODO: Add your set up steps here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
//result |= Assert.CheckFailed( InvalidCases( ) );
result |= Assert.CheckFailed( VanillaRead( ) );
return result;
}
#region Local Helper methods
private bool TestRead(MemoryStream ms, int length)
{
return TestRead(ms, length, length, length);
}
private bool TestRead(MemoryStream ms, int BufferLength, int BytesToRead, int BytesExpected)
{
bool result = true;
int nextbyte = (int)ms.Position % 256;
byte[] byteBuffer = new byte[BufferLength];
int bytesRead = ms.Read(byteBuffer, 0, BytesToRead);
if (bytesRead != BytesExpected)
{
result = false;
Log.Exception("Expected " + BytesToRead + " bytes, but got " + bytesRead + " bytes");
}
for (int i = 0; i < bytesRead; i++)
{
if (byteBuffer[i] != nextbyte)
{
result = false;
Log.Exception("Byte in position " + i + " has wrong value: " + byteBuffer[i]);
}
// Reset if wraps past 255
if (++nextbyte > 255)
nextbyte = 0;
}
return result;
}
#endregion Local Helper methods
#region Test Cases
[TestMethod]
public TestResult InvalidCases()
{
TestResult result = TestResult.Pass;
try
{
using (MemoryStream ms = new MemoryStream())
{
Log.Comment("null Buffer");
try
{
int read = ms.Read(null, 0, 0);
result = TestResult.Fail;
Log.Exception("Expected ArgumentNullException, but read " + read + " bytes");
}
catch (ArgumentNullException) { /* pass case */ }
Log.Comment("negative offset");
try
{
int read = ms.Read(new byte[]{1}, -1, 0);
result = TestResult.Fail;
Log.Exception("Expected ArgumentOutOfRangeException, but read " + read + " bytes");
}
catch (ArgumentOutOfRangeException) { /* pass case */ }
Log.Comment("negative count");
try
{
int read = ms.Read(new byte[] { 1 }, 0, -1);
result = TestResult.Fail;
Log.Exception("Expected ArgumentOutOfRangeException, but read " + read + " bytes");
}
catch (ArgumentOutOfRangeException) { /* pass case */ }
Log.Comment("offset exceeds buffer size");
try
{
int read = ms.Read(new byte[] { 1 }, 2, 0);
result = TestResult.Fail;
Log.Exception("Expected ArgumentException, but read " + read + " bytes");
}
catch (ArgumentException) { /* pass case */ }
Log.Comment("count exceeds buffer size");
try
{
int read = ms.Read(new byte[] { 1 }, 0, 2);
result = TestResult.Fail;
Log.Exception("Expected ArgumentException, but read " + read + " bytes");
}
catch (ArgumentException) { /* pass case */ }
}
MemoryStream ms2 = new MemoryStream();
MemoryStreamHelper.Write(ms2, 100);
ms2.Seek(0, SeekOrigin.Begin);
ms2.Close();
Log.Comment("Read from closed stream");
try
{
int readBytes = ms2.Read(new byte[] { 50 }, 0, 50);
result = TestResult.Fail;
Log.Exception("Expected ObjectDisposedException, but read " + readBytes + " bytes");
}
catch (ObjectDisposedException) { /* pass case */ }
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = TestResult.Fail;
}
return result;
}
[TestMethod]
public TestResult VanillaRead()
{
TestResult result = TestResult.Pass;
try
{
using (MemoryStream ms = new MemoryStream())
{
// Write to stream then reset to beginning
MemoryStreamHelper.Write(ms, 1000);
ms.Seek(0, SeekOrigin.Begin);
Log.Comment("Read 256 bytes of data");
if (!TestRead(ms, 256))
result = TestResult.Fail;
Log.Comment("Request less bytes then buffer");
if (!TestRead(ms, 256, 100, 100))
result = TestResult.Fail;
// 1000 - 256 - 100 = 644
Log.Comment("Request more bytes then file");
if (!TestRead(ms, 1000, 1000, 644))
result = TestResult.Fail;
Log.Comment("Request bytes after EOF");
if (!TestRead(ms, 100, 100, 0))
result = TestResult.Fail;
Log.Comment("Rewind and read entire file in one buffer larger then file");
ms.Seek(0, SeekOrigin.Begin);
if (!TestRead(ms, 1001, 1001, 1000))
result = TestResult.Fail;
Log.Comment("Rewind and read from middle");
ms.Position = 500;
if (!TestRead(ms, 256))
result = TestResult.Fail;
Log.Comment("Read position after EOS");
ms.Position = ms.Length + 10;
if (!TestRead(ms, 100, 100, 0))
result = TestResult.Fail;
Log.Comment("Verify Read validation with UTF8 string");
ms.SetLength(0);
string test = "MFFramework Test";
ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] readbuff = new byte[20];
int read = ms.Read(readbuff, 0, readbuff.Length);
string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, read));
if (test != testResult)
{
result = TestResult.Fail;
Log.Comment("Expected: " + test + ", but got: " + testResult);
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception", ex);
result = TestResult.Fail;
}
return result;
}
#endregion Test Cases
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dialogflow.V2.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedConversationProfilesClientTest
{
[xunit::FactAttribute]
public void GetConversationProfileRequestObject()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationProfileRequest request = new GetConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.GetConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.GetConversationProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConversationProfileRequestObjectAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationProfileRequest request = new GetConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.GetConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.GetConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.GetConversationProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConversationProfile()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationProfileRequest request = new GetConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.GetConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.GetConversationProfile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConversationProfileAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationProfileRequest request = new GetConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.GetConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.GetConversationProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.GetConversationProfileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConversationProfileResourceNames()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationProfileRequest request = new GetConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.GetConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.GetConversationProfile(request.ConversationProfileName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConversationProfileResourceNamesAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConversationProfileRequest request = new GetConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.GetConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.GetConversationProfileAsync(request.ConversationProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.GetConversationProfileAsync(request.ConversationProfileName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConversationProfileRequestObject()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.CreateConversationProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationProfileRequestObjectAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConversationProfile()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.CreateConversationProfile(request.Parent, request.ConversationProfile);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationProfileAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request.Parent, request.ConversationProfile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request.Parent, request.ConversationProfile, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConversationProfileResourceNames1()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.CreateConversationProfile(request.ParentAsProjectName, request.ConversationProfile);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationProfileResourceNames1Async()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request.ParentAsProjectName, request.ConversationProfile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request.ParentAsProjectName, request.ConversationProfile, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConversationProfileResourceNames2()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.CreateConversationProfile(request.ParentAsLocationName, request.ConversationProfile);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConversationProfileResourceNames2Async()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateConversationProfileRequest request = new CreateConversationProfileRequest
{
ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
ConversationProfile = new ConversationProfile(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request.ParentAsLocationName, request.ConversationProfile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request.ParentAsLocationName, request.ConversationProfile, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConversationProfileRequestObject()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationProfileRequest request = new UpdateConversationProfileRequest
{
ConversationProfile = new ConversationProfile(),
UpdateMask = new wkt::FieldMask(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.UpdateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.UpdateConversationProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConversationProfileRequestObjectAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationProfileRequest request = new UpdateConversationProfileRequest
{
ConversationProfile = new ConversationProfile(),
UpdateMask = new wkt::FieldMask(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.UpdateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.UpdateConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.UpdateConversationProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConversationProfile()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationProfileRequest request = new UpdateConversationProfileRequest
{
ConversationProfile = new ConversationProfile(),
UpdateMask = new wkt::FieldMask(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.UpdateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile response = client.UpdateConversationProfile(request.ConversationProfile, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConversationProfileAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateConversationProfileRequest request = new UpdateConversationProfileRequest
{
ConversationProfile = new ConversationProfile(),
UpdateMask = new wkt::FieldMask(),
};
ConversationProfile expectedResponse = new ConversationProfile
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
DisplayName = "display_name137f65c2",
AutomatedAgentConfig = new AutomatedAgentConfig(),
HumanAgentAssistantConfig = new HumanAgentAssistantConfig(),
HumanAgentHandoffConfig = new HumanAgentHandoffConfig(),
NotificationConfig = new NotificationConfig(),
LoggingConfig = new LoggingConfig(),
NewMessageEventNotificationConfig = new NotificationConfig(),
SttConfig = new SpeechToTextConfig(),
LanguageCode = "language_code2f6c7160",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"),
TimeZone = "time_zone73f23b20",
};
mockGrpcClient.Setup(x => x.UpdateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
ConversationProfile responseCallSettings = await client.UpdateConversationProfileAsync(request.ConversationProfile, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConversationProfile responseCancellationToken = await client.UpdateConversationProfileAsync(request.ConversationProfile, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConversationProfileRequestObject()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationProfileRequest request = new DeleteConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
client.DeleteConversationProfile(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConversationProfileRequestObjectAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationProfileRequest request = new DeleteConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
await client.DeleteConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConversationProfileAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConversationProfile()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationProfileRequest request = new DeleteConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
client.DeleteConversationProfile(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConversationProfileAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationProfileRequest request = new DeleteConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
await client.DeleteConversationProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConversationProfileAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConversationProfileResourceNames()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationProfileRequest request = new DeleteConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
client.DeleteConversationProfile(request.ConversationProfileName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConversationProfileResourceNamesAsync()
{
moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteConversationProfileRequest request = new DeleteConversationProfileRequest
{
ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null);
await client.DeleteConversationProfileAsync(request.ConversationProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConversationProfileAsync(request.ConversationProfileName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Author: Ghalib Ghniem ghalib@ItInfoPlus.com
// Created: 2015-03-22
// Last Modified: 2015-03-31
//
using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web;
using System.Reflection;
using System.ComponentModel;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Business;
using mojoPortal.Business.Commerce;
using mojoPortal.Business.WebHelpers;
using iQuran.Business;
using mojoPortal.Net;
using log4net;
using Resources;
namespace iQuran.Web.Helper
{
public static class iQuranHelper
{
private static readonly ILog log = LogManager.GetLogger(typeof(iQuranHelper));
// using mojoPortal.Web.Framework; ConfigHelper.GetStringProperty("iQuranAdvancedRoles", string.Empty);
#region PATH FINDER
//D:\inetpub\RFPUHS\RFP\Web\Data\Sites\1\UHSRFP\ProposalFiles\RFP32\Proposal51\Addendum3\Attachments
//D:\inetpub\RFPUHS\RFP\Web\Data\Sites\1\UHSRFP\ProposalFiles\RFP32\Proposal50\Addendum2\DeliverableSamples
//public static string GetProposalVirtualFolders(int siteId, int rfpID, int proposalID, int addendumSerial)
//{
// string requestedFolder = string.Empty;
// requestedFolder = SiteUtils.GetNavigationSiteRoot() + "/Data/Sites/" + siteId + "/UHSRFP/ProposalFiles/RFP" + rfpID + "/Proposal" + proposalID + "/Addendum" + addendumSerial + "/";
// return requestedFolder;
//}
public static string GetAppPath()
{
return HttpContext.Current.Request.PhysicalApplicationPath;
}
public static string SitesFolderPath()
{
return HttpContext.Current.Request.PhysicalApplicationPath + "Data\\Sites\\";
}
public static string SiteFolderPath(int siteid)
{
return HttpContext.Current.Request.PhysicalApplicationPath + "Data\\Sites\\" + siteid;
}
//public static string ProposalFolderPath(int siteid, int rfpID, int proposalID, int addendumSerial)
//{
// return HttpContext.Current.Request.PhysicalApplicationPath + "Data\\Sites\\" + siteid + "\\UHSRFP\\ProposalFiles\\RFP" + rfpID + "\\Proposal" + proposalID + "\\Addendum" + addendumSerial;
//}
#endregion
//#region RFP DIRECTORY
////CREATE
//public static string CreateRfpFolders(int siteId, int rfpID, int addendumSerial)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\RfpFiles\\" + rfpID + "\\RfpStaff" + "\\Addendum" + addendumSerial;
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
////DELETE
//public static void DeleteRfpFolderFromDisk(int siteId, int rfpID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\RfpFiles\\" + rfpID;
// if (Directory.Exists(requestedFolder))
// Directory.Delete(requestedFolder, true);
//}
//public static void DeleteRfpAddendumFolderFromDisk(int siteId, int rfpID, int addendumSerial)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\RfpFiles\\" + rfpID + "\\RfpStaff" + "\\Addendum" + addendumSerial;
// if (Directory.Exists(requestedFolder))
// Directory.Delete(requestedFolder, true);
//}
//public static void DeleteAddendumAttachmentFromDisk(int siteId, int rfpID, int addendumSerial, string fileName)
//{
// string requestedFile = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFile = path + "\\UHSRFP\\RfpFiles\\" + rfpID + "\\RfpStaff" + "\\Addendum" + addendumSerial + "\\" + fileName;
// if (File.Exists(requestedFile))
// File.Delete(requestedFile);
//}
////GET
//public static string GetRfpFolders(int siteId, int rfpID, int addendumSerial)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\RfpFiles\\" + rfpID + "\\RfpStaff" + "\\Addendum" + addendumSerial + "\\";
// return requestedFolder;
//}
//#endregion
//#region LIBRARY DIRECTORY
////CREATE
//public static string CreateDeliverableFolder(int siteId, int servSubCatID, int deliverableID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\DeliverableSamples\\" + servSubCatID + "_" + deliverableID;
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
//public static string CreateTemplateFolders(int siteId, string tmplateName)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\Templates\\" + tmplateName;
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
//public static string CreateUhsAttachmentFolders(int siteId, int uhsAttachmentCatID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\UhsAttachments\\" + uhsAttachmentCatID;
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
//public static string CreateServCatFolder(int siteId)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\ServCat";
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
////DELETE
//public static void DeleteDeliverableFolderFromDisk(int siteId, int servSubCatID, int deliverableID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\DeliverableSamples\\" + servSubCatID + "_" + deliverableID ;
// if (Directory.Exists(requestedFolder))
// Directory.Delete(requestedFolder, true);
//}
//public static void DeleteDeliverableSampleFromDisk(int siteId, int servSubCatID, int deliverableID, string fileName)
//{
// string requestedFile = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFile = path + "\\UHSRFP\\DeliverableSamples\\" + servSubCatID + "_" + deliverableID + "\\" + fileName;
// if (File.Exists(requestedFile))
// File.Delete(requestedFile);
//}
//public static void DeleteTemplateFromDisk(int siteId, string tmplateName)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\Templates\\" + tmplateName ;
// if (Directory.Exists(requestedFolder))
// Directory.Delete(requestedFolder, true);
//}
//public static void DeleteUhsAttachmentFolderFromDisk(int siteId, int uhsAttachmentCatID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\UhsAttachments\\" + uhsAttachmentCatID;
// if (Directory.Exists(requestedFolder))
// Directory.Delete(requestedFolder, true);
//}
//public static void DeleteUhsAttachmentFromDisk(int siteId, int uhsAttachmentCatID, string fileName)
//{
// string requestedFile = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFile = path + "\\UHSRFP\\UhsAttachments\\" + uhsAttachmentCatID + "\\" + fileName;
// if (File.Exists(requestedFile))
// File.Delete(requestedFile);
//}
//public static void DeleteServCatFromDisk(int siteId, string imageName)
//{
// string requestedFile = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFile = path + "\\UHSRFP\\ServCat\\" + imageName;
// if (File.Exists(requestedFile))
// File.Delete(requestedFile);
//}
////GET
//public static string GetDeliverableFolder(int siteId, int servSubCatID, int deliverableID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\DeliverableSamples\\" + servSubCatID + "_" + deliverableID + "\\";
// return requestedFolder;
//}
//public static string GetTemplateFolder(int siteId, string tmplateName)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\Templates\\" + tmplateName + "\\";
// return requestedFolder;
//}
//public static string GetUhsAttachmentFolder(int siteId, int uhsAttachmentCatID)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\UhsAttachments\\" + uhsAttachmentCatID + "\\";
// return requestedFolder;
//}
//public static string GetServCatFolder(int siteId)
//{
// string requestedFolder = string.Empty;
// string path = SiteFolderPath(siteId);
// requestedFolder = path + "\\UHSRFP\\ServCat\\" ;
// return requestedFolder;
//}
//#endregion
//#region PROPOSAL DIRECTORY
////CREATE
//public static string CreateProposalFolders(int siteId, int rfpID, int proposalID, int addendumSerial)
//{
// string requestedFolder = string.Empty;
// string proposalFolderPath = ProposalFolderPath(siteId, rfpID, proposalID, addendumSerial);
// requestedFolder = proposalFolderPath;
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// requestedFolder = proposalFolderPath + "\\Attachments";
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// requestedFolder = proposalFolderPath + "\\DeliverableSamples";
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
//public static string CreateProposalAttachmentOrSampleFolders(int siteId, int rfpID, int proposalID, int addendumSerial, int ProposalAttachmentCatID, int proposalDeliverableID, string WhichFolder)
//{
// string requestedFolder = string.Empty;
// string proposalFolderPath = ProposalFolderPath(siteId, rfpID, proposalID, addendumSerial);
// switch (WhichFolder)
// {
// case "Attachment":
// requestedFolder = proposalFolderPath + "\\Attachments\\" + ProposalAttachmentCatID + "\\";
// break;
// case "Sample":
// requestedFolder = proposalFolderPath + "\\DeliverableSamples\\" + proposalDeliverableID + "\\";
// break;
// }
// if (!Directory.Exists(requestedFolder))
// Directory.CreateDirectory(requestedFolder);
// return requestedFolder;
//}
////GET
//public static string GetProposalFolders(int siteId, int rfpID, int proposalID, int addendumSerial, int ProposalAttachmentCatID, int proposalDeliverableID, string WhichFolder)
//{
// string requestedFolder = string.Empty;
// string proposalFolderPath = ProposalFolderPath(siteId, rfpID, proposalID, addendumSerial);
// switch (WhichFolder)
// {
// case "Proposal":
// default:
// requestedFolder = proposalFolderPath + "\\";
// break;
// case "Attachment":
// if (ProposalAttachmentCatID > 0)
// requestedFolder = proposalFolderPath + "\\Attachments\\" + ProposalAttachmentCatID + "\\";
// else
// requestedFolder = proposalFolderPath + "\\Attachments\\";
// break;
// case "Sample":
// if (proposalDeliverableID > 0)
// requestedFolder = proposalFolderPath + "\\DeliverableSamples\\" + proposalDeliverableID + "\\";
// else
// requestedFolder = proposalFolderPath + "\\DeliverableSamples\\";
// break;
// }
// return requestedFolder;
//}
////DELETE FILE
//public static void DeleteProposalFile(int siteId, int rfpID, int proposalID, int addendumSerial, int ProposalAttachmentCatID, int proposalDeliverableID, string fileName, string WhichFolder)
//{
// string requestedFile = string.Empty;
// string proposalFolderPath = ProposalFolderPath(siteId, rfpID, proposalID, addendumSerial);
// switch (WhichFolder)
// {
// case "Proposal":
// default:
// requestedFile = proposalFolderPath + "\\" + fileName;
// break;
// case "Attachment":
// if (ProposalAttachmentCatID > 0)
// requestedFile = proposalFolderPath + "\\Attachments\\" + ProposalAttachmentCatID + "\\" + fileName;
// else
// requestedFile = proposalFolderPath + "\\Attachments\\" + fileName;
// break;
// case "Sample":
// if (proposalDeliverableID > 0)
// requestedFile = proposalFolderPath + "\\DeliverableSamples\\" + proposalDeliverableID + "\\" + fileName;
// else
// requestedFile = proposalFolderPath + "\\DeliverableSamples\\" + fileName;
// break;
// }
// if (File.Exists(requestedFile))
// File.Delete(requestedFile);
//}
////DELETE FOLDER
//public static void DeleteProposalFolders(int siteId, int rfpID, int proposalID, int addendumSerial, int ProposalAttachmentCatID, int proposalDeliverableID, string WhichFolder)
//{
// string requestedFolder = string.Empty;
// string proposalFolderPath = ProposalFolderPath(siteId, rfpID, proposalID, addendumSerial);
// switch (WhichFolder)
// {
// case "Proposal":
// default:
// requestedFolder = proposalFolderPath + "\\";
// break;
// case "Attachment":
// if (ProposalAttachmentCatID > 0)
// requestedFolder = proposalFolderPath + "\\Attachments\\" + ProposalAttachmentCatID + "\\";
// else
// requestedFolder = proposalFolderPath + "\\Attachments\\";
// break;
// case "Sample":
// if (proposalDeliverableID > 0)
// requestedFolder = proposalFolderPath + "\\DeliverableSamples\\" + proposalDeliverableID + "\\";
// else
// requestedFolder = proposalFolderPath + "\\DeliverableSamples\\";
// break;
// }
// if (Directory.Exists(requestedFolder))
// Directory.Delete(requestedFolder, true);
//}
//#endregion
//#region FILEWORKS
//public static void CopyFilesArrayFromSourceToTargetTemplateFiles(string[] filePaths, string target)
//{
// bool overwrite = true;
// //string mFolder = SiteFolderPath(siteId) + "\\UHSRFP\\ChartTmp\\Proposal\\" + userid + "\\" + WhichFolder + "\\";
// string trgtFile = string.Empty;
// //string[] filePaths = Directory.GetFiles(src);
// foreach (string filePath in filePaths)
// {
// trgtFile = target + filePath.Substring(filePath.LastIndexOf("\\") + 1);
// File.Copy(filePath, trgtFile, overwrite);
// }
//}
//public static void CopyFilesFromSourceToTargetTemplateFiles(string src, string oldProposal, string newProposal, string oldAddendum, string newAddendum)
//{
// bool overwrite = true;
// string trgtFolder = string.Empty; //SiteFolderPath(siteId) + "\\UHSRFP\\ChartTmp\\Proposal\\" + userid + "\\" + WhichFolder + "\\";
// string trgtFile = string.Empty;
// string[] filePaths = Directory.GetFiles(src,"*.*",SearchOption.AllDirectories);
// foreach (string filePath in filePaths)
// {
// // filePath "D:\\inetpub\\RFPUHS\\RFP\\Web\\Data\\Sites\\1\\UHSRFP\\ProposalFiles\\RFP33\\Proposal55\\Addendum2\\org3.jpg" string
// // target "D:\\inetpub\\RFPUHS\\RFP\\Web\\Data\\Sites\\1\\UHSRFP\\ProposalFiles\\RFP33\\Proposal57\\Addendum3\\" string
// trgtFile = filePath.Replace(oldProposal, newProposal).Replace(oldAddendum, newAddendum);
// trgtFolder = trgtFile.Replace(trgtFile.Substring(filePath.LastIndexOf("\\") + 1),"");
// // trgtFile = target + filePath.Substring(filePath.LastIndexOf("\\") + 1);
// if (!Directory.Exists(trgtFolder))
// Directory.CreateDirectory(trgtFolder);
// File.Copy(filePath, trgtFile, overwrite);
// }
//}
//private static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
//{
// string[] searchPatterns = searchPattern.Split('|');
// List<string> files = new List<string>();
// foreach (string sp in searchPatterns)
// files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
// files.Sort();
// return files.ToArray();
//}
//public static void DeleteAllTemplateImages(string src)
//{
// string[] filePaths = GetFiles(src, "*.jpg|*.gif|*.html|*.mht", SearchOption.TopDirectoryOnly);
// foreach (string filePath in filePaths)
// {
// if (File.Exists(filePath))
// File.Delete(filePath);
// }
//}
//public static void CopyFileFromSourceToTargetFolder(string src, string target)
//{
// bool overwrite = true;
// if (File.Exists(src))
// File.Copy(src, target, overwrite);
//}
//public static bool CheckFileExists(string target)
//{
// if (File.Exists(target))
// return true;
// else
// return false;
//}
//public static void CreateFile(string target)
//{
// if (!File.Exists(target))
// File.Create(target);
//}
//#endregion
//#region EMAIL
//public static void SendEmailNotification(string status, string mUserFullName, string mUserID, string mPageLink,
// string RFPInitiateDatetime, string RfpProjectName, string RfpClientRefference,
// string RfpRefference, string addendumSerial,
// SiteSettings siteSettings)
//{
// // status : SubmitRfp, ReviewRfp, cancelRfp, addendumRfp // SubmitProposal, ApproveProposal, PublishProposal , SendProposal , DeleteProposal
// //string loggedUser = ((mojoPortal.Business.SiteUser)(System.Web.HttpContext.Current.Items["CurrentUser"])).Name;
// CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture();
// SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();
// EmailMessageTask messageTask = new EmailMessageTask(smtpSettings);
// string subjectTemplate = string.Empty;
// string textBodyTemplate = string.Empty;
// string adminEmail = ConfigHelper.GetStringProperty("NotifyAdminEmail", string.Empty);
// string adminRfpEmail = ConfigHelper.GetStringProperty("NotifyRfpAdminEmail", string.Empty);
// switch (status)
// {
// case "SubmitRfp":
// default:
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpSubmitMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpSubmitMessage.config");
// break;
// case "ReviewRfp":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpReviewMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpReviewMessage.config");
// break;
// case "AddendumRfp":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpAddendumMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpAddendumMessage.config");
// break;
// case "CancelRfp":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpCancelMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsRfpCancelMessage.config");
// break;
// case "SubmitProposal":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalSubmitMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalSubmitMessage.config");
// break;
// case "ApproveProposal":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalApproveMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalApproveMessage.config");
// break;
// case "PublishProposal":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalPublishMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalPublishMessage.config");
// break;
// case "SendProposal":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalSendMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalSendMessage.config");
// break;
// case "DeleteProposal":
// subjectTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalDeleteMessageSubject.config");
// textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture,
// "UhsProposalDeleteMessage.config");
// break;
// }
// messageTask.EmailCc = adminRfpEmail;
// messageTask.EmailFrom = ConfigHelper.GetStringProperty("NotifyFromEmail", string.Empty);
// messageTask.EmailTo = adminEmail;
// messageTask.EmailCc = adminRfpEmail;
// messageTask.SiteGuid = siteSettings.SiteGuid;
// string SeperatorLine = ConfigHelper.GetStringProperty("SeperatorLine", string.Empty);
// string ContactUsUrl = ConfigHelper.GetStringProperty("ContactUsUrl", string.Empty);
// string PrivacyPolicyUrl = ConfigHelper.GetStringProperty("PrivacyPolicyUrl", string.Empty);
// string ServiceAgreementUrl = ConfigHelper.GetStringProperty("ServiceAgreementUrl", string.Empty);
// string UhsCompanyName = ConfigHelper.GetStringProperty("UhsCompanyName", string.Empty);
// string UhsPOBoxAddress = ConfigHelper.GetStringProperty("UhsAddress", string.Empty);
// string UhsTel = ConfigHelper.GetStringProperty("UhsTel", string.Empty);
// string UhsFax = ConfigHelper.GetStringProperty("UhsFax", string.Empty);
// string UhsMob = ConfigHelper.GetStringProperty("UhsMob", string.Empty);
// string CurrentYear = DateTime.Now.Year.ToString();
// string CurrentDatetime = String.Format(DateTime.Now.ToString(), "mm dd yyyy");
// messageTask.Subject = string.Format(
// defaultCulture,
// subjectTemplate
// );
// messageTask.TextBody = string.Format(
// defaultCulture,
// textBodyTemplate,
// mUserID,
// mUserFullName,
// mPageLink,
// RFPInitiateDatetime,
// RfpProjectName,
// RfpClientRefference,
// RfpRefference,
// SeperatorLine, CurrentDatetime, ContactUsUrl, PrivacyPolicyUrl, ServiceAgreementUrl,
// CurrentYear, UhsCompanyName,
// UhsTel, UhsFax, UhsMob, UhsPOBoxAddress,
// addendumSerial);
// messageTask.QueueTask();
// WebTaskManager.StartOrResumeTasks();
//}
//#endregion
#region "old"
//public static bool LogEvent(
// bool Log,
// bool RiskLog,
// string userActionStringResorcesName,
// string ActionDetailsStringResorcesName,
// string moreDetails,
// bool isAdmin,
// int autoMEPID,
// int siteID,
// int actionBy,
// string autoMEPName,
// string siteName,
// string actionByName
// )
//{
// //User Actions Details Description:
// //User {0} - {1} <br /> From Site - {2} - {3} <br /> Made the next Action : Send BOQ Report / {4}
// //User {actionBy:UserID} - {UserFullName} - From Site - {SiteID} - {SiteName} Made the next Action : Send BOQ Report / {The Thing that Action made on}
// //User 3 - Ghalib Ghniem From Site - 1 - www.AutoMEPs.COM Made the next Action xxxx - Item Details
// bool res = false;
// CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture();
// string Details = String.Format(defaultCulture, ActionDetailsStringResorcesName.Replace("_"," "),
// actionBy,
// actionByName,
// siteID,
// siteName,
// moreDetails
// );
// if (Log)
// {
// AutoMEPLog autoMEPLog = new AutoMEPLog();
// autoMEPLog.IsAdmin = isAdmin;
// autoMEPLog.AutoMEPID = autoMEPID;
// autoMEPLog.SiteID = siteID;
// autoMEPLog.ActionBy = actionBy;
// autoMEPLog.AutoMEPName = autoMEPName;
// autoMEPLog.SiteName = siteName;
// autoMEPLog.ActionByName = actionByName;
// autoMEPLog.UserAction = userActionStringResorcesName;
// autoMEPLog.Details = Details;
// res = autoMEPLog.Save();
// }
// if (RiskLog)
// {
// AutoMEPRiskLog autoMEPRiskLog = new AutoMEPRiskLog();
// autoMEPRiskLog.IsAdmin = isAdmin;
// autoMEPRiskLog.AutoMEPID = autoMEPID;
// autoMEPRiskLog.SiteID = siteID;
// autoMEPRiskLog.ActionBy = actionBy;
// autoMEPRiskLog.AutoMEPName = autoMEPName;
// autoMEPRiskLog.SiteName = siteName;
// autoMEPRiskLog.ActionByName = actionByName;
// autoMEPRiskLog.UserAction = userActionStringResorcesName;
// autoMEPRiskLog.Details = Details;
// res = autoMEPRiskLog.Save();
// }
// return res;
//}
///// <summary>
/////To Create Folders for each new AutoMEP System
///// </summary>
//public static void CreateAutoMepFolders(int siteId)
//{
// string requestedFolder = string.Empty;
// string path = HttpContext.Current.Request.PhysicalApplicationPath + "\\Data\\Sites\\" + siteId;
// requestedFolder = path + "\\AutoMEPData\\";
// if (!Directory.Exists(requestedFolder + "\\drawings"))
// Directory.CreateDirectory(requestedFolder + "\\drawings");
// if (!Directory.Exists(requestedFolder + "\\images\\thumb"))
// Directory.CreateDirectory(requestedFolder + "\\images\\thumb");
//}
//public static void DeleteUserFolders(int siteId, int userID)
//{
// string path = HttpContext.Current.Request.PhysicalApplicationPath + "\\Data\\Sites\\" + siteId + "\\amsuserfiles\\" + userID;
// if (!Directory.Exists(path ))
// Directory.Delete(path);
//}
///// <summary>
///// To retrive current user temp project folder to work in Or the current AutoMEP System Data Folder for a Project
///// </summary>
////public static string GetProjectFolder(string folderType, int siteId, int Idd, int projId, string moduleName)
////{
//// string requestedFolder = string.Empty;
//// string tmpStr = string.Empty;
//// if (folderType == "tmp")
//// requestedFolder = SiteUtils.GetNavigationSiteRoot() + "/Data/Sites/" + siteId + "/userfiles/" + Idd + "/" + projId;
//// else
//// tmpStr = SiteUtils.GetNavigationSiteRoot() + "/Data/Sites/" + siteId + "/AutoMEPData/" + Idd + "/" + projId;
//// switch (moduleName)
//// {
//// case "":
//// default:
//// break;
//// case "root":
//// requestedFolder = tmpStr;
//// break;
//// case "room":
//// requestedFolder = tmpStr + "/RoomsImages/";
//// break;
//// case "item":
//// requestedFolder = tmpStr + "/ItemsImages/";
//// break;
//// case "report":
//// requestedFolder = tmpStr + "/Reports/";
//// break;
//// case "cad":
//// requestedFolder = tmpStr + "/Drawings/";
//// break;
//// }
////}
//public static Room GetRoomSession(int roomid, bool GetFull)
//{
// if (HttpContext.Current == null) return null;
// if (HttpContext.Current.Items["Room"] != null)
// {
// return (Room)HttpContext.Current.Items["Room"];
// }
// Room room;
// if (roomid > 0)
// room = new Room(roomid, GetFull);
// else
// room = new Room();
// if (room.RoomID > -1)
// {
// HttpContext.Current.Items.Add("Room", room);
// return room;
// }
// return null;
//}
//public static ItemLibrary GetItemSession(bool GetFull, bool UsingCode, bool UsingAbbrev, int libraryId, int itemid)
//{
// if (HttpContext.Current == null) return null;
// if (HttpContext.Current.Items["ItemLibrary"] != null)
// {
// return (ItemLibrary)HttpContext.Current.Items["ItemLibrary"];
// }
// ItemLibrary itemlibrary;
// if (itemid > 0)
// itemlibrary = new ItemLibrary(GetFull, itemid);
// else
// itemlibrary = new ItemLibrary();
// if (itemlibrary.ItemID > -1)
// {
// HttpContext.Current.Items.Add("ItemLibrary", itemlibrary);
// return itemlibrary;
// }
// return null;
//}
////public static Library GetLibrarySession(int libraryId, bool GetFull)
////{
//// if (HttpContext.Current == null) return null;
//// if (HttpContext.Current.Items["Library"] != null)
//// {
//// return (Library)HttpContext.Current.Items["Library"];
//// }
//// Library library;
//// if (libraryId > 0)
//// library = new Library(libraryId, GetFull);
//// else
//// library = new Library();
//// if (library.LibraryID > -1)
//// {
//// HttpContext.Current.Items.Add("Library", library);
//// return library;
//// }
//// return null;
////}
//public enum amsFolder
//{
// [DescriptionAttribute("ItemsImages")]
// itemImage,
// [DescriptionAttribute("ItemsDrawings")]
// itemDrawing,
// [DescriptionAttribute("RoomsImages")]
// room,
// vanilla
//}
/// <summary>
/// To retrive current user temp folder to work in Or the current AutoMEP System Data Folder
/// </summary>
/// <param name="folderType">Either User Temp "tmp" Either AutoMEP System Data "ams" Folder</param>
/// <param name="siteId"></param>
/// <param name="Idd">When AutoMEP System Data Folder "ams" It Will be "AutoMEPID"; When User Temp "tmp" It will be "UserId" </param>
/// <returns>requestedFolder</returns>
//public static string GetFolder(string folderType, int siteId, int Idd)
//{
// string requestedFolder = string.Empty;
// string tmpStr=string.Empty;
// if (folderType=="tmp")
// requestedFolder = SiteUtils.GetNavigationSiteRoot() + "/Data/Sites/" + siteId + "/amsuserfiles/" + Idd + "/";
// else
// requestedFolder = SiteUtils.GetNavigationSiteRoot() + "/Data/Sites/" + siteId + "/AutoMEPData/" + Idd + "/";
// return requestedFolder;
//}
///// <summary>
///// To retrive Save Folder: current user temp folder to work in Or the current AutoMEP System Data Folder
///// </summary>
///// <param name="folderType">Either User Temp "tmp" Either AutoMEP System Data "ams" Folder</param>
///// <param name="moduleName">Folder Name; Used Only if requested AutoMEP System Data "ams" Folder </param>
///// <param name="siteId"></param>
///// <param name="Idd">When AutoMEP System Data Folder "ams" It Will be "AutoMEPID"; When User Temp "tmp" It will be "UserId" </param>
///// <returns>requestedFolder</returns>
//public static string GetFolderToSaveIn(string folderType, int siteId, int Idd)//, string moduleName)
//{
// string requestedFolder = string.Empty;
// string tmpStr = string.Empty;
// //Server.MapPath("\\") + "Data\\Sites\\" + autoMEP.SiteID + "\\userfiles\\" + autoMEP.UserID + "\\"
// if (folderType == "tmp")
// requestedFolder = "Data\\Sites\\" + siteId + "\\amsuserfiles\\" + Idd + "\\";
// else
// requestedFolder = "Data\\Sites\\" + siteId + "\\AutoMEPData\\" + Idd + "\\";
// return requestedFolder;
//}
///// <summary>
/////To Create Folders for each new RFP
///// </summary>
#endregion
}
public class EnumUtils
{
public static string stringValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
public static object enumValueOf(string value, Type enumType)
{
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
{
return Enum.Parse(enumType, name);
}
}
throw new ArgumentException("The string is not a description or value of the specified enum.");
}
}
}
| |
// Copyright 2013-2015 Serilog Contributors
//
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Serilog.Events;
namespace Serilog.Core.Pipeline
{
class SilentLogger : ILogger
{
public static readonly ILogger Instance = new SilentLogger();
SilentLogger()
{
}
public ILogger ForContext(ILogEventEnricher enricher) => this;
public ILogger ForContext(IEnumerable<ILogEventEnricher> enrichers) => this;
public ILogger ForContext(string propertyName, object? value, bool destructureObjects = false) => this;
public ILogger ForContext<TSource>() => this;
public ILogger ForContext(Type source) => this;
public void Write(LogEvent logEvent)
{
}
public void Write(LogEventLevel level, string messageTemplate)
{
}
public void Write<T>(LogEventLevel level, string messageTemplate, T propertyValue)
{
}
public void Write<T0, T1>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Write<T0, T1, T2>(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Write(LogEventLevel level, string messageTemplate, params object?[]? propertyValues)
{
}
public void Write(LogEventLevel level, Exception? exception, string messageTemplate)
{
}
public void Write<T>(LogEventLevel level, Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Write<T0, T1>(LogEventLevel level, Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Write<T0, T1, T2>(LogEventLevel level, Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Write(LogEventLevel level, Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
public bool IsEnabled(LogEventLevel level) => false;
public void Verbose(string messageTemplate)
{
}
public void Verbose<T>(string messageTemplate, T propertyValue)
{
}
public void Verbose<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Verbose<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Verbose(string messageTemplate, params object?[]? propertyValues)
{
}
public void Verbose(Exception? exception, string messageTemplate)
{
}
public void Verbose<T>(Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Verbose<T0, T1>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Verbose<T0, T1, T2>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Verbose(Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
public void Debug(string messageTemplate)
{
}
public void Debug<T>(string messageTemplate, T propertyValue)
{
}
public void Debug<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Debug<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Debug(string messageTemplate, params object?[]? propertyValues)
{
}
public void Debug(Exception? exception, string messageTemplate)
{
}
public void Debug<T>(Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Debug<T0, T1>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Debug<T0, T1, T2>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Debug(Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
public void Information(string messageTemplate)
{
}
public void Information<T>(string messageTemplate, T propertyValue)
{
}
public void Information<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Information<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Information(string messageTemplate, params object?[]? propertyValues)
{
}
public void Information(Exception? exception, string messageTemplate)
{
}
public void Information<T>(Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Information<T0, T1>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Information<T0, T1, T2>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Information(Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
public void Warning(string messageTemplate)
{
}
public void Warning<T>(string messageTemplate, T propertyValue)
{
}
public void Warning<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Warning<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Warning(string messageTemplate, params object?[]? propertyValues)
{
}
public void Warning(Exception? exception, string messageTemplate)
{
}
public void Warning<T>(Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Warning<T0, T1>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Warning<T0, T1, T2>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Warning(Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
public void Error(string messageTemplate)
{
}
public void Error<T>(string messageTemplate, T propertyValue)
{
}
public void Error<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Error<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Error(string messageTemplate, params object?[]? propertyValues)
{
}
public void Error(Exception? exception, string messageTemplate)
{
}
public void Error<T>(Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Error<T0, T1>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Error<T0, T1, T2>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Error(Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
public void Fatal(string messageTemplate)
{
}
public void Fatal<T>(string messageTemplate, T propertyValue)
{
}
public void Fatal<T0, T1>(string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Fatal<T0, T1, T2>(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Fatal(string messageTemplate, params object?[]? propertyValues)
{
}
public void Fatal(Exception? exception, string messageTemplate)
{
}
public void Fatal<T>(Exception? exception, string messageTemplate, T propertyValue)
{
}
public void Fatal<T0, T1>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1)
{
}
public void Fatal<T0, T1, T2>(Exception? exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2)
{
}
public void Fatal(Exception? exception, string messageTemplate, params object?[]? propertyValues)
{
}
[MessageTemplateFormatMethod("messageTemplate")]
public bool BindMessageTemplate(string messageTemplate, object?[]? propertyValues, [NotNullWhen(true)] out MessageTemplate? parsedTemplate, [NotNullWhen(true)] out IEnumerable<LogEventProperty>? boundProperties)
{
parsedTemplate = null;
boundProperties = null;
return false;
}
public bool BindProperty(string? propertyName, object? value, bool destructureObjects, [NotNullWhen(true)] out LogEventProperty? property)
{
property = null;
return false;
}
}
}
| |
//
// CalendarMonthView.cs
//
// Converted to MonoTouch on 1/22/09 - Eduardo Scoz || http://escoz.com
// Originally reated by Devin Ross on 7/28/09 - tapku.com || http://github.com/devinross/tapkulibrary
//
/*
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 MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
namespace escoz
{
public delegate void DateSelected(DateTime date);
public delegate void MonthChanged(DateTime monthSelected);
public class CalendarMonthView : UIView
{
public int BoxHeight = 30;
public int BoxWidth = 46;
int headerHeight = 0;
public Action<DateTime> OnDateSelected;
public Action<DateTime> OnFinishedDateSelection;
public Func<DateTime, bool> IsDayMarkedDelegate;
public Func<DateTime, bool> IsDateAvailable;
public Action<DateTime> MonthChanged;
public Action SwipedUp;
public DateTime CurrentSelectedDate;
public DateTime CurrentMonthYear;
protected DateTime CurrentDate { get; set; }
private UIScrollView _scrollView;
private bool calendarIsLoaded;
private MonthGridView _monthGridView;
bool _showHeader;
public CalendarMonthView(DateTime selectedDate, bool showHeader, float width = 320)
{
_showHeader = showHeader;
if (_showHeader)
headerHeight = 20;
if (_showHeader)
this.Frame = new RectangleF(0, 0, width, 218);
else
this.Frame = new RectangleF(0, 0, width, 198);
BoxWidth = Convert.ToInt32(Math.Ceiling( width / 7 ));
BackgroundColor = UIColor.White;
ClipsToBounds = true;
CurrentSelectedDate = selectedDate;
CurrentDate = DateTime.Now.Date;
CurrentMonthYear = new DateTime(CurrentSelectedDate.Year, CurrentSelectedDate.Month, 1);
var swipeLeft = new UISwipeGestureRecognizer(p_monthViewSwipedLeft);
swipeLeft.Direction = UISwipeGestureRecognizerDirection.Left;
this.AddGestureRecognizer(swipeLeft);
var swipeRight = new UISwipeGestureRecognizer(p_monthViewSwipedRight);
swipeRight.Direction = UISwipeGestureRecognizerDirection.Right;
this.AddGestureRecognizer(swipeRight);
var swipeUp = new UISwipeGestureRecognizer(p_monthViewSwipedUp);
swipeUp.Direction = UISwipeGestureRecognizerDirection.Up;
this.AddGestureRecognizer(swipeUp);
}
public void SetDate (DateTime newDate)
{
bool right = true;
CurrentSelectedDate = newDate;
var monthsDiff = (newDate.Month - CurrentMonthYear.Month) + 12 * (newDate.Year - CurrentMonthYear.Year);
if (monthsDiff != 0)
{
if (monthsDiff < 0)
{
right = false;
monthsDiff = -monthsDiff;
}
for (int i=0; i<monthsDiff; i++)
{
MoveCalendarMonths (right, true);
}
}
else
{
RebuildGrid(right, false);
}
}
void p_monthViewSwipedUp (UISwipeGestureRecognizer ges)
{
if (SwipedUp != null)
SwipedUp ();
}
void p_monthViewSwipedRight (UISwipeGestureRecognizer ges)
{
MoveCalendarMonths(false, true);
}
void p_monthViewSwipedLeft (UISwipeGestureRecognizer ges)
{
MoveCalendarMonths(true, true);
}
public override void SetNeedsDisplay ()
{
base.SetNeedsDisplay();
if (_monthGridView!=null)
_monthGridView.Update();
}
public override void LayoutSubviews ()
{
if (calendarIsLoaded) return;
_scrollView = new UIScrollView()
{
ContentSize = new SizeF(320, 260),
ScrollEnabled = false,
Frame = new RectangleF(0, 16 + headerHeight, 320, this.Frame.Height - 16),
BackgroundColor = UIColor.White
};
//_shadow = new UIImageView(UIImage.FromBundle("Images/Calendar/shadow.png"));
//LoadButtons();
LoadInitialGrids();
BackgroundColor = UIColor.Clear;
AddSubview(_scrollView);
//AddSubview(_shadow);
_scrollView.AddSubview(_monthGridView);
calendarIsLoaded = true;
}
public void DeselectDate(){
if (_monthGridView!=null)
_monthGridView.DeselectDayView();
}
/*private void LoadButtons()
{
_leftButton = UIButton.FromType(UIButtonType.Custom);
_leftButton.TouchUpInside += HandlePreviousMonthTouch;
_leftButton.SetImage(UIImage.FromBundle("Images/Calendar/leftarrow.png"), UIControlState.Normal);
AddSubview(_leftButton);
_leftButton.Frame = new RectangleF(10, 0, 44, 42);
_rightButton = UIButton.FromType(UIButtonType.Custom);
_rightButton.TouchUpInside += HandleNextMonthTouch;
_rightButton.SetImage(UIImage.FromBundle("Images/Calendar/rightarrow.png"), UIControlState.Normal);
AddSubview(_rightButton);
_rightButton.Frame = new RectangleF(320 - 56, 0, 44, 42);
}*/
private void HandlePreviousMonthTouch(object sender, EventArgs e)
{
MoveCalendarMonths(false, true);
}
private void HandleNextMonthTouch(object sender, EventArgs e)
{
MoveCalendarMonths(true, true);
}
public void MoveCalendarMonths (bool right, bool animated)
{
CurrentMonthYear = CurrentMonthYear.AddMonths(right? 1 : -1);
RebuildGrid(right, animated);
}
public void RebuildGrid(bool right, bool animated)
{
UserInteractionEnabled = false;
var gridToMove = CreateNewGrid(CurrentMonthYear);
var pointsToMove = (right? Frame.Width : -Frame.Width);
/*if (left && gridToMove.weekdayOfFirst==0)
pointsToMove += 44;
if (!left && _monthGridView.weekdayOfFirst==0)
pointsToMove -= 44;*/
gridToMove.Frame = new RectangleF(new PointF(pointsToMove, 0), gridToMove.Frame.Size);
_scrollView.AddSubview(gridToMove);
if (animated){
UIView.BeginAnimations("changeMonth");
UIView.SetAnimationDuration(0.4);
UIView.SetAnimationDelay(0.1);
UIView.SetAnimationCurve(UIViewAnimationCurve.EaseInOut);
}
_monthGridView.Center = new PointF(_monthGridView.Center.X - pointsToMove, _monthGridView.Center.Y);
gridToMove.Center = new PointF(gridToMove.Center.X - pointsToMove, gridToMove.Center.Y);
_monthGridView.Alpha = 0;
/*_scrollView.Frame = new RectangleF(
_scrollView.Frame.Location,
new SizeF(_scrollView.Frame.Width, this.Frame.Height-16));
_scrollView.ContentSize = _scrollView.Frame.Size;*/
SetNeedsDisplay();
if (animated)
UIView.CommitAnimations();
_monthGridView = gridToMove;
UserInteractionEnabled = true;
if (MonthChanged != null)
MonthChanged(CurrentMonthYear);
}
private MonthGridView CreateNewGrid(DateTime date){
var grid = new MonthGridView(this, date);
grid.CurrentDate = CurrentDate;
grid.BuildGrid();
grid.Frame = new RectangleF(0, 0, 320, this.Frame.Height-16);
return grid;
}
private void LoadInitialGrids()
{
_monthGridView = CreateNewGrid(CurrentMonthYear);
/*var rect = _scrollView.Frame;
rect.Size = new SizeF { Height = (_monthGridView.Lines + 1) * 44, Width = rect.Size.Width };
_scrollView.Frame = rect;*/
//Frame = new RectangleF(Frame.X, Frame.Y, _scrollView.Frame.Size.Width, _scrollView.Frame.Size.Height+16);
/*var imgRect = _shadow.Frame;
imgRect.Y = rect.Size.Height - 132;
_shadow.Frame = imgRect;*/
}
public override void Draw(RectangleF rect)
{
using(var context = UIGraphics.GetCurrentContext())
{
context.SetFillColor (UIColor.LightGray.CGColor);
context.FillRect (new RectangleF (0, 0, 320, 18 + headerHeight));
}
DrawDayLabels(rect);
if (_showHeader)
DrawMonthLabel(rect);
}
private void DrawMonthLabel(RectangleF rect)
{
var r = new RectangleF(new PointF(0, 2), new SizeF {Width = 320, Height = 42});
UIColor.DarkGray.SetColor();
DrawString(CurrentMonthYear.ToString("MMMM yyyy"),
r, UIFont.BoldSystemFontOfSize(16),
UILineBreakMode.WordWrap, UITextAlignment.Center);
}
private void DrawDayLabels(RectangleF rect)
{
var font = UIFont.BoldSystemFontOfSize(10);
UIColor.DarkGray.SetColor();
var context = UIGraphics.GetCurrentContext();
context.SaveState();
var i = 0;
foreach (var d in Enum.GetNames(typeof(DayOfWeek)))
{
DrawString(d.Substring(0, 3), new RectangleF(i*BoxWidth, 2 + headerHeight, BoxWidth, 10), font,
UILineBreakMode.WordWrap, UITextAlignment.Center);
i++;
}
context.RestoreState();
}
}
public class MonthGridView : UIView
{
private CalendarMonthView _calendarMonthView;
public DateTime CurrentDate {get;set;}
private DateTime _currentMonth;
protected readonly IList<CalendarDayView> _dayTiles = new List<CalendarDayView>();
public int Lines { get; set; }
protected CalendarDayView SelectedDayView {get;set;}
public int weekdayOfFirst;
public IList<DateTime> Marks { get; set; }
public MonthGridView(CalendarMonthView calendarMonthView, DateTime month)
{
_calendarMonthView = calendarMonthView;
_currentMonth = month.Date;
var tapped = new UITapGestureRecognizer(p_Tapped);
this.AddGestureRecognizer(tapped);
}
void p_Tapped(UITapGestureRecognizer tapRecg)
{
var loc = tapRecg.LocationInView(this);
if (SelectDayView(loc)&& _calendarMonthView.OnDateSelected!=null)
_calendarMonthView.OnDateSelected(new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag));
}
public void Update(){
foreach (var v in _dayTiles)
updateDayView(v);
this.SetNeedsDisplay();
}
public void updateDayView(CalendarDayView dayView){
dayView.Marked = _calendarMonthView.IsDayMarkedDelegate == null ?
false : _calendarMonthView.IsDayMarkedDelegate(dayView.Date);
dayView.Available = _calendarMonthView.IsDateAvailable == null ?
true : _calendarMonthView.IsDateAvailable(dayView.Date);
}
public void BuildGrid ()
{
DateTime previousMonth = _currentMonth.AddMonths (-1);
var daysInPreviousMonth = DateTime.DaysInMonth (previousMonth.Year, previousMonth.Month);
var daysInMonth = DateTime.DaysInMonth (_currentMonth.Year, _currentMonth.Month);
weekdayOfFirst = (int)_currentMonth.DayOfWeek;
var lead = daysInPreviousMonth - (weekdayOfFirst - 1);
int boxWidth = _calendarMonthView.BoxWidth;
int boxHeight = _calendarMonthView.BoxHeight;
// build last month's days
for (int i = 1; i <= weekdayOfFirst; i++)
{
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView (_calendarMonthView);
dayView.Frame = new RectangleF ((i - 1) * boxWidth - 1, 0, boxWidth, boxHeight);
dayView.Date = viewDay;
dayView.Text = lead.ToString ();
AddSubview (dayView);
_dayTiles.Add (dayView);
lead++;
}
var position = weekdayOfFirst + 1;
var line = 0;
// current month
for (int i = 1; i <= daysInMonth; i++)
{
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView(_calendarMonthView)
{
Frame = new RectangleF((position - 1) * boxWidth - 1, line * boxHeight, boxWidth, boxHeight),
Today = (CurrentDate.Date==viewDay.Date),
Text = i.ToString(),
Active = true,
Tag = i,
Selected = (viewDay.Date == _calendarMonthView.CurrentSelectedDate.Date)
};
dayView.Date = viewDay;
updateDayView (dayView);
if (dayView.Selected)
SelectedDayView = dayView;
AddSubview (dayView);
_dayTiles.Add (dayView);
position++;
if (position > 7)
{
position = 1;
line++;
}
}
//next month
int dayCounter = 1;
if (position != 1)
{
for (int i = position; i < 8; i++)
{
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView (_calendarMonthView)
{
Frame = new RectangleF((i - 1) * boxWidth -1, line * boxHeight, boxWidth, boxHeight),
Text = dayCounter.ToString(),
};
dayView.Date = viewDay;
updateDayView (dayView);
AddSubview (dayView);
_dayTiles.Add (dayView);
dayCounter++;
}
}
while (line < 6)
{
line++;
for (int i = 1; i < 8; i++)
{
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView (_calendarMonthView)
{
Frame = new RectangleF((i - 1) * boxWidth -1, line * boxHeight, boxWidth, boxHeight),
Text = dayCounter.ToString(),
};
dayView.Date = viewDay;
updateDayView (dayView);
AddSubview (dayView);
_dayTiles.Add (dayView);
dayCounter++;
}
}
Frame = new RectangleF(Frame.Location, new SizeF(Frame.Width, (line + 1) * boxHeight));
Lines = (position == 1 ? line - 1 : line);
if (SelectedDayView!=null)
this.BringSubviewToFront(SelectedDayView);
}
/*public override void TouchesBegan (NSSet touches, UIEvent evt)
{
base.TouchesBegan (touches, evt);
if (SelectDayView((UITouch)touches.AnyObject)&& _calendarMonthView.OnDateSelected!=null)
_calendarMonthView.OnDateSelected(new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag));
}
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
base.TouchesMoved (touches, evt);
if (SelectDayView((UITouch)touches.AnyObject)&& _calendarMonthView.OnDateSelected!=null)
_calendarMonthView.OnDateSelected(new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag));
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
base.TouchesEnded (touches, evt);
if (_calendarMonthView.OnFinishedDateSelection==null) return;
var date = new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag);
if (_calendarMonthView.IsDateAvailable == null || _calendarMonthView.IsDateAvailable(date))
_calendarMonthView.OnFinishedDateSelection(date);
}*/
private bool SelectDayView(PointF p){
int index = ((int)p.Y / _calendarMonthView.BoxHeight) * 7 + ((int)p.X / _calendarMonthView.BoxWidth);
if(index<0 || index >= _dayTiles.Count) return false;
var newSelectedDayView = _dayTiles[index];
if (newSelectedDayView == SelectedDayView)
return false;
if (!newSelectedDayView.Active){
var day = int.Parse(newSelectedDayView.Text);
if (day > 15)
_calendarMonthView.MoveCalendarMonths(false, true);
else
_calendarMonthView.MoveCalendarMonths(true, true);
return false;
} else if (!newSelectedDayView.Active && !newSelectedDayView.Available){
return false;
}
if (SelectedDayView!=null)
SelectedDayView.Selected = false;
this.BringSubviewToFront(newSelectedDayView);
newSelectedDayView.Selected = true;
SelectedDayView = newSelectedDayView;
_calendarMonthView.CurrentSelectedDate = SelectedDayView.Date;
SetNeedsDisplay();
return true;
}
public void DeselectDayView(){
if (SelectedDayView==null) return;
SelectedDayView.Selected= false;
SelectedDayView = null;
SetNeedsDisplay();
}
}
public class CalendarDayView : UIView
{
string _text;
public DateTime Date {get;set;}
bool _active, _today, _selected, _marked, _available;
public bool Available {get {return _available; } set {_available = value; SetNeedsDisplay(); }}
public string Text {get { return _text; } set { _text = value; SetNeedsDisplay(); } }
public bool Active {get { return _active; } set { _active = value; SetNeedsDisplay(); } }
public bool Today {get { return _today; } set { _today = value; SetNeedsDisplay(); } }
public bool Selected {get { return _selected; } set { _selected = value; SetNeedsDisplay(); } }
public bool Marked {get { return _marked; } set { _marked = value; SetNeedsDisplay(); } }
CalendarMonthView _mv;
public CalendarDayView (CalendarMonthView mv)
{
_mv = mv;
BackgroundColor = UIColor.White;
}
public override void Draw(RectangleF rect)
{
UIImage img = null;
UIColor color = UIColor.Gray;
if (!Active || !Available)
{
//color = UIColor.FromRGBA(0.576f, 0.608f, 0.647f, 1f);
//img = UIImage.FromBundle("Images/Calendar/datecell.png");
}
else if (Today && Selected)
{
//color = UIColor.White;
img = UIImage.FromBundle("Images/Calendar/todayselected.png").CreateResizableImage(new UIEdgeInsets(4,4,4,4));
}
else if (Today)
{
//color = UIColor.White;
img = UIImage.FromBundle("Images/Calendar/today.png").CreateResizableImage(new UIEdgeInsets(4,4,4,4));
}
else if (Selected || Marked)
{
//color = UIColor.White;
img = UIImage.FromBundle("Images/Calendar/datecellselected.png").CreateResizableImage(new UIEdgeInsets(4,4,4,4));
}
else
{
color = UIColor.FromRGBA(0.275f, 0.341f, 0.412f, 1f);
//img = UIImage.FromBundle("Images/Calendar/datecell.png");
}
if (img != null)
img.Draw(new RectangleF(0, 0, _mv.BoxWidth, _mv.BoxHeight));
color.SetColor();
var inflated = new RectangleF(0, 5, Bounds.Width, Bounds.Height);
DrawString(Text, inflated,
UIFont.BoldSystemFontOfSize(16),
UILineBreakMode.WordWrap, UITextAlignment.Center);
// if (Marked)
// {
// var context = UIGraphics.GetCurrentContext();
// if (Selected || Today)
// context.SetRGBFillColor(1, 1, 1, 1);
// else if (!Active || !Available)
// UIColor.LightGray.SetColor();
// else
// context.SetRGBFillColor(75/255f, 92/255f, 111/255f, 1);
// context.SetLineWidth(0);
// context.AddEllipseInRect(new RectangleF(Frame.Size.Width/2 - 2, 45-10, 4, 4));
// context.FillPath();
//
// }
}
}
}
| |
//SERVER LoginForm
//#################
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Win32;
namespace AWI.SmartTracker
{
/// <summary>
/// Summary description for LoginForm.
/// </summary>
public class LoginForm : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton SQLRadioButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button OKButton;
private System.Windows.Forms.Button CloseButton;
private System.Windows.Forms.TextBox UserNameTextBox;
private System.Windows.Forms.TextBox PWTextBox;
private System.Windows.Forms.TextBox ServerTextBox;
private System.Windows.Forms.TextBox DBTextBox;
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.RadioButton MySQLRadioButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public LoginForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//changes made to support MYSQL Server v5.0 and later
CultureInfo ci = new CultureInfo("sv-SE", true);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.DateSeparator = "-";
RegistryKey regVersion = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Active Wave", true);
RegistryKey reg = Registry.CurrentUser.CreateSubKey("Software\\Active Wave\\Smart Tracker\\");
string s = (string)reg.GetValue("server");
if(s != null)
MainForm.server = s;
s = (string)reg.GetValue("database");
if(s != null)
MainForm.database = s;
s = (string)reg.GetValue("serverMySQL");
if(s != null)
MainForm.serverMySQL = s;
s = (string)reg.GetValue("user");
if(s != null)
MainForm.user = s;
s = (string)reg.GetValue("provider");
if(s != null)
{
if (s == "SQL")
MainForm.providerName = dbProvider.SQL;
else if (s == "MySQL")
MainForm.providerName = dbProvider.MySQL;
}
//Registry.LocalMachine.OpenSubKey("Software\\myTestKey", true);
//if (regVersion.
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.MySQLRadioButton = new System.Windows.Forms.RadioButton();
this.SQLRadioButton = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.OKButton = new System.Windows.Forms.Button();
this.CloseButton = new System.Windows.Forms.Button();
this.UserNameTextBox = new System.Windows.Forms.TextBox();
this.PWTextBox = new System.Windows.Forms.TextBox();
this.ServerTextBox = new System.Windows.Forms.TextBox();
this.DBTextBox = new System.Windows.Forms.TextBox();
this.PortTextBox = new System.Windows.Forms.TextBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.MySQLRadioButton);
this.groupBox1.Controls.Add(this.SQLRadioButton);
this.groupBox1.Location = new System.Drawing.Point(10, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(222, 56);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Database Server";
//
// MySQLRadioButton
//
this.MySQLRadioButton.AutoSize = true;
this.MySQLRadioButton.Location = new System.Drawing.Point(136, 25);
this.MySQLRadioButton.Name = "MySQLRadioButton";
this.MySQLRadioButton.Size = new System.Drawing.Size(58, 17);
this.MySQLRadioButton.TabIndex = 1;
this.MySQLRadioButton.Text = "MySQL";
this.MySQLRadioButton.Click += new System.EventHandler(this.MySQLRadioButton_Click);
//
// SQLRadioButton
//
this.SQLRadioButton.AutoSize = true;
this.SQLRadioButton.Location = new System.Drawing.Point(28, 25);
this.SQLRadioButton.Name = "SQLRadioButton";
this.SQLRadioButton.Size = new System.Drawing.Size(44, 17);
this.SQLRadioButton.TabIndex = 0;
this.SQLRadioButton.Text = "SQL";
this.SQLRadioButton.Click += new System.EventHandler(this.SQLRadioButton_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 91);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(66, 13);
this.label1.TabIndex = 1;
this.label1.Text = "User Name: ";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 122);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(60, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Password: ";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 152);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(43, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Server:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 182);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(60, 13);
this.label4.TabIndex = 7;
this.label4.Text = "Database: ";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 212);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(34, 13);
this.label5.TabIndex = 9;
this.label5.Text = "Port: ";
//
// OKButton
//
this.OKButton.AutoSize = true;
this.OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OKButton.Location = new System.Drawing.Point(39, 244);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(75, 26);
this.OKButton.TabIndex = 11;
this.OKButton.Text = "OK";
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// CloseButton
//
this.CloseButton.AutoSize = true;
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Location = new System.Drawing.Point(136, 244);
this.CloseButton.Name = "CloseButton";
this.CloseButton.Size = new System.Drawing.Size(75, 26);
this.CloseButton.TabIndex = 12;
this.CloseButton.Text = "Cancel";
this.CloseButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// UserNameTextBox
//
this.UserNameTextBox.Location = new System.Drawing.Point(78, 88);
this.UserNameTextBox.Name = "UserNameTextBox";
this.UserNameTextBox.Size = new System.Drawing.Size(154, 21);
this.UserNameTextBox.TabIndex = 2;
//
// PWTextBox
//
this.PWTextBox.Location = new System.Drawing.Point(78, 118);
this.PWTextBox.Name = "PWTextBox";
this.PWTextBox.PasswordChar = '*';
this.PWTextBox.Size = new System.Drawing.Size(154, 21);
this.PWTextBox.TabIndex = 4;
this.PWTextBox.UseSystemPasswordChar = true;
//
// ServerTextBox
//
this.ServerTextBox.Location = new System.Drawing.Point(78, 148);
this.ServerTextBox.Name = "ServerTextBox";
this.ServerTextBox.Size = new System.Drawing.Size(154, 21);
this.ServerTextBox.TabIndex = 6;
//
// DBTextBox
//
this.DBTextBox.Location = new System.Drawing.Point(78, 178);
this.DBTextBox.Name = "DBTextBox";
this.DBTextBox.Size = new System.Drawing.Size(154, 21);
this.DBTextBox.TabIndex = 8;
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(78, 208);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.ReadOnly = true;
this.PortTextBox.Size = new System.Drawing.Size(154, 21);
this.PortTextBox.TabIndex = 10;
this.PortTextBox.Text = "3306";
//
// LoginForm
//
this.AcceptButton = this.OKButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.CancelButton = this.CloseButton;
this.ClientSize = new System.Drawing.Size(250, 283);
this.ControlBox = false;
this.Controls.Add(this.PortTextBox);
this.Controls.Add(this.DBTextBox);
this.Controls.Add(this.ServerTextBox);
this.Controls.Add(this.PWTextBox);
this.Controls.Add(this.UserNameTextBox);
this.Controls.Add(this.CloseButton);
this.Controls.Add(this.OKButton);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LoginForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Database Login";
this.TopMost = true;
this.Load += new System.EventHandler(this.LoginForm_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void LoginForm_Load(object sender, System.EventArgs e)
{
if (MainForm.providerName == dbProvider.SQL)
{
SQLRadioButton.Checked = true;
}
else if (MainForm.providerName == dbProvider.MySQL)
{
MySQLRadioButton.Checked = true;
}
}
private void OKButton_Click(object sender, System.EventArgs e)
{
if (SQLRadioButton.Checked)
{
MainForm.providerName = dbProvider.SQL;
if (ServerTextBox.TextLength > 0)
MainForm.server = ServerTextBox.Text;
}
else
{
MainForm.providerName = dbProvider.MySQL;
if (ServerTextBox.TextLength > 0)
MainForm.serverMySQL = ServerTextBox.Text;
}
if (UserNameTextBox.TextLength > 0)
MainForm.user = UserNameTextBox.Text;
if (PWTextBox.TextLength > 0)
MainForm.password = PWTextBox.Text;
if (DBTextBox.TextLength > 0)
MainForm.database = DBTextBox.Text;
MainForm.PlaySound(1);
Close();
}
private void CancelButton_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
private void SQLRadioButton_Click(object sender, System.EventArgs e)
{
UserNameTextBox.Text = "";
UserNameTextBox.Enabled = false;
PWTextBox.Text = "";
PWTextBox.Enabled = false;
if (MainForm.server.Length > 0)
ServerTextBox.Text = MainForm.server;
else
ServerTextBox.Text = "";
if (MainForm.database.Length > 0)
DBTextBox.Text = MainForm.database;
}
private void MySQLRadioButton_Click(object sender, System.EventArgs e)
{
if (MainForm.user.Length > 0)
UserNameTextBox.Text = MainForm.user;
else
UserNameTextBox.Text = "";
UserNameTextBox.Enabled = true;
if (MainForm.password.Length > 0)
PWTextBox.Text = MainForm.password;
else
PWTextBox.Text = "";
PWTextBox.Enabled = true;
if (MainForm.serverMySQL.Length > 0)
ServerTextBox.Text = MainForm.serverMySQL;
else
ServerTextBox.Text = "";
if (MainForm.database.Length > 0)
DBTextBox.Text = MainForm.database;
}
}
}
| |
namespace Petstore
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for StorageAccountsOperations.
/// </summary>
public static partial class StorageAccountsOperationsExtensions
{
/// <summary>
/// Checks that account name is valid and is not in use.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
public static CheckNameAvailabilityResult CheckNameAvailability(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).CheckNameAvailabilityAsync(accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks that account name is valid and is not in use.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and should
/// instead use the Update Storage Account API. If an account is already
/// created and subsequent PUT request is issued with exact same set of
/// properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
public static StorageAccount Create(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).CreateAsync(resourceGroupName, accountName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and should
/// instead use the Update Storage Account API. If an account is already
/// created and subsequent PUT request is issued with exact same set of
/// properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> CreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and should
/// instead use the Update Storage Account API. If an account is already
/// created and subsequent PUT request is issued with exact same set of
/// properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
public static StorageAccount BeginCreate(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).BeginCreateAsync(resourceGroupName, accountName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and should
/// instead use the Update Storage Account API. If an account is already
/// created and subsequent PUT request is issued with exact same set of
/// properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> BeginCreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
public static void Delete(this IStorageAccountsOperations operations, string resourceGroupName, string accountName)
{
Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).DeleteAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns the properties for the specified storage account including but not
/// limited to name, account type, location, and account status. The ListKeys
/// operation should be used to retrieve storage keys.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
public static StorageAccount GetProperties(this IStorageAccountsOperations operations, string resourceGroupName, string accountName)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).GetPropertiesAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the properties for the specified storage account including but not
/// limited to name, account type, location, and account status. The ListKeys
/// operation should be used to retrieve storage keys.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> GetPropertiesAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the account type or tags for a storage account. It can also be
/// used to add a custom domain (note that custom domains cannot be added via
/// the Create operation). Only one custom domain is supported per storage
/// account. In order to replace a custom domain, the old value must be
/// cleared before a new value may be set. To clear a custom domain, simply
/// update the custom domain with empty string. Then call update again with
/// the new cutsom domain name. The update API can only be used to update one
/// of tags, accountType, or customDomain per call. To update multiple of
/// these properties, call the API multiple times with one change per call.
/// This call does not change the storage keys for the account. If you want
/// to change storage account keys, use the RegenerateKey operation. The
/// location and name of the storage account cannot be changed after creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to update on the account. Note that only one property can
/// be changed at a time using this API.
/// </param>
public static StorageAccount Update(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).UpdateAsync(resourceGroupName, accountName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates the account type or tags for a storage account. It can also be
/// used to add a custom domain (note that custom domains cannot be added via
/// the Create operation). Only one custom domain is supported per storage
/// account. In order to replace a custom domain, the old value must be
/// cleared before a new value may be set. To clear a custom domain, simply
/// update the custom domain with empty string. Then call update again with
/// the new cutsom domain name. The update API can only be used to update one
/// of tags, accountType, or customDomain per call. To update multiple of
/// these properties, call the API multiple times with one change per call.
/// This call does not change the storage keys for the account. If you want
/// to change storage account keys, use the RegenerateKey operation. The
/// location and name of the storage account cannot be changed after creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to update on the account. Note that only one property can
/// be changed at a time using this API.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccount> UpdateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the storage account.
/// </param>
public static StorageAccountKeys ListKeys(this IStorageAccountsOperations operations, string resourceGroupName, string accountName)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).ListKeysAsync(resourceGroupName, accountName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the storage account.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccountKeys> ListKeysAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the storage accounts available under the subscription. Note that
/// storage keys are not returned; use the ListKeys operation for this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<StorageAccount> List(this IStorageAccountsOperations operations)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).ListAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the storage accounts available under the subscription. Note that
/// storage keys are not returned; use the ListKeys operation for this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<StorageAccount>> ListAsync(this IStorageAccountsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the storage accounts available under the given resource group.
/// Note that storage keys are not returned; use the ListKeys operation for
/// this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
public static IEnumerable<StorageAccount> ListByResourceGroup(this IStorageAccountsOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the storage accounts available under the given resource group.
/// Note that storage keys are not returned; use the ListKeys operation for
/// this.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this IStorageAccountsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Specifies name of the key which should be regenerated. key1 or key2 for
/// the default keys
/// </param>
public static StorageAccountKeys RegenerateKey(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey)
{
return Task.Factory.StartNew(s => ((IStorageAccountsOperations)s).RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and
/// use numbers and lower-case letters only.
/// </param>
/// <param name='regenerateKey'>
/// Specifies name of the key which should be regenerated. key1 or key2 for
/// the default keys
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<StorageAccountKeys> RegenerateKeyAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, regenerateKey, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Internal
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal unsafe struct MemoryBlock
{
internal readonly byte* Pointer;
internal readonly int Length;
internal MemoryBlock(byte* buffer, int length)
{
Debug.Assert(length >= 0 && (buffer != null || length == 0));
this.Pointer = buffer;
this.Length = length;
}
internal static MemoryBlock CreateChecked(byte* buffer, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (buffer == null && length != 0)
{
throw new ArgumentNullException("buffer");
}
// the reader performs little-endian specific operations
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired);
}
return new MemoryBlock(buffer, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length)
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
internal byte[] ToArray()
{
return Pointer == null ? null : PeekBytes(0, Length);
}
private string GetDebuggerDisplay()
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
return GetDebuggerDisplay(out displayedBytes);
}
internal string GetDebuggerDisplay(out int displayedBytes)
{
displayedBytes = Math.Min(Length, 64);
string result = BitConverter.ToString(PeekBytes(0, displayedBytes));
if (displayedBytes < Length)
{
result += "-...";
}
return result;
}
internal string GetDebuggerDisplay(int offset)
{
if (Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = GetDebuggerDisplay(out displayedBytes);
if (offset < displayedBytes)
{
display = display.Insert(offset * 3, "*");
}
else if (displayedBytes == Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(Pointer + offset, length);
}
internal byte PeekByte(int offset)
{
CheckBounds(offset, sizeof(byte));
return Pointer[offset];
}
internal int PeekInt32(int offset)
{
uint result = PeekUInt32(offset);
if (unchecked((int)result != result))
{
ThrowValueOverflow();
}
return (int)result;
}
internal uint PeekUInt32(int offset)
{
CheckBounds(offset, sizeof(uint));
return *(uint*)(Pointer + offset);
}
/// <summary>
/// Decodes a compressed integer value starting at offset.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="offset">Offset to the start of the compressed data.</param>
/// <param name="numberOfBytesRead">Bytes actually read.</param>
/// <returns>
/// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid.
/// </returns>
internal int PeekCompressedInteger(int offset, out int numberOfBytesRead)
{
CheckBounds(offset, 0);
byte* ptr = Pointer + offset;
long limit = Length - offset;
if (limit == 0)
{
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
byte headerByte = ptr[0];
if ((headerByte & 0x80) == 0)
{
numberOfBytesRead = 1;
return headerByte;
}
else if ((headerByte & 0x40) == 0)
{
if (limit >= 2)
{
numberOfBytesRead = 2;
return ((headerByte & 0x3f) << 8) | ptr[1];
}
}
else if ((headerByte & 0x20) == 0)
{
if (limit >= 4)
{
numberOfBytesRead = 4;
return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
}
numberOfBytesRead = 0;
return BlobReader.InvalidCompressedInteger;
}
internal ushort PeekUInt16(int offset)
{
CheckBounds(offset, sizeof(ushort));
return *(ushort*)(Pointer + offset);
}
// When reference has tag bits.
internal uint PeekTaggedReference(int offset, bool smallRefSize)
{
return PeekReferenceUnchecked(offset, smallRefSize);
}
// Use when searching for a tagged or non-tagged reference.
// The result may be an invalid reference and shall only be used to compare with a valid reference.
internal uint PeekReferenceUnchecked(int offset, bool smallRefSize)
{
return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset);
}
// When reference has at most 24 bits.
internal int PeekReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!TokenTypeIds.IsValidRowId(value))
{
Throw.ReferenceOverflow();
}
return (int)value;
}
// #String, #Blob heaps
internal int PeekHeapReference(int offset, bool smallRefSize)
{
if (smallRefSize)
{
return PeekUInt16(offset);
}
uint value = PeekUInt32(offset);
if (!HeapHandleType.IsValidHeapOffset(value))
{
Throw.ReferenceOverflow();
}
return (int)value;
}
internal Guid PeekGuid(int offset)
{
CheckBounds(offset, sizeof(Guid));
return *(Guid*)(Pointer + offset);
}
internal string PeekUtf16(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
// doesn't allocate a new string if byteCount == 0
return new string((char*)(Pointer + offset), 0, byteCount / sizeof(char));
}
internal string PeekUtf8(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
return Encoding.UTF8.GetString(Pointer + offset, byteCount);
}
/// <summary>
/// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param>
/// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <returns>The decoded string.</returns>
internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0')
{
Debug.Assert(terminator <= 0x7F);
CheckBounds(offset, 0);
int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator);
return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder);
}
/// <summary>
/// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first).
/// Returned length does not include the terminator, but numberOfBytesRead out parameter does.
/// </summary>
/// <param name="offset">Offset in to the block where the UTF8 bytes start.</param>
/// <param name="terminator">A character in the ASCII range that marks the end of the string.
/// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param>
/// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param>
/// <returns>Length (byte count) not including terminator.</returns>
internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0')
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7f);
byte* start = Pointer + offset;
byte* end = Pointer + Length;
byte* current = start;
while (current < end)
{
byte b = *current;
if (b == 0 || b == terminator)
{
break;
}
current++;
}
int length = (int)(current - start);
numberOfBytesRead = length;
if (current < end)
{
// we also read the terminator
numberOfBytesRead++;
}
return length;
}
internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar)
{
CheckBounds(startOffset, 0);
Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f);
for (int i = startOffset; i < Length; i++)
{
byte b = Pointer[i];
if (b == 0)
{
break;
}
if (b == asciiChar)
{
return i;
}
}
return -1;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase)
{
int firstDifference;
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase);
if (result == FastComparisonResult.Inconclusive)
{
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return result == FastComparisonResult.Equal;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase)
{
int endIndex;
FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase);
switch (result)
{
case FastComparisonResult.Equal:
case FastComparisonResult.BytesStartWithText:
return true;
case FastComparisonResult.Unequal:
case FastComparisonResult.TextStartsWithBytes:
return false;
default:
Debug.Assert(result == FastComparisonResult.Inconclusive);
int bytesRead;
string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator);
return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
}
internal enum FastComparisonResult
{
Equal,
BytesStartWithText,
TextStartsWithBytes,
Unequal,
Inconclusive
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase)
{
CheckBounds(offset, 0);
Debug.Assert(terminator <= 0x7F);
byte* startPointer = Pointer + offset;
byte* endPointer = Pointer + Length;
byte* currentPointer = startPointer;
int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase);
int currentIndex = textStart;
while (currentIndex < text.Length && currentPointer != endPointer)
{
byte currentByte = *currentPointer;
// note that terminator is not compared case-insensitively even if ignore case is true
if (currentByte == 0 || currentByte == terminator)
{
break;
}
char currentChar = text[currentIndex];
if ((currentByte & 0x80) == 0 && StringUtils.IsEqualAscii(currentChar, currentByte, ignoreCaseMask))
{
currentIndex++;
currentPointer++;
}
else
{
firstDifferenceIndex = currentIndex;
// uncommon non-ascii case --> fall back to slow allocating comparison.
return (currentChar > 0x7F) ? FastComparisonResult.Inconclusive : FastComparisonResult.Unequal;
}
}
firstDifferenceIndex = currentIndex;
bool textTerminated = currentIndex == text.Length;
bool bytesTerminated = currentPointer == endPointer || *currentPointer == 0 || *currentPointer == terminator;
if (textTerminated && bytesTerminated)
{
return FastComparisonResult.Equal;
}
return textTerminated ? FastComparisonResult.BytesStartWithText : FastComparisonResult.TextStartsWithBytes;
}
// comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first.
internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
// Make sure that we won't read beyond the block even if the block doesn't end with 0 byte.
if (asciiPrefix.Length > Length - offset)
{
return false;
}
byte* p = Pointer + offset;
for (int i = 0; i < asciiPrefix.Length; i++)
{
Debug.Assert(asciiPrefix[i] > 0 && asciiPrefix[i] <= 0x7f);
if (asciiPrefix[i] != *p)
{
return false;
}
p++;
}
return true;
}
internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString)
{
// Assumes stringAscii only contains ASCII characters and no nil characters.
CheckBounds(offset, 0);
byte* p = Pointer + offset;
int limit = Length - offset;
for (int i = 0; i < asciiString.Length; i++)
{
Debug.Assert(asciiString[i] > 0 && asciiString[i] <= 0x7f);
if (i > limit)
{
// Heap value is shorter.
return -1;
}
if (*p != asciiString[i])
{
// If we hit the end of the heap value (*p == 0)
// the heap value is shorter than the string, so we return negative value.
return *p - asciiString[i];
}
p++;
}
// Either the heap value name matches exactly the given string or
// it is longer so it is considered "greater".
return (*p == 0) ? 0 : +1;
}
internal byte[] PeekBytes(int offset, int byteCount)
{
CheckBounds(offset, byteCount);
if (byteCount == 0)
{
return EmptyArray<byte>.Instance;
}
byte[] result = new byte[byteCount];
Marshal.Copy((IntPtr)(Pointer + offset), result, 0, byteCount);
return result;
}
internal int IndexOf(byte b, int start)
{
CheckBounds(start, 0);
byte* p = Pointer + start;
byte* end = Pointer + Length;
while (p < end)
{
if (*p == b)
{
return (int)(p - Pointer);
}
p++;
}
return -1;
}
// same as Array.BinarySearch, but without using IComparer
internal int BinarySearch(string[] asciiKeys, int offset)
{
var low = 0;
var high = asciiKeys.Length - 1;
while (low <= high)
{
var middle = low + ((high - low) >> 1);
var midValue = asciiKeys[middle];
int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue);
if (comparison == 0)
{
return middle;
}
if (comparison < 0)
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return ~low;
}
/// <summary>
/// In a table that specifies children via a list field (e.g. TypeDef.FieldList, TypeDef.MethodList),
/// seaches for the parent given a reference to a child.
/// </summary>
/// <returns>Returns row number [0..RowCount).</returns>
internal int BinarySearchForSlot(
int rowCount,
int rowSize,
int referenceListOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceListOffset, isReferenceSmall);
uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceListOffset, isReferenceSmall);
if (endRowNumber == 1)
{
if (referenceValue >= endValue)
{
return endRowNumber;
}
return startRowNumber;
}
while (endRowNumber - startRowNumber > 1)
{
if (referenceValue <= startValue)
{
return referenceValue == startValue ? startRowNumber : startRowNumber - 1;
}
if (referenceValue >= endValue)
{
return referenceValue == endValue ? endRowNumber : endRowNumber + 1;
}
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceListOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber;
startValue = midReferenceValue;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber;
endValue = midReferenceValue;
}
else
{
return midRowNumber;
}
}
return startRowNumber;
}
/// <summary>
/// In a table ordered by a column containing entity references seaches for a row with the specified reference.
/// </summary>
/// <returns>Returns row number [0..RowCount) or -1 if not found.</returns>
internal int BinarySearchReference(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = rowCount - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
// Row number [0, ptrTable.Length) or -1 if not found.
internal int BinarySearchReference(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int startRowNumber = 0;
int endRowNumber = ptrTable.Length - 1;
while (startRowNumber <= endRowNumber)
{
int midRowNumber = (startRowNumber + endRowNumber) / 2;
uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall);
if (referenceValue > midReferenceValue)
{
startRowNumber = midRowNumber + 1;
}
else if (referenceValue < midReferenceValue)
{
endRowNumber = midRowNumber - 1;
}
else
{
return midRowNumber;
}
}
return -1;
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int rowCount,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, rowCount) or -1
out int endRowNumber) // [0, rowCount) or -1
{
int foundRowNumber = BinarySearchReference(
rowCount,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < rowCount &&
PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
/// <summary>
/// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column.
/// </summary>
internal void BinarySearchReferenceRange(
int[] ptrTable,
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall,
out int startRowNumber, // [0, ptrTable.Length) or -1
out int endRowNumber) // [0, ptrTable.Length) or -1
{
int foundRowNumber = BinarySearchReference(
ptrTable,
rowSize,
referenceOffset,
referenceValue,
isReferenceSmall
);
if (foundRowNumber == -1)
{
startRowNumber = -1;
endRowNumber = -1;
return;
}
startRowNumber = foundRowNumber;
while (startRowNumber > 0 &&
PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
startRowNumber--;
}
endRowNumber = foundRowNumber;
while (endRowNumber + 1 < ptrTable.Length &&
PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue)
{
endRowNumber++;
}
}
// Always RowNumber....
internal int LinearSearchReference(
int rowSize,
int referenceOffset,
uint referenceValue,
bool isReferenceSmall)
{
int currOffset = referenceOffset;
int totalSize = this.Length;
while (currOffset < totalSize)
{
uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall);
if (currReference == referenceValue)
{
return currOffset / rowSize;
}
currOffset += rowSize;
}
return -1;
}
internal bool IsOrderedByReferenceAscending(
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
uint previous = 0;
while (offset < totalSize)
{
uint current = PeekReferenceUnchecked(offset, isReferenceSmall);
if (current < previous)
{
return false;
}
previous = current;
offset += rowSize;
}
return true;
}
internal int[] BuildPtrTable(
int numberOfRows,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int[] ptrTable = new int[numberOfRows];
uint[] unsortedReferences = new uint[numberOfRows];
for (int i = 0; i < ptrTable.Length; i++)
{
ptrTable[i] = i + 1;
}
ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall);
Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); });
return ptrTable;
}
private void ReadColumn(
uint[] result,
int rowSize,
int referenceOffset,
bool isReferenceSmall)
{
int offset = referenceOffset;
int totalSize = this.Length;
int i = 0;
while (offset < totalSize)
{
result[i] = PeekReferenceUnchecked(offset, isReferenceSmall);
offset += rowSize;
i++;
}
Debug.Assert(i == result.Length);
}
internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size)
{
int bytesRead;
int numberOfBytes = PeekCompressedInteger(index, out bytesRead);
if (numberOfBytes == BlobReader.InvalidCompressedInteger)
{
offset = 0;
size = 0;
return false;
}
offset = index + bytesRead;
size = numberOfBytes;
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace SimShift.MapTool
{
public class Ets2Item
{
public Ets2Sector Sector { get; private set; }
public ulong ItemUID { get; private set; }
public Ets2ItemType Type { get; set; }
public string FilePath { get; set; }
public int FileOffset { get; set; }
public int BlockSize { get; private set; }
public bool Valid { get; private set; }
public bool HideUI { get; private set; }
public Dictionary<ulong, Ets2Node> NodesList { get; private set; }
// Dictionary <Prefab> , <NavigationWeight, Length, RoadList>>
public Dictionary<Ets2Item, Tuple<float, float, IEnumerable<Ets2Item>>> Navigation { get; private set; }
public Ets2Node StartNode { get; private set; }
public ulong StartNodeUID { get; private set; }
public Ets2Node EndNode { get; private set; }
public ulong EndNodeUID { get; private set; }
public Ets2Node PrefabNode { get; set; }
public ulong PrefabNodeUID { get; set; }
/** Item specific values/interpretations **/
// Prefab type
public Ets2Prefab Prefab { get; private set; }
public int Origin = 0;
// Road info
public Ets2RoadLook RoadLook { get; private set; }
public IEnumerable<PointF> RoadPolygons { get; private set; }
// City/company info
public string City { get; private set; }
public string Company { get; set; }
public Ets2Item(ulong uid, Ets2Sector sector, int offset)
{
ItemUID = uid;
Navigation = new Dictionary<Ets2Item, Tuple<float, float, IEnumerable<Ets2Item>>>();
Sector = sector;
FileOffset = offset;
FilePath = sector.FilePath;
NodesList = new Dictionary<ulong, Ets2Node>();
Type = (Ets2ItemType)BitConverter.ToUInt32(sector.Stream, offset);
int nodeCount;
switch (Type)
{
case Ets2ItemType.Road:
StartNodeUID = BitConverter.ToUInt64(sector.Stream, offset + 141);
EndNodeUID = BitConverter.ToUInt64(sector.Stream, offset + 149);
var lookId = BitConverter.ToUInt32(sector.Stream, offset + 61); // unique UINT32 ID with road look
RoadLook = Sector.Mapper.LookupRoadLookID(lookId);
// Need to create LUT to translate road_look.sii <> ID
// Then we can parse highway routes etc.
HideUI = (sector.Stream[offset + 0x37] & 0x02) != 0;
// Make sure these UID's exist in the world.
if ((StartNodeUID != 0 && sector.Mapper.Nodes.ContainsKey(StartNodeUID)) ||
(EndNodeUID != 0 && sector.Mapper.Nodes.ContainsKey(EndNodeUID)))
{
Valid = true;
var stamps = BitConverter.ToInt32(sector.Stream, offset + 433);
BlockSize = 437 + stamps*24;
}
else
{
Valid = false;
}
break;
case Ets2ItemType.Prefab:
if (uid == 0x2935de9c700704)
{
//
}
nodeCount = BitConverter.ToInt32(sector.Stream, offset + 81);
HideUI = (sector.Stream[offset + 0x36] & 0x02) != 0;
if (nodeCount > 0x20)
{
Valid = false;
return;
}
var somethingOffset = offset + 85 + 8*nodeCount;
if (somethingOffset < offset || somethingOffset > sector.Stream.Length)
{
Valid = false;
return;
}
var something = BitConverter.ToInt32(sector.Stream,somethingOffset);
if (something < 0 || something > 32)
{
Valid = false;
return;
}
var OriginOffset = offset + 0x61 + nodeCount*8 + something*8;
if (OriginOffset < offset || OriginOffset > sector.Stream.Length)
{
Valid = false;
return;
}
Origin = sector.Stream[OriginOffset] & 0x03;
//Console.WriteLine("PREFAB @ " + uid.ToString("X16") + " origin: " + Origin);
var prefabId = (int)BitConverter.ToUInt32(sector.Stream, offset + 57);
// Invalidate unreasonable amount of node counts..
if (nodeCount < 0x20 && nodeCount != 0)
{
Valid = true;
for (int i = 0; i < nodeCount; i++)
{
var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 81 + 4 + i*8);
//Console.WriteLine("prefab node link " + i + ": " + nodeUid.ToString("X16"));
// TODO: if node is in other sector..
if (AddNodeUID(nodeUid) == false)
{
//Console.WriteLine("Could not add prefab node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16"));
break;
}
}
PrefabNodeUID = NodesList.Keys.FirstOrDefault();
}
//Console.WriteLine("PREFAB ID: " + prefabId.ToString("X8"));
Prefab = sector.Mapper.LookupPrefab(prefabId);
if (Prefab == null)
{
//Console.WriteLine("Prefab ID: " + uid.ToString("X16") + " / " + prefabId.ToString("X") +
// " not found");
}
break;
case Ets2ItemType.Company:
Valid = true;
// There are 3 nodes subtracted from found in sector:
// 1) The node of company itself
// 2) The node of loading area
// 3) The node of job
nodeCount = Sector.Nodes.Count(x => x.ForwardItemUID == uid) - 2;
BlockSize = nodeCount*8 + 109;
// Invalidate unreasonable amount of node counts..
if (nodeCount < 0x20)
{
var prefabItemUid = BitConverter.ToUInt64(sector.Stream, offset + 73);
var loadAreaNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 93);
var jobAreaNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 81);
if (AddNodeUID(loadAreaNodeUid) == false)
{
//Console.WriteLine("Could not add loading area node " + loadAreaNodeUid.ToString("X16"));
}
else if (AddNodeUID(jobAreaNodeUid) == false)
{
//Console.WriteLine("Could not add job area node" + jobAreaNodeUid.ToString("X16"));
}
else
{
for (int i = 0; i < nodeCount; i++)
{
var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 113 + i*8);
//Console.WriteLine("company node link " + i + ": " + nodeUid.ToString("X16"));
if (AddNodeUID(nodeUid) == false)
{
//Console.WriteLine("Could not add cargo area node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16"));
break;
}
}
}
}
else
{
Valid = false;
}
break;
case Ets2ItemType.Building:
var buildingNodeUid1 = BitConverter.ToUInt64(sector.Stream, offset + 73);
var buildingNodeUid2 = BitConverter.ToUInt64(sector.Stream, offset + 65);
Valid = AddNodeUID(buildingNodeUid1) && AddNodeUID(buildingNodeUid2);
BlockSize = 97;
break;
case Ets2ItemType.Sign:
var signNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 65);
BlockSize = 153;
Valid = AddNodeUID(signNodeUid);
break;
case Ets2ItemType.Model:
var modelNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 81);
BlockSize = 101;
Valid = AddNodeUID(modelNodeUid);
break;
case Ets2ItemType.MapOverlay:
var mapOverlayNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 65);
BlockSize = 73;
Valid = AddNodeUID(mapOverlayNodeUid);
break;
case Ets2ItemType.Ferry:
var ferryNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 73);
BlockSize = 93;
Valid = AddNodeUID(ferryNodeUid);
break;
case Ets2ItemType.CutPlane:
nodeCount = BitConverter.ToInt32(sector.Stream, offset + 57);
// Invalidate unreasonable amount of node counts..
if (nodeCount < 0x20)
{
Valid = true;
for (int i = 0; i < nodeCount; i++)
{
var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57 + 4 + i * 8);
//Console.WriteLine("cut plane node " + i + ": " + nodeUid.ToString("X16"));
if (AddNodeUID(nodeUid) == false)
{
//Console.WriteLine("Could not add cut plane node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16"));
break;
}
}
}
BlockSize = 61 + 8 * nodeCount;
break;
case Ets2ItemType.TrafficRule:
nodeCount = BitConverter.ToInt32(sector.Stream, offset + 57);
// Invalidate unreasonable amount of node counts..
if (nodeCount < 0x20)
{
Valid = true;
for (int i = 0; i < nodeCount; i++)
{
var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57 + 4 + i * 8);
//Console.WriteLine("traffic area node " + i + ": " + nodeUid.ToString("X16"));
if (AddNodeUID(nodeUid) == false)
{
//Console.WriteLine("Could not add traffic area node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16"));
break;
}
}
}
BlockSize = 73 + 8 * nodeCount;
break;
case Ets2ItemType.Trigger:
nodeCount = BitConverter.ToInt32(sector.Stream, offset + 57);
// Invalidate unreasonable amount of node counts..
if (nodeCount < 0x20)
{
Valid = true;
for (int i = 0; i < nodeCount; i++)
{
var nodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57 + 4 + i * 8);
//Console.WriteLine("trigger node " + i + ": " + nodeUid.ToString("X16"));
if (AddNodeUID(nodeUid) == false)
{
//Console.WriteLine("Could not add trigger node " + nodeUid.ToString("X16") + " for item " + uid.ToString("X16"));
break;
}
}
}
BlockSize = 117 + 8 * nodeCount;
break;
case Ets2ItemType.BusStop:
var busStopUid = BitConverter.ToUInt64(sector.Stream, offset + 73);
BlockSize = 81;
Valid = AddNodeUID(busStopUid);
break;
case Ets2ItemType.Garage:
// TODO: at offset 65 there is a int '1' value.. is it a list?
var garageUid = BitConverter.ToUInt64(sector.Stream, offset + 69);
BlockSize = 85;
Valid = AddNodeUID(garageUid);
break;
case Ets2ItemType.FuelPump:
var dunno2Uid = BitConverter.ToUInt64(sector.Stream, offset + 57);
BlockSize = 73;
Valid = AddNodeUID(dunno2Uid);
break;
case Ets2ItemType.Dunno:
Valid = true;
break;
case Ets2ItemType.Service:
var locationNodeUid = BitConverter.ToUInt64(sector.Stream, offset + 57);
Valid = AddNodeUID(locationNodeUid);
BlockSize = 73;
break;
case Ets2ItemType.City:
var CityID = BitConverter.ToUInt64(sector.Stream, offset + 57);
var NodeID = BitConverter.ToUInt64(sector.Stream, offset + 73);
if ((CityID >> 56) != 0)
{
break;
}
City = Sector.Mapper.LookupCityID(CityID);
Valid = City != string.Empty && NodeID != 0 && sector.Mapper.Nodes.ContainsKey(NodeID);
if (!Valid)
{
Console.WriteLine("Unknown city ID " + CityID.ToString("X16") + " at " + ItemUID.ToString("X16"));
}
else
{
StartNodeUID = NodeID;
//Console.WriteLine(CityID.ToString("X16") + " === " + City);
}
BlockSize = 81;
break;
default:
Valid = false;
break;
}
//if (Valid)
// Console.WriteLine("Item " + uid.ToString("X16") + " (" + Type.ToString() + ") is found at " + offset.ToString("X"));
}
/// <summary>
/// Generate road curves for a specific lane. The curve is generated with [steps]
/// nodes and positioned left or right from the road's middle point.
/// Additionally, each extra lane is shifted 4.5 game units outward.
/// </summary>
/// <param name="steps"></param>
/// <param name="leftlane"></param>
/// <param name="lane"></param>
/// <returns></returns>
public IEnumerable<Ets2Point> GenerateRoadCurve(int steps, bool leftlane, int lane)
{
var ps = new Ets2Point[steps];
var sx = StartNode.X;
var ex = EndNode.X;
var sz = StartNode.Z;
var ez = EndNode.Z;
if (steps == 2)
{
sx += (float)Math.Sin(-StartNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f);
sz += (float)Math.Cos(-StartNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f);
ex += (float)Math.Sin(-EndNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f);
ez += (float)Math.Cos(-EndNode.Yaw) * (leftlane ? -1 : 1) * (RoadLook.Offset + (0.5f + lane) * 4.5f);
ps[0] = new Ets2Point(sx, 0, sz, StartNode.Yaw);
ps[1] = new Ets2Point(ex, 0, ez, EndNode.Yaw);
return ps;
}
var radius = (float)Math.Sqrt((sx - ex) * (sx - ex) + (sz - ez) * (sz - ez));
var tangentSX = (float)Math.Cos(-StartNode.Yaw) * radius;
var tangentEX = (float)Math.Cos(-EndNode.Yaw) * radius;
var tangentSZ = (float)Math.Sin(-StartNode.Yaw) * radius;
var tangentEZ = (float)Math.Sin(-EndNode.Yaw) * radius;
for (int k = 0; k < steps; k++)
{
var s = (float) k/(float) (steps - 1);
var x = (float) Ets2CurveHelper.Hermite(s, sx, ex, tangentSX, tangentEX);
var z = (float) Ets2CurveHelper.Hermite(s, sz, ez, tangentSZ, tangentEZ);
var tx = (float) Ets2CurveHelper.HermiteTangent(s, sx, ex, tangentSX, tangentEX);
var ty = (float) Ets2CurveHelper.HermiteTangent(s, sz, ez, tangentSZ, tangentEZ);
var yaw = (float) Math.Atan2(ty, tx);
x += (float) Math.Sin(-yaw)*(leftlane ? -1 : 1)*(RoadLook.Offset + (0.5f + lane)*4.5f);
z += (float) Math.Cos(-yaw)*(leftlane ? -1 : 1)*(RoadLook.Offset + (0.5f + lane)*4.5f);
ps[k] = new Ets2Point(x, 0, z, yaw);
}
return ps;
}
public void GenerateRoadPolygon(int steps)
{
if (RoadPolygons == null)
RoadPolygons = new PointF[0];
if (RoadPolygons != null && RoadPolygons.Count() == steps)
return;
if (StartNode == null || EndNode == null)
return;
if (Type != Ets2ItemType.Road)
return;
var ps = new PointF[steps];
var sx = StartNode.X;
var ex = EndNode.X;
var sy = StartNode.Z;
var ey = EndNode.Z;
var radius = (float)Math.Sqrt((sx - ex) * (sx - ex) + (sy - ey) * (sy - ey));
var tangentSX = (float)Math.Cos(-StartNode.Yaw) * radius;
var tangentEX = (float)Math.Cos(-EndNode.Yaw) * radius;
var tangentSY = (float)Math.Sin(-StartNode.Yaw) * radius;
var tangentEY = (float)Math.Sin(-EndNode.Yaw) * radius;
for (int k = 0; k < steps; k++)
{
var s = (float)k / (float)(steps - 1);
var x= (float)Ets2CurveHelper.Hermite(s, sx, ex, tangentSX, tangentEX);
var y = (float)Ets2CurveHelper.Hermite(s, sy, ey, tangentSY, tangentEY);
ps[k] = new PointF(x, y);
}
RoadPolygons = ps;
}
private bool AddNodeUID(ulong nodeUid)
{
if (nodeUid == 0 || Sector.Mapper.Nodes.ContainsKey(nodeUid)== false)
{
Valid = false;
return false;
}
else
{
NodesList.Add(nodeUid, null);
return true;
}
}
public bool Apply(Ets2Node node)
{
if (node.NodeUID == PrefabNodeUID)
{
PrefabNode = node;
}
if (node.NodeUID == StartNodeUID)
{
StartNode = node;
return true;
}
else if (node.NodeUID == EndNodeUID)
{
EndNode = node;
return true;
}
else if (NodesList.ContainsKey(node.NodeUID))
{
NodesList[node.NodeUID] = node;
return true;
}
else
{
//Console.WriteLine("Could not apply node " + node.NodeUID.ToString("X16") + " to item " + ItemUID.ToString("X16"));
return false;
}
}
public override string ToString()
{
return "Item #" + ItemUID.ToString("X16") + " (" + Type.ToString() + ")";
}
}
}
| |
/*
* Copyright (C) 2004 Bruno Fernandez-Ruiz <brunofr@olympum.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.
*/
namespace Caffeine.Caffeinator
{
using System;
using System.Collections;
using System.Reflection;
public class Method
{
AccessFlag accessFlags;
string name;
string signature;
Class parent;
Descriptor ret;
ArrayList arguments;
public Method(Class parent)
{
this.parent = parent;
arguments = new ArrayList();
}
public AccessFlag AccessFlags {
set {
accessFlags = value;
}
get {
return accessFlags;
}
}
public string Name {
get {
return name;
}
set {
name = value;
}
}
public string Signature {
get {
return signature;
}
set {
if (value == null) {
throw new ApplicationException("Class format error, null descriptor");
}
if (value[0] != '(') {
throw new ApplicationException("Class format error, wrong descriptor");
}
signature = value;
}
}
public Class DeclaringType {
get {
return parent;
}
set {
parent = value;
}
}
public Descriptor Return {
get {
return ret;
}
set {
ret = value;
}
}
public Descriptor[] Arguments {
get {
return (Descriptor[]) arguments.ToArray(typeof(Descriptor));
}
}
public void AddArgument(Descriptor des)
{
arguments.Add(des);
}
public bool IsPublic {
get {
return (accessFlags & AccessFlag.ACC_PUBLIC) != 0;
}
}
public bool IsPrivate {
get {
return (accessFlags & AccessFlag.ACC_PRIVATE) != 0;
}
}
public bool IsProtected {
get {
return (accessFlags & AccessFlag.ACC_PROTECTED) != 0;
}
}
public bool IsStatic {
get {
return (accessFlags & AccessFlag.ACC_STATIC) != 0;
}
}
public bool IsFinal {
get {
return (accessFlags & AccessFlag.ACC_FINAL) != 0;
}
}
public bool IsSynchronized {
get {
return (accessFlags & AccessFlag.ACC_SYNCHRONIZED) != 0;
}
}
public bool IsNative {
get {
return (accessFlags & AccessFlag.ACC_NATIVE) != 0;
}
}
public bool IsAbstract {
get {
return (accessFlags & AccessFlag.ACC_ABSTRACT) != 0;
}
}
public bool IsStrict {
get {
return (accessFlags & AccessFlag.ACC_STRICT) != 0;
}
}
public MethodAttributes MethodAttributes {
get {
MethodAttributes attr;
if (IsPublic) {
attr = MethodAttributes.Public;
} else if (IsProtected) {
attr = MethodAttributes.Family;
} else if (IsPrivate) {
attr = MethodAttributes.Private;
} else { // package -> assembly (C# "internal")
attr = MethodAttributes.Assembly;
}
if (IsAbstract) {
attr |= MethodAttributes.Abstract;
}
if (IsStatic) {
attr |= MethodAttributes.Static;
} else {
if (IsFinal) {
attr |= MethodAttributes.Final;
} else {
attr |= MethodAttributes.Virtual;
}
}
return attr;
}
}
public enum AccessFlag
{
ACC_PUBLIC = 0x0001,
ACC_PRIVATE = 0x0002,
ACC_PROTECTED = 0x0004,
ACC_STATIC = 0x0008,
ACC_FINAL = 0x0010,
ACC_SYNCHRONIZED = 0x0020,
ACC_NATIVE = 0x0100,
ACC_ABSTRACT = 0x0400,
ACC_STRICT = 0x0800
}
public override string ToString()
{
string r = ret.ToString() + " " + name;
r += "(";
foreach (Descriptor d in arguments) {
r += d.ToString();
}
r += ")";
return r;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Collections;
using System.Threading;
using MyDownloader.Core.Concurrency;
namespace MyDownloader.Core
{
public class DownloadManager
{
#region Singleton
private static DownloadManager instance = new DownloadManager();
public static DownloadManager Instance
{
get
{
return instance;
}
}
#endregion
#region Fields
private List<Downloader> downloads = new List<Downloader>();
private int addBatchCount;
private ReaderWriterObjectLocker downloadListSync = new ReaderWriterObjectLocker();
#endregion
#region Properties
public event EventHandler BeginAddBatchDownloads;
public event EventHandler EndAddBatchDownloads;
public event EventHandler<DownloaderEventArgs> DownloadEnded;
public event EventHandler<DownloaderEventArgs> DownloadAdded;
public event EventHandler<DownloaderEventArgs> DownloadRemoved;
public ReadOnlyCollection<Downloader> Downloads
{
get
{
return downloads.AsReadOnly();
}
}
public double TotalDownloadRate
{
get
{
double total = 0;
using (LockDownloadList(false))
{
for (int i = 0; i < this.Downloads.Count; i++)
{
if (this.Downloads[i].State == DownloaderState.Working)
{
total += this.Downloads[i].Rate;
}
}
}
return total;
}
}
public int AddBatchCount
{
get
{
return addBatchCount;
}
}
#endregion
#region Methods
void downloader_StateChanged(object sender, EventArgs e)
{
Downloader downloader = (Downloader)sender;
if (downloader.State == DownloaderState.Ended ||
downloader.State == DownloaderState.EndedWithError)
{
OnDownloadEnded((Downloader)sender);
}
}
public IDisposable LockDownloadList(bool lockForWrite)
{
if (lockForWrite)
{
return downloadListSync.LockForWrite();
}
else
{
return downloadListSync.LockForRead();
}
}
public void RemoveDownload(int index)
{
RemoveDownload(downloads[index]);
}
public void RemoveDownload(Downloader downloader)
{
if (downloader.State != DownloaderState.NeedToPrepare ||
downloader.State != DownloaderState.Ended ||
downloader.State != DownloaderState.Paused)
{
downloader.Pause();
}
using (LockDownloadList(true))
{
downloads.Remove(downloader);
}
OnDownloadRemoved(downloader);
}
public void ClearEnded()
{
using (LockDownloadList(true))
{
for (int i = downloads.Count - 1; i >= 0; i--)
{
if (downloads[i].State == DownloaderState.Ended)
{
Downloader d = downloads[i];
downloads.RemoveAt(i);
OnDownloadRemoved(d);
}
}
}
}
public void PauseAll()
{
using (LockDownloadList(false))
{
for (int i = 0; i < this.Downloads.Count; i++)
{
this.Downloads[i].Pause();
}
}
}
public Downloader Add(ResourceLocation rl, ResourceLocation[] mirrors, string localFile, int segments, bool autoStart)
{
Downloader d = new Downloader(rl, mirrors, localFile, segments);
Add(d, autoStart);
return d;
}
public Downloader Add(ResourceLocation rl, ResourceLocation[] mirrors, string localFile, List<Segment> segments, RemoteFileInfo remoteInfo, int requestedSegmentCount, bool autoStart, DateTime createdDateTime)
{
Downloader d = new Downloader(rl, mirrors, localFile, segments, remoteInfo, requestedSegmentCount, createdDateTime);
Add(d, autoStart);
return d;
}
public void Add(Downloader downloader, bool autoStart)
{
downloader.StateChanged += new EventHandler(downloader_StateChanged);
using (LockDownloadList(true))
{
downloads.Add(downloader);
}
OnDownloadAdded(downloader, autoStart);
if (autoStart)
{
downloader.Start();
}
}
public virtual void OnBeginAddBatchDownloads()
{
addBatchCount++;
if (BeginAddBatchDownloads != null)
{
BeginAddBatchDownloads(this, EventArgs.Empty);
}
}
public virtual void OnEndAddBatchDownloads()
{
addBatchCount--;
if (EndAddBatchDownloads != null)
{
EndAddBatchDownloads(this, EventArgs.Empty);
}
}
protected virtual void OnDownloadEnded(Downloader d)
{
if (DownloadEnded != null)
{
DownloadEnded(this, new DownloaderEventArgs(d));
}
}
protected virtual void OnDownloadAdded(Downloader d, bool willStart)
{
if (DownloadAdded != null)
{
DownloadAdded(this, new DownloaderEventArgs(d, willStart));
}
}
protected virtual void OnDownloadRemoved(Downloader d)
{
if (DownloadRemoved != null)
{
DownloadRemoved(this, new DownloaderEventArgs(d));
}
}
public void SwapDownloads(int idx, bool isThreadSafe)
{
if (isThreadSafe)
{
InternalSwap(idx);
}
else
{
using (LockDownloadList(true))
{
InternalSwap(idx);
}
}
}
private void InternalSwap(int idx)
{
if (this.downloads.Count <= idx)
{
//return;
}
Downloader it1 = this.downloads[idx];
Downloader it2 = this.downloads[idx - 1];
this.downloads.RemoveAt(idx);
this.downloads.RemoveAt(idx - 1);
this.downloads.Insert(idx - 1, it1);
this.downloads.Insert(idx, it2);
}
#endregion
}
}
| |
//
// Encog(tm) Examples v3.0 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2011 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
namespace AIFH_Vol1_OCR
{
partial class OCRForm
{
/// <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.letters = new System.Windows.Forms.ListBox();
this.entry = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.btnDelete = new System.Windows.Forms.Button();
this.btnLoad = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnRecognize = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnSample = new System.Windows.Forms.Button();
this.sample = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// letters
//
this.letters.FormattingEnabled = true;
this.letters.Location = new System.Drawing.Point(12, 33);
this.letters.Name = "letters";
this.letters.ScrollAlwaysVisible = true;
this.letters.Size = new System.Drawing.Size(120, 95);
this.letters.TabIndex = 0;
this.letters.SelectedIndexChanged += new System.EventHandler(this.letters_SelectedIndexChanged);
//
// entry
//
this.entry.Location = new System.Drawing.Point(138, 33);
this.entry.Name = "entry";
this.entry.Size = new System.Drawing.Size(142, 95);
this.entry.TabIndex = 1;
this.entry.Paint += new System.Windows.Forms.PaintEventHandler(this.entry_Paint);
this.entry.MouseDown += new System.Windows.Forms.MouseEventHandler(this.entry_MouseDown);
this.entry.MouseMove += new System.Windows.Forms.MouseEventHandler(this.entry_MouseMove);
this.entry.MouseUp += new System.Windows.Forms.MouseEventHandler(this.entry_MouseUp);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(97, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Characters Known:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(135, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(110, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Draw Character Here:";
//
// btnDelete
//
this.btnDelete.Location = new System.Drawing.Point(12, 134);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(120, 23);
this.btnDelete.TabIndex = 4;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnLoad
//
this.btnLoad.Location = new System.Drawing.Point(12, 163);
this.btnLoad.Name = "btnLoad";
this.btnLoad.Size = new System.Drawing.Size(56, 23);
this.btnLoad.TabIndex = 5;
this.btnLoad.Text = "Load";
this.btnLoad.UseVisualStyleBackColor = true;
this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(74, 163);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(58, 23);
this.btnSave.TabIndex = 6;
this.btnSave.Text = "Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(138, 134);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(69, 23);
this.btnAdd.TabIndex = 8;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnRecognize
//
this.btnRecognize.Location = new System.Drawing.Point(213, 134);
this.btnRecognize.Name = "btnRecognize";
this.btnRecognize.Size = new System.Drawing.Size(67, 23);
this.btnRecognize.TabIndex = 9;
this.btnRecognize.Text = "Recognize";
this.btnRecognize.UseVisualStyleBackColor = true;
this.btnRecognize.Click += new System.EventHandler(this.btnRecognize_Click);
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(138, 163);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(69, 23);
this.btnClear.TabIndex = 10;
this.btnClear.Text = "Clear";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnSample
//
this.btnSample.Location = new System.Drawing.Point(213, 163);
this.btnSample.Name = "btnSample";
this.btnSample.Size = new System.Drawing.Size(69, 23);
this.btnSample.TabIndex = 11;
this.btnSample.Text = "Sample";
this.btnSample.UseVisualStyleBackColor = true;
this.btnSample.Click += new System.EventHandler(this.btnSample_Click);
//
// sample
//
this.sample.Location = new System.Drawing.Point(74, 192);
this.sample.Name = "sample";
this.sample.Size = new System.Drawing.Size(142, 124);
this.sample.TabIndex = 19;
this.sample.Paint += new System.Windows.Forms.PaintEventHandler(this.sample_Paint);
//
// OCRForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 331);
this.Controls.Add(this.sample);
this.Controls.Add(this.btnSample);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnRecognize);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.btnLoad);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.entry);
this.Controls.Add(this.letters);
this.Name = "OCRForm";
this.Text = "OCR Example";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox letters;
private System.Windows.Forms.Panel entry;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnLoad;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnRecognize;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnSample;
private System.Windows.Forms.Panel sample;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestMixOnesZerosUInt64()
{
var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanTwoComparisonOpTest__TestMixOnesZerosUInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private BooleanTwoComparisonOpTest__DataTable<UInt64, UInt64> _dataTable;
static BooleanTwoComparisonOpTest__TestMixOnesZerosUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestMixOnesZerosUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<UInt64, UInt64>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestMixOnesZeros(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestMixOnesZeros(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestMixOnesZeros(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestMixOnesZeros(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestMixOnesZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosUInt64();
var result = Sse41.TestMixOnesZeros(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestMixOnesZeros(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestMixOnesZeros)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace System.Net.Sockets
{
// The System.Net.Sockets.UdpClient class provides access to UDP services at a higher abstraction
// level than the System.Net.Sockets.Socket class. System.Net.Sockets.UdpClient is used to
// connect to a remote host and to receive connections from a remote client.
public class UdpClient : IDisposable
{
private const int MaxUDPSize = 0x10000;
private Socket _clientSocket;
private bool _active;
private byte[] _buffer = new byte[MaxUDPSize];
private AddressFamily _family = AddressFamily.InterNetwork;
// Initializes a new instance of the System.Net.Sockets.UdpClientclass.
public UdpClient() : this(AddressFamily.InterNetwork)
{
}
// Initializes a new instance of the System.Net.Sockets.UdpClientclass.
public UdpClient(AddressFamily family)
{
// Validate the address family.
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "UDP"), "family");
}
_family = family;
CreateClientSocket();
}
// Creates a new instance of the UdpClient class that communicates on the
// specified port number.
//
// NOTE: We should obsolete this. This also breaks IPv6-only scenarios.
// But fixing it has many complications that we have decided not
// to fix it and instead obsolete it later.
public UdpClient(int port) : this(port, AddressFamily.InterNetwork)
{
}
// Creates a new instance of the UdpClient class that communicates on the
// specified port number.
public UdpClient(int port, AddressFamily family)
{
// Validate input parameters.
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException("port");
}
// Validate the address family.
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.net_protocol_invalid_family, "family");
}
IPEndPoint localEP;
_family = family;
if (_family == AddressFamily.InterNetwork)
{
localEP = new IPEndPoint(IPAddress.Any, port);
}
else
{
localEP = new IPEndPoint(IPAddress.IPv6Any, port);
}
CreateClientSocket();
Client.Bind(localEP);
}
// Creates a new instance of the UdpClient class that communicates on the
// specified end point.
public UdpClient(IPEndPoint localEP)
{
// Validate input parameters.
if (localEP == null)
{
throw new ArgumentNullException("localEP");
}
// IPv6 Changes: Set the AddressFamily of this object before
// creating the client socket.
_family = localEP.AddressFamily;
CreateClientSocket();
Client.Bind(localEP);
}
// Used by the class to provide the underlying network socket.
public Socket Client
{
get
{
return _clientSocket;
}
set
{
_clientSocket = value;
}
}
// Used by the class to indicate that a connection to a remote host has been made.
protected bool Active
{
get
{
return _active;
}
set
{
_active = value;
}
}
public int Available
{
get
{
return _clientSocket.Available;
}
}
public short Ttl
{
get
{
return _clientSocket.Ttl;
}
set
{
_clientSocket.Ttl = value;
}
}
public bool DontFragment
{
get
{
return _clientSocket.DontFragment;
}
set
{
_clientSocket.DontFragment = value;
}
}
public bool MulticastLoopback
{
get
{
return _clientSocket.MulticastLoopback;
}
set
{
_clientSocket.MulticastLoopback = value;
}
}
public bool EnableBroadcast
{
get
{
return _clientSocket.EnableBroadcast;
}
set
{
_clientSocket.EnableBroadcast = value;
}
}
public bool ExclusiveAddressUse
{
get
{
return _clientSocket.ExclusiveAddressUse;
}
set
{
_clientSocket.ExclusiveAddressUse = value;
}
}
private bool _cleanedUp = false;
private void FreeResources()
{
// The only resource we need to free is the network stream, since this
// is based on the client socket, closing the stream will cause us
// to flush the data to the network, close the stream and (in the
// NetoworkStream code) close the socket as well.
if (_cleanedUp)
{
return;
}
Socket chkClientSocket = Client;
if (chkClientSocket != null)
{
// If the NetworkStream wasn't retrieved, the Socket might
// still be there and needs to be closed to release the effect
// of the Bind() call and free the bound IPEndPoint.
chkClientSocket.InternalShutdown(SocketShutdown.Both);
chkClientSocket.Dispose();
Client = null;
}
_cleanedUp = true;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("UdpClient::Dispose()");
}
FreeResources();
GC.SuppressFinalize(this);
}
}
private bool _isBroadcast;
private void CheckForBroadcast(IPAddress ipAddress)
{
// Here we check to see if the user is trying to use a Broadcast IP address
// we only detect IPAddress.Broadcast (which is not the only Broadcast address)
// and in that case we set SocketOptionName.Broadcast on the socket to allow its use.
// if the user really wants complete control over Broadcast addresses he needs to
// inherit from UdpClient and gain control over the Socket and do whatever is appropriate.
if (Client != null && !_isBroadcast && IsBroadcast(ipAddress))
{
// We need to set the Broadcast socket option.
// Note that once we set the option on the Socket we never reset it.
_isBroadcast = true;
Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
}
}
private bool IsBroadcast(IPAddress address)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
// No such thing as a broadcast address for IPv6.
return false;
}
else
{
return address.Equals(IPAddress.Broadcast);
}
}
internal IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (datagram == null)
{
throw new ArgumentNullException("datagram");
}
if (bytes > datagram.Length || bytes < 0)
{
throw new ArgumentOutOfRangeException("bytes");
}
if (_active && endPoint != null)
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
if (endPoint == null)
{
return Client.BeginSend(datagram, 0, bytes, SocketFlags.None, requestCallback, state);
}
CheckForBroadcast(endPoint.Address);
return Client.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state);
}
internal IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state)
{
if (_active && ((hostname != null) || (port != 0)))
{
// Do not allow sending packets to arbitrary host when connected.
throw new InvalidOperationException(SR.net_udpconnected);
}
IPEndPoint ipEndPoint = null;
if (hostname != null && port != 0)
{
IPAddress[] addresses = Dns.GetHostAddressesAsync(hostname).GetAwaiter().GetResult();
int i = 0;
for (; i < addresses.Length && addresses[i].AddressFamily != _family; i++)
{
}
if (addresses.Length == 0 || i == addresses.Length)
{
throw new ArgumentException(SR.net_invalidAddressList, "hostname");
}
CheckForBroadcast(addresses[i]);
ipEndPoint = new IPEndPoint(addresses[i], port);
}
return BeginSend(datagram, bytes, ipEndPoint, requestCallback, state);
}
internal IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state)
{
return BeginSend(datagram, bytes, null, requestCallback, state);
}
internal int EndSend(IAsyncResult asyncResult)
{
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_active)
{
return Client.EndSend(asyncResult);
}
else
{
return Client.EndSendTo(asyncResult);
}
}
internal IAsyncResult BeginReceive(AsyncCallback requestCallback, object state)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
// Due to the nature of the ReceiveFrom() call and the ref parameter convention,
// we need to cast an IPEndPoint to its base class EndPoint and cast it back down
// to IPEndPoint.
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
return Client.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state);
}
internal byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP)
{
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
EndPoint tempRemoteEP;
if (_family == AddressFamily.InterNetwork)
{
tempRemoteEP = IPEndPointStatics.Any;
}
else
{
tempRemoteEP = IPEndPointStatics.IPv6Any;
}
int received = Client.EndReceiveFrom(asyncResult, ref tempRemoteEP);
remoteEP = (IPEndPoint)tempRemoteEP;
// Because we don't return the actual length, we need to ensure the returned buffer
// has the appropriate length.
if (received < MaxUDPSize)
{
byte[] newBuffer = new byte[received];
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, received);
return newBuffer;
}
return _buffer;
}
// Joins a multicast address group.
public void JoinMulticastGroup(IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
// IPv6 Changes: we need to create the correct MulticastOption and
// must also check for address family compatibility.
if (multicastAddr.AddressFamily != _family)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr");
}
if (_family == AddressFamily.InterNetwork)
{
MulticastOption mcOpt = new MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcOpt);
}
else
{
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
mcOpt);
}
}
public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (_family != AddressFamily.InterNetwork)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
MulticastOption mcOpt = new MulticastOption(multicastAddr, localAddress);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcOpt);
}
// Joins an IPv6 multicast address group.
public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (ifindex < 0)
{
throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex");
}
// Ensure that this is an IPv6 client, otherwise throw WinSock
// Operation not supported socked exception.
if (_family != AddressFamily.InterNetworkV6)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
mcOpt);
}
// Joins a multicast address group with the specified time to live (TTL).
public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive)
{
// parameter validation;
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255))
{
throw new ArgumentOutOfRangeException("timeToLive");
}
// Join the Multicast Group.
JoinMulticastGroup(multicastAddr);
// Set Time To Live (TTL).
Client.SetSocketOption(
(_family == AddressFamily.InterNetwork) ? SocketOptionLevel.IP : SocketOptionLevel.IPv6,
SocketOptionName.MulticastTimeToLive,
timeToLive);
}
// Leaves a multicast address group.
public void DropMulticastGroup(IPAddress multicastAddr)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
// IPv6 Changes: we need to create the correct MulticastOption and
// must also check for address family compatibility.
if (multicastAddr.AddressFamily != _family)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), "multicastAddr");
}
if (_family == AddressFamily.InterNetwork)
{
MulticastOption mcOpt = new MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.DropMembership,
mcOpt);
}
else
{
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.DropMembership,
mcOpt);
}
}
// Leaves an IPv6 multicast address group.
public void DropMulticastGroup(IPAddress multicastAddr, int ifindex)
{
// Validate input parameters.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (multicastAddr == null)
{
throw new ArgumentNullException("multicastAddr");
}
if (ifindex < 0)
{
throw new ArgumentException(SR.net_value_cannot_be_negative, "ifindex");
}
// Ensure that this is an IPv6 client, otherwise throw WinSock
// Operation not supported socked exception.
if (_family != AddressFamily.InterNetworkV6)
{
throw new SocketException((int)SocketError.OperationNotSupported);
}
IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex);
Client.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.DropMembership,
mcOpt);
}
public Task<int> SendAsync(byte[] datagram, int bytes)
{
return Task<int>.Factory.FromAsync(
(targetDatagram, targetBytes, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, callback, state),
asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
datagram,
bytes,
state: this);
}
public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint)
{
return Task<int>.Factory.FromAsync(
(targetDatagram, targetBytes, targetEndpoint, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, targetEndpoint, callback, state),
asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
datagram,
bytes,
endPoint,
state: this);
}
public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port)
{
Tuple<byte[], string> packedArguments = Tuple.Create(datagram, hostname);
return Task<int>.Factory.FromAsync(
(targetPackedArguments, targetBytes, targetPort, callback, state) =>
{
byte[] targetDatagram = targetPackedArguments.Item1;
string targetHostname = targetPackedArguments.Item2;
var client = (UdpClient)state;
return client.BeginSend(targetDatagram, targetBytes, targetHostname, targetPort, callback, state);
},
asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
packedArguments,
bytes,
port,
state: this);
}
public Task<UdpReceiveResult> ReceiveAsync()
{
return Task<UdpReceiveResult>.Factory.FromAsync(
(callback, state) => ((UdpClient)state).BeginReceive(callback, state),
asyncResult =>
{
var client = (UdpClient)asyncResult.AsyncState;
IPEndPoint remoteEP = null;
byte[] buffer = client.EndReceive(asyncResult, ref remoteEP);
return new UdpReceiveResult(buffer, remoteEP);
},
state: this);
}
private void CreateClientSocket()
{
// Common initialization code.
//
// IPv6 Changes: Use the AddressFamily of this class rather than hardcode.
Client = new Socket(_family, SocketType.Dgram, ProtocolType.Udp);
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
using System;
using System.Diagnostics;
using SharpBox2D.Callbacks;
using SharpBox2D.Common;
namespace SharpBox2D.Collision.Broadphase
{
/**
* A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and
* ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by _fatAABBFactor
* so that the proxy AABB is bigger than the client object. This allows the client object to move by
* small amounts without triggering a tree update.
*
* @author daniel
*/
public class DynamicTree : BroadPhaseStrategy
{
public static int MAX_STACK_SIZE = 64;
public static int NULL_NODE = -1;
private DynamicTreeNode m_root;
private DynamicTreeNode[] m_nodes;
private int m_nodeCount;
private int m_nodeCapacity;
private int m_freeList;
private Vec2[] drawVecs = new Vec2[4];
private DynamicTreeNode[] nodeStack = new DynamicTreeNode[20];
private int nodeStackIndex = 0;
public DynamicTree()
{
m_root = null;
m_nodeCount = 0;
m_nodeCapacity = 16;
m_nodes = new DynamicTreeNode[16];
// Build a linked list for the free list.
for (int i = m_nodeCapacity - 1; i >= 0; i--)
{
m_nodes[i] = new DynamicTreeNode(i);
m_nodes[i].parent = (i == m_nodeCapacity - 1) ? null : m_nodes[i + 1];
m_nodes[i].height = -1;
}
m_freeList = 0;
for (int i = 0; i < drawVecs.Length; i++)
{
drawVecs[i] = new Vec2();
}
}
public int createProxy(AABB aabb, object userData)
{
Debug.Assert(aabb.isValid());
DynamicTreeNode node = allocateNode();
int proxyId = node.id;
// Fatten the aabb
AABB nodeAABB = node.aabb;
nodeAABB.lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension;
nodeAABB.lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension;
nodeAABB.upperBound.x = aabb.upperBound.x + Settings.aabbExtension;
nodeAABB.upperBound.y = aabb.upperBound.y + Settings.aabbExtension;
node.userData = userData;
insertLeaf(proxyId);
return proxyId;
}
public void destroyProxy(int proxyId)
{
Debug.Assert(0 <= proxyId && proxyId < m_nodeCapacity);
DynamicTreeNode node = m_nodes[proxyId];
Debug.Assert(node.child1 == null);
removeLeaf(node);
freeNode(node);
}
public bool moveProxy(int proxyId, AABB aabb, Vec2 displacement)
{
Debug.Assert(aabb.isValid());
Debug.Assert(0 <= proxyId && proxyId < m_nodeCapacity);
DynamicTreeNode node = m_nodes[proxyId];
Debug.Assert(node.child1 == null);
AABB nodeAABB = node.aabb;
// if (nodeAABB.contains(aabb)) {
if (nodeAABB.lowerBound.x <= aabb.lowerBound.x && nodeAABB.lowerBound.y <= aabb.lowerBound.y
&& aabb.upperBound.x <= nodeAABB.upperBound.x && aabb.upperBound.y <= nodeAABB.upperBound.y)
{
return false;
}
removeLeaf(node);
// Extend AABB
Vec2 lowerBound = nodeAABB.lowerBound;
Vec2 upperBound = nodeAABB.upperBound;
lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension;
lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension;
upperBound.x = aabb.upperBound.x + Settings.aabbExtension;
upperBound.y = aabb.upperBound.y + Settings.aabbExtension;
// Predict AABB displacement.
float dx = displacement.x*Settings.aabbMultiplier;
float dy = displacement.y*Settings.aabbMultiplier;
if (dx < 0.0f)
{
lowerBound.x += dx;
}
else
{
upperBound.x += dx;
}
if (dy < 0.0f)
{
lowerBound.y += dy;
}
else
{
upperBound.y += dy;
}
insertLeaf(proxyId);
return true;
}
public object getUserData(int proxyId)
{
Debug.Assert(0 <= proxyId && proxyId < m_nodeCapacity);
return m_nodes[proxyId].userData;
}
public AABB getFatAABB(int proxyId)
{
Debug.Assert(0 <= proxyId && proxyId < m_nodeCapacity);
return m_nodes[proxyId].aabb;
}
public void query(TreeCallback callback, AABB aabb)
{
Debug.Assert(aabb.isValid());
nodeStackIndex = 0;
nodeStack[nodeStackIndex++] = m_root;
while (nodeStackIndex > 0)
{
DynamicTreeNode node = nodeStack[--nodeStackIndex];
if (node == null)
{
continue;
}
if (AABB.testOverlap(node.aabb, aabb))
{
if (node.child1 == null)
{
bool proceed = callback.treeCallback(node.id);
if (!proceed)
{
return;
}
}
else
{
if (nodeStack.Length - nodeStackIndex - 2 <= 0)
{
DynamicTreeNode[] newBuffer = new DynamicTreeNode[nodeStack.Length*2];
Array.Copy(nodeStack, 0, newBuffer, 0, nodeStack.Length);
nodeStack = newBuffer;
}
nodeStack[nodeStackIndex++] = node.child1;
nodeStack[nodeStackIndex++] = node.child2;
}
}
}
}
private Vec2 r = new Vec2();
private AABB aabb = new AABB();
private RayCastInput subInput = new RayCastInput();
public void raycast(TreeRayCastCallback callback, RayCastInput input)
{
Vec2 p1 = input.p1;
Vec2 p2 = input.p2;
float p1x = p1.x, p2x = p2.x, p1y = p1.y, p2y = p2.y;
float vx, vy;
float rx, ry;
float absVx, absVy;
float cx, cy;
float hx, hy;
float tempx, tempy;
r.x = p2x - p1x;
r.y = p2y - p1y;
Debug.Assert((r.x*r.x + r.y*r.y) > 0f);
r.normalize();
rx = r.x;
ry = r.y;
// v is perpendicular to the segment.
vx = -1f*ry;
vy = 1f*rx;
absVx = MathUtils.abs(vx);
absVy = MathUtils.abs(vy);
// Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h)
float maxFraction = input.maxFraction;
// Build a bounding box for the segment.
AABB segAABB = aabb;
// Vec2 t = p1 + maxFraction * (p2 - p1);
// before inline
// temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1);
// Vec2.minToOut(p1, temp, segAABB.lowerBound);
// Vec2.maxToOut(p1, temp, segAABB.upperBound);
tempx = (p2x - p1x)*maxFraction + p1x;
tempy = (p2y - p1y)*maxFraction + p1y;
segAABB.lowerBound.x = p1x < tempx ? p1x : tempx;
segAABB.lowerBound.y = p1y < tempy ? p1y : tempy;
segAABB.upperBound.x = p1x > tempx ? p1x : tempx;
segAABB.upperBound.y = p1y > tempy ? p1y : tempy;
// end inline
nodeStackIndex = 0;
nodeStack[nodeStackIndex++] = m_root;
while (nodeStackIndex > 0)
{
DynamicTreeNode node = nodeStack[--nodeStackIndex];
if (node == null)
{
continue;
}
AABB nodeAABB = node.aabb;
if (!AABB.testOverlap(nodeAABB, segAABB))
{
continue;
}
// Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h)
// node.aabb.getCenterToOut(c);
// node.aabb.getExtentsToOut(h);
cx = (nodeAABB.lowerBound.x + nodeAABB.upperBound.x)*.5f;
cy = (nodeAABB.lowerBound.y + nodeAABB.upperBound.y)*.5f;
hx = (nodeAABB.upperBound.x - nodeAABB.lowerBound.x)*.5f;
hy = (nodeAABB.upperBound.y - nodeAABB.lowerBound.y)*.5f;
tempx = p1x - cx;
tempy = p1y - cy;
float separation = MathUtils.abs(vx*tempx + vy*tempy) - (absVx*hx + absVy*hy);
if (separation > 0.0f)
{
continue;
}
if (node.child1 == null)
{
subInput.p1.x = p1x;
subInput.p1.y = p1y;
subInput.p2.x = p2x;
subInput.p2.y = p2y;
subInput.maxFraction = maxFraction;
float value = callback.raycastCallback(subInput, node.id);
if (value == 0.0f)
{
// The client has terminated the ray cast.
return;
}
if (value > 0.0f)
{
// Update segment bounding box.
maxFraction = value;
// temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1);
// Vec2.minToOut(p1, temp, segAABB.lowerBound);
// Vec2.maxToOut(p1, temp, segAABB.upperBound);
tempx = (p2x - p1x)*maxFraction + p1x;
tempy = (p2y - p1y)*maxFraction + p1y;
segAABB.lowerBound.x = p1x < tempx ? p1x : tempx;
segAABB.lowerBound.y = p1y < tempy ? p1y : tempy;
segAABB.upperBound.x = p1x > tempx ? p1x : tempx;
segAABB.upperBound.y = p1y > tempy ? p1y : tempy;
}
}
else
{
if (nodeStack.Length - nodeStackIndex - 2 <= 0)
{
DynamicTreeNode[] newBuffer = new DynamicTreeNode[nodeStack.Length*2];
Array.Copy(nodeStack, 0, newBuffer, 0, nodeStack.Length);
nodeStack = newBuffer;
}
nodeStack[nodeStackIndex++] = node.child1;
nodeStack[nodeStackIndex++] = node.child2;
}
}
}
public int computeHeight()
{
return computeHeight(m_root);
}
private int computeHeight(DynamicTreeNode node)
{
Debug.Assert(0 <= node.id && node.id < m_nodeCapacity);
if (node.child1 == null)
{
return 0;
}
int height1 = computeHeight(node.child1);
int height2 = computeHeight(node.child2);
return 1 + MathUtils.max(height1, height2);
}
/**
* Validate this tree. For testing.
*/
public void validate()
{
validateStructure(m_root);
validateMetrics(m_root);
int freeCount = 0;
DynamicTreeNode freeNode = m_freeList != NULL_NODE ? m_nodes[m_freeList] : null;
while (freeNode != null)
{
Debug.Assert(0 <= freeNode.id && freeNode.id < m_nodeCapacity);
Debug.Assert(freeNode == m_nodes[freeNode.id]);
freeNode = freeNode.parent;
++freeCount;
}
Debug.Assert(getHeight() == computeHeight());
Debug.Assert(m_nodeCount + freeCount == m_nodeCapacity);
}
public int getHeight()
{
if (m_root == null)
{
return 0;
}
return m_root.height;
}
public int getMaxBalance()
{
int maxBalance = 0;
for (int i = 0; i < m_nodeCapacity; ++i)
{
DynamicTreeNode node = m_nodes[i];
if (node.height <= 1)
{
continue;
}
Debug.Assert(node.child1 == null == false);
DynamicTreeNode child1 = node.child1;
DynamicTreeNode child2 = node.child2;
int balance = MathUtils.abs(child2.height - child1.height);
maxBalance = MathUtils.max(maxBalance, balance);
}
return maxBalance;
}
public float getAreaRatio()
{
if (m_root == null)
{
return 0.0f;
}
DynamicTreeNode root = m_root;
float rootArea = root.aabb.getPerimeter();
float totalArea = 0.0f;
for (int i = 0; i < m_nodeCapacity; ++i)
{
DynamicTreeNode node = m_nodes[i];
if (node.height < 0)
{
// Free node in pool
continue;
}
totalArea += node.aabb.getPerimeter();
}
return totalArea/rootArea;
}
/**
* Build an optimal tree. Very expensive. For testing.
*/
public void rebuildBottomUp()
{
int[] nodes = new int[m_nodeCount];
int count = 0;
// Build array of leaves. Free the rest.
for (int i = 0; i < m_nodeCapacity; ++i)
{
if (m_nodes[i].height < 0)
{
// free node in pool
continue;
}
DynamicTreeNode node = m_nodes[i];
if (node.child1 == null)
{
node.parent = null;
nodes[count] = i;
++count;
}
else
{
freeNode(node);
}
}
AABB b = new AABB();
while (count > 1)
{
float minCost = float.MaxValue;
int iMin = -1, jMin = -1;
for (int i = 0; i < count; ++i)
{
AABB aabbi = m_nodes[nodes[i]].aabb;
for (int j = i + 1; j < count; ++j)
{
AABB aabbj = m_nodes[nodes[j]].aabb;
b.combine(aabbi, aabbj);
float cost = b.getPerimeter();
if (cost < minCost)
{
iMin = i;
jMin = j;
minCost = cost;
}
}
}
int index1 = nodes[iMin];
int index2 = nodes[jMin];
DynamicTreeNode child1 = m_nodes[index1];
DynamicTreeNode child2 = m_nodes[index2];
DynamicTreeNode parent = allocateNode();
parent.child1 = child1;
parent.child2 = child2;
parent.height = 1 + MathUtils.max(child1.height, child2.height);
parent.aabb.combine(child1.aabb, child2.aabb);
parent.parent = null;
child1.parent = parent;
child2.parent = parent;
nodes[jMin] = nodes[count - 1];
nodes[iMin] = parent.id;
--count;
}
m_root = m_nodes[nodes[0]];
validate();
}
private DynamicTreeNode allocateNode()
{
if (m_freeList == NULL_NODE)
{
Debug.Assert(m_nodeCount == m_nodeCapacity);
DynamicTreeNode[] old = m_nodes;
m_nodeCapacity *= 2;
m_nodes = new DynamicTreeNode[m_nodeCapacity];
Array.Copy(old, 0, m_nodes, 0, old.Length);
// Build a linked list for the free list.
for (int i = m_nodeCapacity - 1; i >= m_nodeCount; i--)
{
m_nodes[i] = new DynamicTreeNode(i);
m_nodes[i].parent = (i == m_nodeCapacity - 1) ? null : m_nodes[i + 1];
m_nodes[i].height = -1;
}
m_freeList = m_nodeCount;
}
int nodeId = m_freeList;
DynamicTreeNode treeNode = m_nodes[nodeId];
m_freeList = treeNode.parent != null ? treeNode.parent.id : NULL_NODE;
treeNode.parent = null;
treeNode.child1 = null;
treeNode.child2 = null;
treeNode.height = 0;
treeNode.userData = null;
++m_nodeCount;
return treeNode;
}
/**
* returns a node to the pool
*/
private void freeNode(DynamicTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(0 < m_nodeCount);
node.parent = m_freeList != NULL_NODE ? m_nodes[m_freeList] : null;
node.height = -1;
m_freeList = node.id;
m_nodeCount--;
}
private AABB combinedAABB = new AABB();
private void insertLeaf(int leaf_index)
{
DynamicTreeNode leaf = m_nodes[leaf_index];
if (m_root == null)
{
m_root = leaf;
m_root.parent = null;
return;
}
// find the best sibling
AABB leafAABB = leaf.aabb;
DynamicTreeNode index = m_root;
while (index.child1 != null)
{
DynamicTreeNode node = index;
DynamicTreeNode child1 = node.child1;
DynamicTreeNode child2 = node.child2;
float area = node.aabb.getPerimeter();
combinedAABB.combine(node.aabb, leafAABB);
float combinedArea = combinedAABB.getPerimeter();
// Cost of creating a new parent for this node and the new leaf
float cost = 2.0f*combinedArea;
// Minimum cost of pushing the leaf further down the tree
float inheritanceCost = 2.0f*(combinedArea - area);
// Cost of descending into child1
float cost1;
if (child1.child1 == null)
{
combinedAABB.combine(leafAABB, child1.aabb);
cost1 = combinedAABB.getPerimeter() + inheritanceCost;
}
else
{
combinedAABB.combine(leafAABB, child1.aabb);
float oldArea = child1.aabb.getPerimeter();
float newArea = combinedAABB.getPerimeter();
cost1 = (newArea - oldArea) + inheritanceCost;
}
// Cost of descending into child2
float cost2;
if (child2.child1 == null)
{
combinedAABB.combine(leafAABB, child2.aabb);
cost2 = combinedAABB.getPerimeter() + inheritanceCost;
}
else
{
combinedAABB.combine(leafAABB, child2.aabb);
float oldArea = child2.aabb.getPerimeter();
float newArea = combinedAABB.getPerimeter();
cost2 = newArea - oldArea + inheritanceCost;
}
// Descend according to the minimum cost.
if (cost < cost1 && cost < cost2)
{
break;
}
// Descend
if (cost1 < cost2)
{
index = child1;
}
else
{
index = child2;
}
}
DynamicTreeNode sibling = index;
DynamicTreeNode oldParent = m_nodes[sibling.id].parent;
DynamicTreeNode newParent = allocateNode();
newParent.parent = oldParent;
newParent.userData = null;
newParent.aabb.combine(leafAABB, sibling.aabb);
newParent.height = sibling.height + 1;
if (oldParent != null)
{
// The sibling was not the root.
if (oldParent.child1 == sibling)
{
oldParent.child1 = newParent;
}
else
{
oldParent.child2 = newParent;
}
newParent.child1 = sibling;
newParent.child2 = leaf;
sibling.parent = newParent;
leaf.parent = newParent;
}
else
{
// The sibling was the root.
newParent.child1 = sibling;
newParent.child2 = leaf;
sibling.parent = newParent;
leaf.parent = newParent;
m_root = newParent;
}
// Walk back up the tree fixing heights and AABBs
index = leaf.parent;
while (index != null)
{
index = balance(index);
DynamicTreeNode child1 = index.child1;
DynamicTreeNode child2 = index.child2;
Debug.Assert(child1 != null);
Debug.Assert(child2 != null);
index.height = 1 + MathUtils.max(child1.height, child2.height);
index.aabb.combine(child1.aabb, child2.aabb);
index = index.parent;
}
// validate();
}
private void removeLeaf(DynamicTreeNode leaf)
{
if (leaf == m_root)
{
m_root = null;
return;
}
DynamicTreeNode parent = leaf.parent;
DynamicTreeNode grandParent = parent.parent;
DynamicTreeNode sibling;
if (parent.child1 == leaf)
{
sibling = parent.child2;
}
else
{
sibling = parent.child1;
}
if (grandParent != null)
{
// Destroy parent and connect sibling to grandParent.
if (grandParent.child1 == parent)
{
grandParent.child1 = sibling;
}
else
{
grandParent.child2 = sibling;
}
sibling.parent = grandParent;
freeNode(parent);
// Adjust ancestor bounds.
DynamicTreeNode index = grandParent;
while (index != null)
{
index = balance(index);
DynamicTreeNode child1 = index.child1;
DynamicTreeNode child2 = index.child2;
index.aabb.combine(child1.aabb, child2.aabb);
index.height = 1 + MathUtils.max(child1.height, child2.height);
index = index.parent;
}
}
else
{
m_root = sibling;
sibling.parent = null;
freeNode(parent);
}
// validate();
}
// Perform a left or right rotation if node A is imbalanced.
// Returns the new root index.
private DynamicTreeNode balance(DynamicTreeNode iA)
{
Debug.Assert(iA != null);
DynamicTreeNode A = iA;
if (A.child1 == null || A.height < 2)
{
return iA;
}
DynamicTreeNode iB = A.child1;
DynamicTreeNode iC = A.child2;
Debug.Assert(0 <= iB.id && iB.id < m_nodeCapacity);
Debug.Assert(0 <= iC.id && iC.id < m_nodeCapacity);
DynamicTreeNode B = iB;
DynamicTreeNode C = iC;
int balance = C.height - B.height;
// Rotate C up
if (balance > 1)
{
DynamicTreeNode iF = C.child1;
DynamicTreeNode iG = C.child2;
DynamicTreeNode F = iF;
DynamicTreeNode G = iG;
Debug.Assert(F != null);
Debug.Assert(G != null);
Debug.Assert(0 <= iF.id && iF.id < m_nodeCapacity);
Debug.Assert(0 <= iG.id && iG.id < m_nodeCapacity);
// Swap A and C
C.child1 = iA;
C.parent = A.parent;
A.parent = iC;
// A's old parent should point to C
if (C.parent != null)
{
if (C.parent.child1 == iA)
{
C.parent.child1 = iC;
}
else
{
Debug.Assert(C.parent.child2 == iA);
C.parent.child2 = iC;
}
}
else
{
m_root = iC;
}
// Rotate
if (F.height > G.height)
{
C.child2 = iF;
A.child2 = iG;
G.parent = iA;
A.aabb.combine(B.aabb, G.aabb);
C.aabb.combine(A.aabb, F.aabb);
A.height = 1 + MathUtils.max(B.height, G.height);
C.height = 1 + MathUtils.max(A.height, F.height);
}
else
{
C.child2 = iG;
A.child2 = iF;
F.parent = iA;
A.aabb.combine(B.aabb, F.aabb);
C.aabb.combine(A.aabb, G.aabb);
A.height = 1 + MathUtils.max(B.height, F.height);
C.height = 1 + MathUtils.max(A.height, G.height);
}
return iC;
}
// Rotate B up
if (balance < -1)
{
DynamicTreeNode iD = B.child1;
DynamicTreeNode iE = B.child2;
DynamicTreeNode D = iD;
DynamicTreeNode E = iE;
Debug.Assert(0 <= iD.id && iD.id < m_nodeCapacity);
Debug.Assert(0 <= iE.id && iE.id < m_nodeCapacity);
// Swap A and B
B.child1 = iA;
B.parent = A.parent;
A.parent = iB;
// A's old parent should point to B
if (B.parent != null)
{
if (B.parent.child1 == iA)
{
B.parent.child1 = iB;
}
else
{
Debug.Assert(B.parent.child2 == iA);
B.parent.child2 = iB;
}
}
else
{
m_root = iB;
}
// Rotate
if (D.height > E.height)
{
B.child2 = iD;
A.child1 = iE;
E.parent = iA;
A.aabb.combine(C.aabb, E.aabb);
B.aabb.combine(A.aabb, D.aabb);
A.height = 1 + MathUtils.max(C.height, E.height);
B.height = 1 + MathUtils.max(A.height, D.height);
}
else
{
B.child2 = iE;
A.child1 = iD;
D.parent = iA;
A.aabb.combine(C.aabb, D.aabb);
B.aabb.combine(A.aabb, E.aabb);
A.height = 1 + MathUtils.max(C.height, D.height);
B.height = 1 + MathUtils.max(A.height, E.height);
}
return iB;
}
return iA;
}
private void validateStructure(DynamicTreeNode node)
{
if (node == null)
{
return;
}
Debug.Assert(node == m_nodes[node.id]);
if (node == m_root)
{
Debug.Assert(node.parent == null);
}
DynamicTreeNode child1 = node.child1;
DynamicTreeNode child2 = node.child2;
if (node.child1 == null)
{
Debug.Assert(child1 == null);
Debug.Assert(child2 == null);
Debug.Assert(node.height == 0);
return;
}
Debug.Assert(child1 != null && 0 <= child1.id && child1.id < m_nodeCapacity);
Debug.Assert(child2 != null && 0 <= child2.id && child2.id < m_nodeCapacity);
Debug.Assert(child1.parent == node);
Debug.Assert(child2.parent == node);
validateStructure(child1);
validateStructure(child2);
}
private void validateMetrics(DynamicTreeNode node)
{
if (node == null)
{
return;
}
DynamicTreeNode child1 = node.child1;
DynamicTreeNode child2 = node.child2;
if (node.child1 == null)
{
Debug.Assert(child1 == null);
Debug.Assert(child2 == null);
Debug.Assert(node.height == 0);
return;
}
Debug.Assert(child1 != null && 0 <= child1.id && child1.id < m_nodeCapacity);
Debug.Assert(child2 != null && 0 <= child2.id && child2.id < m_nodeCapacity);
int height1 = child1.height;
int height2 = child2.height;
int height;
height = 1 + MathUtils.max(height1, height2);
Debug.Assert(node.height == height);
AABB aabb = new AABB();
aabb.combine(child1.aabb, child2.aabb);
Debug.Assert(aabb.lowerBound.Equals(node.aabb.lowerBound));
Debug.Assert(aabb.upperBound.Equals(node.aabb.upperBound));
validateMetrics(child1);
validateMetrics(child2);
}
public void drawTree(DebugDraw argDraw)
{
if (m_root == null)
{
return;
}
int height = computeHeight();
drawTree(argDraw, m_root, 0, height);
}
private Color4f color = new Color4f();
private Vec2 textVec = new Vec2();
public void drawTree(DebugDraw argDraw, DynamicTreeNode node, int spot, int height)
{
node.aabb.getVertices(drawVecs);
color.set(1, (height - spot)*1f/height, (height - spot)*1f/height);
argDraw.drawPolygon(drawVecs, 4, color);
argDraw.getViewportTranform().getWorldToScreen(node.aabb.upperBound, textVec);
argDraw.drawString(textVec.x, textVec.y, node.id + "-" + (spot + 1) + "/" + height, color);
if (node.child1 != null)
{
drawTree(argDraw, node.child1, spot + 1, height);
}
if (node.child2 != null)
{
drawTree(argDraw, node.child2, spot + 1, height);
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
using SR = System.Reflection;
using Mono.Collections.Generic;
namespace Mono.Cecil.Cil {
[StructLayout (LayoutKind.Sequential)]
public struct ImageDebugDirectory {
public int Characteristics;
public int TimeDateStamp;
public short MajorVersion;
public short MinorVersion;
public int Type;
public int SizeOfData;
public int AddressOfRawData;
public int PointerToRawData;
}
public sealed class Scope : IVariableDefinitionProvider {
Instruction start;
Instruction end;
Collection<Scope> scopes;
Collection<VariableDefinition> variables;
public Instruction Start {
get { return start; }
set { start = value; }
}
public Instruction End {
get { return end; }
set { end = value; }
}
public bool HasScopes {
get { return !scopes.IsNullOrEmpty (); }
}
public Collection<Scope> Scopes {
get {
if (scopes == null)
scopes = new Collection<Scope> ();
return scopes;
}
}
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
variables = new Collection<VariableDefinition> ();
return variables;
}
}
}
public struct InstructionSymbol {
public readonly int Offset;
public readonly SequencePoint SequencePoint;
public InstructionSymbol (int offset, SequencePoint sequencePoint)
{
this.Offset = offset;
this.SequencePoint = sequencePoint;
}
}
public sealed class MethodSymbols {
internal int code_size;
internal string method_name;
internal MetadataToken method_token;
internal MetadataToken local_var_token;
internal Collection<VariableDefinition> variables;
internal Collection<InstructionSymbol> instructions;
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get {
if (variables == null)
variables = new Collection<VariableDefinition> ();
return variables;
}
}
public Collection<InstructionSymbol> Instructions {
get {
if (instructions == null)
instructions = new Collection<InstructionSymbol> ();
return instructions;
}
}
public int CodeSize {
get { return code_size; }
}
public string MethodName {
get { return method_name; }
}
public MetadataToken MethodToken {
get { return method_token; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
}
internal MethodSymbols (string methodName)
{
this.method_name = methodName;
}
public MethodSymbols (MetadataToken methodToken)
{
this.method_token = methodToken;
}
}
public delegate Instruction InstructionMapper (int offset);
public interface ISymbolReader : IDisposable {
bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header);
void Read (MethodBody body, InstructionMapper mapper);
void Read (MethodSymbols symbols);
}
public interface ISymbolReaderProvider {
ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName);
ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream);
}
static class SymbolProvider {
static readonly string symbol_kind = Type.GetType ("Mono.Runtime") != null ? "Mdb" : "Pdb";
static SR.AssemblyName GetPlatformSymbolAssemblyName ()
{
var cecil_name = typeof (SymbolProvider).Assembly.GetName ();
var name = new SR.AssemblyName {
Name = "Mono.Cecil." + symbol_kind,
Version = cecil_name.Version,
};
name.SetPublicKeyToken (cecil_name.GetPublicKeyToken ());
return name;
}
static Type GetPlatformType (string fullname)
{
var type = Type.GetType (fullname);
if (type != null)
return type;
var assembly_name = GetPlatformSymbolAssemblyName ();
type = Type.GetType (fullname + ", " + assembly_name.FullName);
if (type != null)
return type;
try {
var assembly = SR.Assembly.Load (assembly_name);
if (assembly != null)
return assembly.GetType (fullname);
} catch (FileNotFoundException) {
#if !CF
} catch (FileLoadException) {
#endif
}
return null;
}
static ISymbolReaderProvider reader_provider;
public static ISymbolReaderProvider GetPlatformReaderProvider ()
{
if (reader_provider != null)
return reader_provider;
var type = GetPlatformType (GetProviderTypeName ("ReaderProvider"));
if (type == null)
return null;
return reader_provider = (ISymbolReaderProvider) Activator.CreateInstance (type);
}
static string GetProviderTypeName (string name)
{
return "Mono.Cecil." + symbol_kind + "." + symbol_kind + name;
}
#if !READ_ONLY
static ISymbolWriterProvider writer_provider;
public static ISymbolWriterProvider GetPlatformWriterProvider ()
{
if (writer_provider != null)
return writer_provider;
var type = GetPlatformType (GetProviderTypeName ("WriterProvider"));
if (type == null)
return null;
return writer_provider = (ISymbolWriterProvider) Activator.CreateInstance (type);
}
#endif
}
#if !READ_ONLY
public interface ISymbolWriter : IDisposable {
bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header);
void Write (MethodBody body);
void Write (MethodSymbols symbols);
}
public interface ISymbolWriterProvider {
ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName);
ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream);
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryDivideTests
{
#region Test methods
[Fact]
public static void CheckByteDivideTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteDivide(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteDivideTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteDivide(array[i], array[j]);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckUShortDivideTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckShortDivideTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckUIntDivideTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIntDivideTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckULongDivideTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckLongDivideTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatDivideTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleDivideTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalDivideTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalDivide(array[i], array[j], useInterpreter);
}
}
}
[Fact]
public static void CheckCharDivideTest()
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharDivide(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteDivide(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
private static void VerifySByteDivide(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
private static void VerifyUShortDivide(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Divide(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((ushort)(a / b), f());
}
private static void VerifyShortDivide(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Divide(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(unchecked((short)(a / b)), f());
}
private static void VerifyUIntDivide(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Divide(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyIntDivide(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Divide(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (b == -1 && a == int.MinValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyULongDivide(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Divide(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyLongDivide(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Divide(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (b == -1 && a == long.MinValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyFloatDivide(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Divide(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(a / b, f());
}
private static void VerifyDoubleDivide(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Divide(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(a / b, f());
}
private static void VerifyDecimalDivide(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Divide(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyCharDivide(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Divide(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Divide(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Divide(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("left", () => Expression.Divide(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
AssertExtensions.Throws<ArgumentException>("right", () => Expression.Divide(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e = Expression.Divide(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a / b)", e.ToString());
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.S3.Model
{
/// <summary>Rules Item
/// </summary>
public class LifecycleRule
{
private string id;
private string prefix;
private LifecycleRuleExpiration expiration;
private LifecycleRuleStatus status = LifecycleRuleStatus.Disabled;
private LifecycleTransition transition;
private LifecycleRuleNoncurrentVersionTransition noncurrentVersionTransition;
private LifecycleRuleNoncurrentVersionExpiration noncurrentVersionExpiration;
private List<LifecycleTransition> transitions;
private List<LifecycleRuleNoncurrentVersionTransition> noncurrentVersionTransitions;
/// <summary>
/// Defines the length of time, in days, before objects expire.
/// </summary>
public LifecycleRuleExpiration Expiration
{
get { return this.expiration; }
set { this.expiration = value; }
}
// Check to see if Expiration property is set
internal bool IsSetExpiration()
{
return this.expiration != null;
}
/// <summary>
/// Unique identifier for the rule. The value cannot be longer than 255 characters.
/// </summary>
public string Id
{
get { return this.id; }
set { this.id = value; }
}
// Check to see if ID property is set
internal bool IsSetId()
{
return this.id != null;
}
/// <summary>
/// Prefix identifying one or more objects to which the rule applies.
///
/// </summary>
public string Prefix
{
get { return this.prefix; }
set { this.prefix = value; }
}
// Check to see if Prefix property is set
internal bool IsSetPrefix()
{
return this.prefix != null;
}
/// <summary>
/// If 'Enabled', the rule is currently being applied. If 'Disabled', the rule is not currently being applied.
///
/// </summary>
public LifecycleRuleStatus Status
{
get { return this.status; }
set { this.status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this.status != null;
}
/// <summary>
/// The transition rule that describes when objects transition to a different storage class.
/// <para>
/// Lifecycle rules can now contain multiple transitions. This property is obsolete in favor of the Transitions property.
/// This property will aways get or set the the zeroth element in the Transitions collection.
/// </para>
/// </summary>
[Obsolete("The Transition property is now obsolete in favor the Transitions property.")]
public LifecycleTransition Transition
{
get
{
if (!this.IsSetTransitions())
return null;
return this.Transitions[0];
}
set
{
if (this.Transitions.Count == 0)
this.Transitions.Add(value);
else
this.Transitions[0] = value;
}
}
// Check to see if Transition property is set
internal bool IsSetTransition()
{
return this.transition != null;
}
/// <summary>
/// Defines the length of time, in days, before noncurrent versions expire.
/// </summary>
public LifecycleRuleNoncurrentVersionExpiration NoncurrentVersionExpiration
{
get { return this.noncurrentVersionExpiration; }
set { this.noncurrentVersionExpiration = value; }
}
// Check to see if Expiration property is set
internal bool IsSetNoncurrentVersionExpiration()
{
return this.noncurrentVersionExpiration != null;
}
/// <summary>
/// The transition rule that describes when noncurrent versions transition to
/// a different storage class.
/// <para>
/// Lifecycle rules can now contain multiple noncurrent version transitions. This property
/// is obsolete in favor of the NoncurrentVersionTransitions property.
/// This property will aways get or set the the zeroth element in the NoncurrentVersionTransitions collection.
/// </para>
/// </summary>
[Obsolete("The NoncurrentVersionTransition property is now obsolete in favor the NoncurrentVersionTransitions property.")]
public LifecycleRuleNoncurrentVersionTransition NoncurrentVersionTransition
{
get
{
if (!this.IsSetNoncurrentVersionTransitions())
return null;
return this.NoncurrentVersionTransitions[0];
}
set
{
if (this.NoncurrentVersionTransitions.Count == 0)
this.NoncurrentVersionTransitions.Add(value);
else
this.NoncurrentVersionTransitions[0] = value;
}
}
// Check to see if Transition property is set
internal bool IsSetNoncurrentVersionTransition()
{
return this.noncurrentVersionTransition != null;
}
/// <summary>
/// The transition rules that describe when objects transition to a different storage class.
/// </summary>
public List<LifecycleTransition> Transitions
{
get
{
if (this.transitions == null)
this.transitions = new List<LifecycleTransition>();
return this.transitions;
}
set { this.transitions = value; }
}
// Check to see if Transitions property is set
internal bool IsSetTransitions()
{
return this.transitions != null && this.transitions.Count > 0;
}
/// <summary>
/// The transition rules that describe when noncurrent versions transition to
/// a different storage class.
/// </summary>
public List<LifecycleRuleNoncurrentVersionTransition> NoncurrentVersionTransitions
{
get
{
if (this.noncurrentVersionTransitions == null)
this.noncurrentVersionTransitions = new List<LifecycleRuleNoncurrentVersionTransition>();
return this.noncurrentVersionTransitions;
}
set { this.noncurrentVersionTransitions = value; }
}
// Check to see if Transitions property is set
internal bool IsSetNoncurrentVersionTransitions()
{
return this.noncurrentVersionTransitions != null && this.noncurrentVersionTransitions.Count > 0;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Prominence")]
public class SgtProminence : MonoBehaviour
{
public static List<SgtProminence> AllProminences = new List<SgtProminence>();
public Texture MainTex;
public Color Color = Color.white;
public float Brightness = 1.0f;
public SgtRenderQueue RenderQueue = SgtRenderQueue.Transparent;
public int RenderQueueOffset;
[SgtSeedAttribute]
public int Seed;
public float InnerRadius = 1.0f;
public float OuterRadius = 2.0f;
public int PlaneCount = 8;
public int Detail = 10;
public bool FadeEdge;
public float FadePower = 2.0f;
public bool ClipNear;
public float ClipPower = 2.0f;
public float ObserverOffset;
public float Width
{
get
{
return OuterRadius - InnerRadius;
}
}
private bool dirty = true;
[System.NonSerialized]
private Mesh mesh;
[System.NonSerialized]
private Material material;
[SerializeField]
private List<SgtProminencePlane> planes = new List<SgtProminencePlane>();
private static List<string> keywords = new List<string>();
public void MarkAsDirty()
{
#if UNITY_EDITOR
SgtHelper.SetDirty(this);
#endif
dirty = true;
}
public void UpdateState()
{
UpdateDirty();
UpdateMaterial();
UpdatePlanes();
}
public void ObserverPreCull(SgtObserver observer)
{
if (ObserverOffset != 0.0f)
{
for (var i = planes.Count - 1; i >= 0; i--)
{
var plane = planes[i];
if (plane != null)
{
var planeTransform = plane.transform;
var oldPosition = planeTransform.position;
var observerDir = (oldPosition - observer.transform.position).normalized;
plane.TempPosition = oldPosition;
SgtHelper.BeginStealthSet(planeTransform);
{
planeTransform.position += observerDir * ObserverOffset;
}
SgtHelper.EndStealthSet();
}
}
}
}
public void ObserverPostRender(SgtObserver observer)
{
if (ObserverOffset != 0.0f)
{
for (var i = planes.Count - 1; i >= 0; i--)
{
var plane = planes[i];
if (plane != null)
{
var planeTransform = plane.transform;
SgtHelper.BeginStealthSet(planeTransform);
{
planeTransform.position = plane.TempPosition;
}
SgtHelper.EndStealthSet();
}
}
}
}
public static SgtProminence CreateProminence(Transform parent = null)
{
return CreateProminence(parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
public static SgtProminence CreateProminence(Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
var gameObject = SgtHelper.CreateGameObject("Prominence", parent, localPosition, localRotation, localScale);
var prominence = gameObject.AddComponent<SgtProminence>();
return prominence;
}
protected virtual void OnEnable()
{
AllProminences.Add(this);
for (var i = planes.Count - 1; i >= 0; i--)
{
var plane = planes[i];
if (plane != null)
{
plane.gameObject.SetActive(true);
}
}
}
protected virtual void OnDisable()
{
AllProminences.Remove(this);
for (var i = planes.Count - 1; i >= 0; i--)
{
var plane = planes[i];
if (plane != null)
{
plane.gameObject.SetActive(false);
}
}
}
protected virtual void OnDestroy()
{
SgtHelper.Destroy(material);
for (var i = planes.Count - 1; i >= 0; i--)
{
SgtProminencePlane.MarkForDestruction(planes[i]);
}
planes.Clear();
}
protected virtual void Update()
{
UpdateState();
}
#if UNITY_EDITOR
protected virtual void OnDrawGizmosSelected()
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireSphere(Vector3.zero, InnerRadius);
Gizmos.DrawWireSphere(Vector3.zero, OuterRadius);
}
#endif
private void UpdateDirty()
{
if (mesh == null || mesh.vertexCount == 0)
{
dirty = true;
}
if (dirty == true)
{
dirty = false;
RegenerateMesh();
}
}
private void UpdateMaterial()
{
if (material == null) material = SgtHelper.CreateTempMaterial(SgtHelper.ShaderNamePrefix + "Prominence");
var color = SgtHelper.Premultiply(SgtHelper.Brighten(Color, Brightness));
var renderQueue = (int)RenderQueue + RenderQueueOffset;
material.renderQueue = renderQueue;
material.SetTexture("_MainTex", MainTex);
material.SetColor("_Color", color);
material.SetVector("_WorldPosition", transform.position);
if (FadeEdge == true)
{
keywords.Add("SGT_A");
material.SetFloat("_FadePower", FadePower);
}
if (ClipNear == true)
{
keywords.Add("SGT_B");
material.SetFloat("_ClipPower", ClipPower);
}
SgtHelper.SetKeywords(material, keywords); keywords.Clear();
}
private void UpdatePlanes()
{
planes.RemoveAll(p => p == null);
if (PlaneCount != planes.Count)
{
SgtHelper.ResizeArrayTo(ref planes, PlaneCount, i => SgtProminencePlane.Create(this), p => SgtProminencePlane.Pool(p));
}
SgtHelper.BeginRandomSeed(Seed);
{
for (var i = planes.Count - 1; i >= 0; i--)
{
planes[i].ManualUpdate(mesh, material, Random.rotationUniform);
}
}
SgtHelper.EndRandomSeed();
}
private void RegenerateMesh()
{
mesh = SgtObjectPool<Mesh>.Add(mesh, m => m.Clear());
SgtProceduralMesh.Clear();
{
if (Detail >= 3)
{
var angleStep = SgtHelper.Divide(Mathf.PI * 2.0f, Detail);
var coordStep = SgtHelper.Reciprocal(Detail);
for (var i = 0; i <= Detail; i++)
{
var coord = coordStep * i;
var angle = angleStep * i;
var sin = Mathf.Sin(angle);
var cos = Mathf.Cos(angle);
var iPos = new Vector3(sin * InnerRadius, 0.0f, cos * InnerRadius);
var oPos = new Vector3(sin * OuterRadius, 0.0f, cos * OuterRadius);
SgtProceduralMesh.PushPosition(iPos);
SgtProceduralMesh.PushPosition(oPos);
SgtProceduralMesh.PushNormal(Vector3.up);
SgtProceduralMesh.PushNormal(Vector3.up);
SgtProceduralMesh.PushCoord1(0.0f, coord * InnerRadius);
SgtProceduralMesh.PushCoord1(1.0f, coord * OuterRadius);
SgtProceduralMesh.PushCoord2(InnerRadius, 0.0f);
SgtProceduralMesh.PushCoord2(OuterRadius, 0.0f);
}
}
}
SgtProceduralMesh.SplitStrip(HideFlags.DontSave);
mesh = SgtProceduralMesh.Pop(); SgtProceduralMesh.Discard();
}
#if UNITY_EDITOR
[UnityEditor.MenuItem(SgtHelper.GameObjectMenuPrefix + "Prominence", false, 10)]
public static void CreateProminenceMenuItem()
{
var prominence = CreateProminence(null);
SgtHelper.SelectAndPing(prominence);
}
#endif
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI
{
using System;
using NPOI.POIFS.Common;
using NPOI.Util;
using NPOI.OpenXml4Net.Exceptions;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using System.Collections.Generic;
using NPOI.OpenXml4Net;
using System.Reflection;
public abstract class POIXMLDocument : POIXMLDocumentPart
{
public static String DOCUMENT_CREATOR = "NPOI";
// OLE embeddings relation name
public static String OLE_OBJECT_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject";
// Embedded OPC documents relation name
public static String PACK_OBJECT_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package";
/** The OPC Package */
private OPCPackage pkg;
/**
* The properties of the OPC namespace, opened as needed
*/
private POIXMLProperties properties;
protected POIXMLDocument(OPCPackage pkg)
: base(pkg)
{
this.pkg = pkg;
}
/**
* Wrapper to open a namespace, returning an IOException
* in the event of a problem.
* Works around shortcomings in java's this() constructor calls
*/
public static OPCPackage OpenPackage(String path)
{
try
{
return OPCPackage.Open(path);
}
catch (InvalidFormatException e)
{
throw new IOException(e.ToString());
}
}
public OPCPackage Package
{
get
{
return this.pkg;
}
}
protected PackagePart CorePart
{
get
{
return GetPackagePart();
}
}
/**
* Retrieves all the PackageParts which are defined as
* relationships of the base document with the
* specified content type.
*/
protected PackagePart[] GetRelatedByType(String contentType)
{
PackageRelationshipCollection partsC =
GetPackagePart().GetRelationshipsByType(contentType);
PackagePart[] parts = new PackagePart[partsC.Size];
int count = 0;
foreach (PackageRelationship rel in partsC)
{
parts[count] = GetPackagePart().GetRelatedPart(rel);
count++;
}
return parts;
}
/**
* Checks that the supplied Stream (which MUST
* support mark and reSet, or be a PushbackStream)
* has a OOXML (zip) header at the start of it.
* If your Stream does not support mark / reSet,
* then wrap it in a PushBackStream, then be
* sure to always use that, and not the original!
* @param inp An Stream which supports either mark/reSet, or is a PushbackStream
*/
public static bool HasOOXMLHeader(Stream inp)
{
// We want to peek at the first 4 bytes
byte[] header = new byte[4];
IOUtils.ReadFully(inp, header);
// Wind back those 4 bytes
if (inp is PushbackStream)
{
PushbackStream pin = (PushbackStream)inp;
pin.Position = pin.Position - 4;
}
else
{
inp.Position = 0;
}
// Did it match the ooxml zip signature?
return (
header[0] == POIFSConstants.OOXML_FILE_HEADER[0] &&
header[1] == POIFSConstants.OOXML_FILE_HEADER[1] &&
header[2] == POIFSConstants.OOXML_FILE_HEADER[2] &&
header[3] == POIFSConstants.OOXML_FILE_HEADER[3]
);
}
/**
* Get the document properties. This gives you access to the
* core ooxml properties, and the extended ooxml properties.
*/
public POIXMLProperties GetProperties()
{
if (properties == null)
{
try
{
properties = new POIXMLProperties(pkg);
}
catch (Exception e)
{
throw new POIXMLException(e);
}
}
return properties;
}
/**
* Get the document's embedded files.
*/
public abstract List<PackagePart> GetAllEmbedds();
protected void Load(POIXMLFactory factory)
{
Dictionary<PackagePart, POIXMLDocumentPart> context = new Dictionary<PackagePart, POIXMLDocumentPart>();
try
{
Read(factory, context);
}
catch (OpenXml4NetException e)
{
throw new POIXMLException(e);
}
OnDocumentRead();
context.Clear();
}
/**
* Closes the underlying {@link OPCPackage} from which this
* document was read, if there is one
*/
public void Close()
{
if (pkg != null)
{
if (pkg.GetPackageAccess() == PackageAccess.READ)
{
pkg.Revert();
}
else
{
pkg.Close();
}
pkg = null;
}
}
/**
* Write out this document to an Outputstream.
*
* @param stream - the java Stream you wish to write the file to
*
* @exception IOException if anything can't be written.
*/
public void Write(Stream stream)
{
if (!this.GetProperties().CustomProperties.Contains("Generator"))
this.GetProperties().CustomProperties.AddProperty("Generator", "NPOI");
if (!this.GetProperties().CustomProperties.Contains("Generator Version"))
this.GetProperties().CustomProperties.AddProperty("Generator Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
//force all children to commit their Changes into the underlying OOXML Package
List<PackagePart> context = new List<PackagePart>();
OnSave(context);
context.Clear();
//save extended and custom properties
GetProperties().Commit();
Package.Save(stream);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Runtime.Remoting {
using System.Globalization;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.ConstrainedExecution;
using System.Reflection;
using System;
// IdentityHolder maintains a lookup service for remoting identities. The methods
// provided by it are used during calls to Wrap, UnWrap, Marshal, Unmarshal etc.
//
using System.Collections;
using System.Diagnostics.Contracts;
// This is just a internal struct to hold the various flags
// that get passed for different flavors of idtable operations
// just so that we do not have too many separate boolean parameters
// all over the place (eg. xxxIdentity(id,uri, true, false, true);)
internal struct IdOps
{
internal const int None = 0x00000000;
internal const int GenerateURI = 0x00000001;
internal const int StrongIdentity = 0x00000002;
internal static bool bStrongIdentity(int flags)
{
return (flags&StrongIdentity)!=0;
}
}
// Internal enum to specify options for SetIdentity
[Serializable]
internal enum DuplicateIdentityOption
{
Unique, // -throw an exception if there is already an identity in the table
UseExisting, // -if there is already an identity in the table, then use that one.
// (could happen in a Connect ----, but we don't care which identity we get)
} // enum DuplicateIdentityOption
internal sealed class IdentityHolder
{
// private static Timer CleanupTimer = null;
// private const int CleanupInterval = 60000; // 1 minute.
// private static Object staticSyncObject = new Object();
private static volatile int SetIDCount=0;
private const int CleanUpCountInterval = 0x40;
private const int INFINITE = 0x7fffffff;
private static Hashtable _URITable = new Hashtable();
private static volatile Context _cachedDefaultContext = null;
internal static Hashtable URITable
{
get { return _URITable; }
}
internal static Context DefaultContext
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_cachedDefaultContext == null)
{
_cachedDefaultContext = Thread.GetDomain().GetDefaultContext();
}
return _cachedDefaultContext;
}
}
// NOTE!!!: This must be used to convert any uri into something that can
// be used as a key in the URITable!!!
private static String MakeURIKey(String uri)
{
return Identity.RemoveAppNameOrAppGuidIfNecessary(
uri.ToLower(CultureInfo.InvariantCulture));
}
private static String MakeURIKeyNoLower(String uri)
{
return Identity.RemoveAppNameOrAppGuidIfNecessary(uri);
}
internal static ReaderWriterLock TableLock
{
get { return Thread.GetDomain().RemotingData.IDTableLock;}
}
// Cycles through the table periodically and cleans up expired entries.
//
private static void CleanupIdentities(Object state)
{
// <
Contract.Assert(
Thread.GetDomain().RemotingData.IDTableLock.IsWriterLockHeld,
"ID Table being cleaned up without taking a lock!");
IDictionaryEnumerator e = URITable.GetEnumerator();
ArrayList removeList = new ArrayList();
while (e.MoveNext())
{
Object o = e.Value;
WeakReference wr = o as WeakReference;
if ((null != wr) && (null == wr.Target))
{
removeList.Add(e.Key);
}
}
foreach (String key in removeList)
{
URITable.Remove(key);
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void FlushIdentityTable()
{
// We need to guarantee that finally is not interrupted so that the lock is released.
// TableLock has a long path without reliability contract. To avoid adding contract on
// the path, we will use ReaderWriterLock directly.
ReaderWriterLock rwlock = TableLock;
bool takeAndRelease = !rwlock.IsWriterLockHeld;
RuntimeHelpers.PrepareConstrainedRegions();
try{
if (takeAndRelease)
rwlock.AcquireWriterLock(INFINITE);
CleanupIdentities(null);
}
finally{
if(takeAndRelease && rwlock.IsWriterLockHeld){
rwlock.ReleaseWriterLock();
}
}
}
private IdentityHolder() { // this is a singleton object. Can't construct it.
}
// Looks up the identity corresponding to a URI.
//
[System.Security.SecurityCritical] // auto-generated
internal static Identity ResolveIdentity(String URI)
{
if (URI == null)
throw new ArgumentNullException("URI");
Contract.EndContractBlock();
Identity id;
// We need to guarantee that finally is not interrupted so that the lock is released.
// TableLock has a long path without reliability contract. To avoid adding contract on
// the path, we will use ReaderWriterLock directly.
ReaderWriterLock rwlock = TableLock;
bool takeAndRelease = !rwlock.IsReaderLockHeld;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (takeAndRelease)
rwlock.AcquireReaderLock(INFINITE);
Message.DebugOut("ResolveIdentity:: URI: " + URI + "\n");
Message.DebugOut("ResolveIdentity:: table.count: " + URITable.Count + "\n");
//Console.WriteLine("\n ResolveID: URI = " + URI);
// This may be called both in the client process and the server process (loopback case).
id = ResolveReference(URITable[MakeURIKey(URI)]);
}
finally
{
if (takeAndRelease && rwlock.IsReaderLockHeld){
rwlock.ReleaseReaderLock();
}
}
return id;
} // ResolveIdentity
// If the identity isn't found, this version will just return
// null instead of asserting (this version doesn't need to
// take a lock).
[System.Security.SecurityCritical] // auto-generated
internal static Identity CasualResolveIdentity(String uri)
{
if (uri == null)
return null;
Identity id = CasualResolveReference(URITable[MakeURIKeyNoLower(uri)]);
if (id == null) {
id = CasualResolveReference(URITable[MakeURIKey(uri)]);
if(id == null)
{
// Check if this a well-known object which needs to be faulted in
id = RemotingConfigHandler.CreateWellKnownObject(uri);
}
}
return id;
} // CasualResolveIdentity
private static Identity ResolveReference(Object o)
{
Contract.Assert(
TableLock.IsReaderLockHeld || TableLock.IsWriterLockHeld ,
"Should have locked the ID Table!");
WeakReference wr = o as WeakReference;
if (null != wr)
{
return((Identity) wr.Target);
}
else
{
return((Identity) o);
}
} // ResolveReference
private static Identity CasualResolveReference(Object o)
{
WeakReference wr = o as WeakReference;
if (null != wr)
{
return((Identity) wr.Target);
}
else
{
return((Identity) o);
}
} // CasualResolveReference
//
//
// This is typically called when we need to create/establish
// an identity for a serverObject.
[System.Security.SecurityCritical] // auto-generated
internal static ServerIdentity FindOrCreateServerIdentity(
MarshalByRefObject obj, String objURI, int flags)
{
Message.DebugOut("Entered FindOrCreateServerIdentity \n");
ServerIdentity srvID = null;
bool fServer;
srvID = (ServerIdentity) MarshalByRefObject.GetIdentity(obj, out fServer);
if (srvID == null)
{
// Create a new server identity and add it to the
// table. IdentityHolder will take care of ----s
Context serverCtx = null;
if (obj is ContextBoundObject)
{
serverCtx = Thread.CurrentContext;
}
else
{
serverCtx = DefaultContext;
}
Contract.Assert(null != serverCtx, "null != serverCtx");
ServerIdentity serverID = new ServerIdentity(obj, serverCtx);
// Set the identity depending on whether we have the server or proxy
if(fServer)
{
srvID = obj.__RaceSetServerIdentity(serverID);
Contract.Assert(srvID == MarshalByRefObject.GetIdentity(obj), "Bad ID state!" );
}
else
{
RealProxy rp = null;
rp = RemotingServices.GetRealProxy(obj);
Contract.Assert(null != rp, "null != rp");
rp.IdentityObject = serverID;
srvID = (ServerIdentity) rp.IdentityObject;
}
Message.DebugOut("Created ServerIdentity \n");
}
#if false
// Check that we are asked to create the identity for the same
// URI as the one already associated with the server object.
// It is an error to associate two URIs with the same server
// object
// GopalK: Try eliminating the test because it is also done by GetOrCreateIdentity
if ((null != objURI) && (null != srvID.ObjURI))
{
if (string.Compare(objURI, srvID.ObjURI, StringComparison.OrdinalIgnoreCase) == 0) // case-insensitive compare
{
Message.DebugOut("Trying to associate a URI with identity again .. throwing execption \n");
throw new RemotingException(
String.Format(
Environment.GetResourceString(
"Remoting_ResetURI"),
srvID.ObjURI, objURI));
}
}
#endif
// NOTE: for purely x-context cases we never execute this ...
// the server ID is not put in the ID table.
if ( IdOps.bStrongIdentity(flags) )
{
// We need to guarantee that finally is not interrupted so that the lock is released.
// TableLock has a long path without reliability contract. To avoid adding contract on
// the path, we will use ReaderWriterLock directly.
ReaderWriterLock rwlock = TableLock;
bool takeAndRelease = !rwlock.IsWriterLockHeld;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (takeAndRelease)
rwlock.AcquireWriterLock(INFINITE);
// It is possible that we are marshaling out of this app-domain
// for the first time. We need to do two things
// (1) If there is no URI associated with the identity then go ahead
// and generate one.
// (2) Add the identity to the URI -> Identity map if not already present
// (For purely x-context cases we don't need the URI)
// (3) If the object ref is null, then this object hasn't been
// marshalled yet.
// (4) if id was created through SetObjectUriForMarshal, it would be
// in the ID table
if ((srvID.ObjURI == null) ||
(srvID.IsInIDTable() == false))
{
// we are marshalling a server object, so there should not be a
// a different identity at this location.
SetIdentity(srvID, objURI, DuplicateIdentityOption.Unique);
}
// If the object is marked as disconnect, mark it as connected
if(srvID.IsDisconnected())
srvID.SetFullyConnected();
}
finally
{
if (takeAndRelease && rwlock.IsWriterLockHeld)
{
rwlock.ReleaseWriterLock();
}
}
}
Message.DebugOut("Leaving FindOrCreateServerIdentity \n");
Contract.Assert(null != srvID,"null != srvID");
return srvID;
}
//
//
// This is typically called when we are unmarshaling an objectref
// in order to create a client side identity for a remote server
// object.
[System.Security.SecurityCritical] // auto-generated
internal static Identity FindOrCreateIdentity(
String objURI, String URL, ObjRef objectRef)
{
Identity idObj = null;
Contract.Assert(null != objURI,"null != objURI");
bool bWellKnown = (URL != null);
// Lookup the object in the identity table
// for well-known objects we user the URL
// as the hash-key (instead of just the objUri)
idObj = ResolveIdentity(bWellKnown ? URL : objURI);
if (bWellKnown &&
(idObj != null) &&
(idObj is ServerIdentity))
{
// We are trying to do a connect to a server wellknown object.
throw new RemotingException(
String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString(
"Remoting_WellKnown_CantDirectlyConnect"),
URL));
}
if (null == idObj)
{
// There is no entry for this uri in the IdTable.
Message.DebugOut("RemotingService::FindOrCreateIdentity: Creating Identity\n");
// This identity is being encountered for the first time.
// We have to do the following things
// (1) Create an identity object for the proxy
// (2) Add the identity to the identity table
// (3) Create a proxy for the object represented by the objref
// Create a new identity
// <EMAIL>GopalK:</EMAIL> Identity should get only one string that is used for everything
idObj = new Identity(objURI, URL);
// We need to guarantee that finally is not interrupted so that the lock is released.
// TableLock has a long path without reliability contract. To avoid adding contract on
// the path, we will use ReaderWriterLock directly.
ReaderWriterLock rwlock = TableLock;
bool takeAndRelease = !rwlock.IsWriterLockHeld;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
// Add it to the identity table
if (takeAndRelease)
rwlock.AcquireWriterLock(INFINITE);
// SetIdentity will give the correct Id if we ----d
// between the ResolveIdentity call above and now.
// (we are unmarshaling, and the server should guarantee
// that the uri is unique, so we will use an existing identity
// in case of a ----)
idObj = SetIdentity(idObj, null, DuplicateIdentityOption.UseExisting);
idObj.RaceSetObjRef(objectRef);
}
finally
{
if (takeAndRelease && rwlock.IsWriterLockHeld)
{
rwlock.ReleaseWriterLock();
}
}
}
else
{
Message.DebugOut("RemotingService::FindOrCreateIdentity: Found Identity!\n");
}
Contract.Assert(null != idObj,"null != idObj");
return idObj;
}
// Creates an identity entry.
// This is used by Unmarshal and Marshal to generate the URI to identity
// mapping
//
//
[System.Security.SecurityCritical] // auto-generated
private static Identity SetIdentity(
Identity idObj, String URI, DuplicateIdentityOption duplicateOption)
{
// NOTE: This function assumes that a lock has been taken
// by the calling function
// idObj could be for a transparent proxy or a server object
Message.DebugOut("SetIdentity:: domainid: " + Thread.GetDomainID() + "\n");
Contract.Assert(null != idObj,"null != idObj");
// WriterLock must already be taken when SetIdentity is called!
Contract.Assert(
TableLock.IsWriterLockHeld,
"Should have write-locked the ID Table!");
// flag to denote that the id being set is a ServerIdentity
bool bServerIDSet = idObj is ServerIdentity;
if (null == idObj.URI)
{
// No URI has been associated with this identity. It must be a
// server identity getting marshaled out of the app domain for
// the first time.
Contract.Assert(bServerIDSet,"idObj should be ServerIdentity");
// Set the URI on the idObj (generating one if needed)
idObj.SetOrCreateURI(URI);
// If objectref is non-null make sure both have same URIs
// (the URI in the objectRef could have potentially been reset
// in a past external call to Disconnect()
if (idObj.ObjectRef != null)
{
idObj.ObjectRef.URI = idObj.URI;
}
Message.DebugOut("SetIdentity: Generated URI " + URI + " for identity");
}
// If we have come this far then there is no URI to identity
// mapping present. Go ahead and create one.
// ID should have a URI by now.
Contract.Assert(null != idObj.URI,"null != idObj.URI");
// See if this identity is already present in the Uri table
String uriKey = MakeURIKey(idObj.URI);
Object o = URITable[uriKey];
// flag to denote that the id found in the table is a ServerIdentity
bool bServerID;
if (null != o)
{
// We found an identity (or a WeakRef to one) for the URI provided
WeakReference wr = o as WeakReference;
Identity idInTable = null;
if (wr != null)
{
// The object we found is a weak referece to an identity
// This could be an identity for a client side
// proxy
// OR
// a server identity which has been weakened since its life
// is over.
idInTable = (Identity) wr.Target;
bServerID = idInTable is ServerIdentity;
// If we find a weakRef for a ServerId we will be converting
// it to a strong one before releasing the IdTable lock.
Contract.Assert(
(idInTable == null)||
(!bServerID || idInTable.IsRemoteDisconnected()),
"Expect to find WeakRef only for remotely disconnected ids");
// We could find a weakRef to a client ID that does not
// match the idObj .. but that is a handled ---- case
// during Unmarshaling .. SetIdentity() will return the ID
// from the table to the caller.
}
else
{
// We found a non-weak (strong) Identity for the URI
idInTable = (Identity) o;
bServerID = idInTable is ServerIdentity;
//We dont put strong refs to client "Identity"s in the table
Contract.Assert(
bServerID,
"Found client side strong ID in the table");
}
if ((idInTable != null) && (idInTable != idObj))
{
// We are trying to add another identity for the same URI
switch (duplicateOption)
{
case DuplicateIdentityOption.Unique:
{
String tempURI = idObj.URI;
// Throw an exception to indicate the error since this could
// be caused by a user trying to marshal two objects with the same
// URI
throw new RemotingException(
Environment.GetResourceString("Remoting_URIClash",
tempURI));
} // case DuplicateIdentityOption.Unique
case DuplicateIdentityOption.UseExisting:
{
// This would be a case where our thread lost the ----
// we will return the one found in the table
idObj = idInTable;
break;
} // case DuplicateIdentityOption.UseExisting:
default:
{
Contract.Assert(false, "Invalid DuplicateIdentityOption");
break;
}
} // switch (duplicateOption)
}
else
if (wr!=null)
{
// We come here if we found a weakRef in the table but
// the target object had been cleaned up
// OR
// If there was a weakRef in the table and the target
// object matches the idObj just passed in
// Strengthen the entry if it a ServerIdentity.
if (bServerID)
{
URITable[uriKey] = idObj;
}
else
{
// For client IDs associate the table entry
// with the one passed in.
// (If target was null we would set it ...
// if was non-null then it matches idObj anyway)
wr.Target = idObj;
}
}
}
else
{
// We did not find an identity entry for the URI
Object addMe = null;
if (bServerIDSet)
{
addMe = idObj;
((ServerIdentity)idObj).SetHandle();
}
else
{
addMe = new WeakReference(idObj);
}
// Add the entry into the table
URITable.Add(uriKey, addMe);
idObj.SetInIDTable();
// After every fixed number of set-id calls we run through
// the table and cleanup if needed.
SetIDCount++;
if (SetIDCount % CleanUpCountInterval == 0)
{
// This should be called with the write lock held!
// (which is why we assert that at the beginning of this
// method)
CleanupIdentities(null);
}
}
Message.DebugOut("SetIdentity:: Identity::URI: " + idObj.URI + "\n");
return idObj;
}
#if false
// Convert table entry to a weak reference
//
internal static void WeakenIdentity(String URI)
{
Contract.Assert(URI!=null, "Null URI");
BCLDebug.Trace("REMOTE",
"IdentityHolder.WeakenIdentity ",URI, " for context ", Thread.CurrentContext);
String uriKey = MakeURIKey(URI);
// We need to guarantee that finally is not interrupted so that the lock is released.
// TableLock has a long path without reliability contract. To avoid adding contract on
// the path, we will use ReaderWriterLock directly.
ReaderWriterLock rwlock = TableLock;
bool takeAndRelease = !rwlock.IsWriterLockHeld;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (takeAndRelease)
rwlock.AcquireWriterLock(INFINITE);
Object oRef = URITable[uriKey];
WeakReference wr = oRef as WeakReference;
if (null == wr)
{
// Make the id a weakRef if it isn't already.
Contract.Assert(
oRef != null && (oRef is ServerIdentity),
"Invaild URI given to WeakenIdentity");
URITable[uriKey] = new WeakReference(oRef);
}
}
finally
{
if (takeAndRelase && rwlock.IsWriterLockHeld){
rwlock.ReleaseWriterLock();
}
}
}
#endif
[System.Security.SecurityCritical] // auto-generated
internal static void RemoveIdentity(String uri)
{
RemoveIdentity(uri, true);
}
[System.Security.SecurityCritical] // auto-generated
internal static void RemoveIdentity(String uri, bool bResetURI)
{
Contract.Assert(uri!=null, "Null URI");
BCLDebug.Trace("REMOTE",
"IdentityHolder.WeakenIdentity ",uri, " for context ", Thread.CurrentContext);
Identity id;
String uriKey = MakeURIKey(uri);
// We need to guarantee that finally is not interrupted so that the lock is released.
// TableLock has a long path without reliability contract. To avoid adding contract on
// the path, we will use ReaderWriterLock directly.
ReaderWriterLock rwlock = TableLock;
bool takeAndRelease = !rwlock.IsWriterLockHeld;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (takeAndRelease)
rwlock.AcquireWriterLock(INFINITE);
Object oRef = URITable[uriKey];
WeakReference wr = oRef as WeakReference;
if (null != wr)
{
id = (Identity) wr.Target;
wr.Target = null;
}
else
{
id = (Identity) oRef;
if (id != null)
((ServerIdentity)id).ResetHandle();
}
if(id != null)
{
URITable.Remove(uriKey);
// Mark the ID as not present in the ID Table
// This will clear its URI & objRef fields
id.ResetInIDTable(bResetURI);
}
}
finally
{
if (takeAndRelease && rwlock.IsWriterLockHeld){
rwlock.ReleaseWriterLock();
}
}
} // RemoveIdentity
// Support for dynamically registered property sinks
[System.Security.SecurityCritical] // auto-generated
internal static bool AddDynamicProperty(MarshalByRefObject obj, IDynamicProperty prop)
{
if (RemotingServices.IsObjectOutOfContext(obj))
{
// We have to add a proxy side property, get the identity
RealProxy rp = RemotingServices.GetRealProxy(obj);
return rp.IdentityObject.AddProxySideDynamicProperty(prop);
}
else
{
MarshalByRefObject realObj =
(MarshalByRefObject)
RemotingServices.AlwaysUnwrap((ContextBoundObject)obj);
// This is a real object. See if we have an identity for it
ServerIdentity srvID = (ServerIdentity)MarshalByRefObject.GetIdentity(realObj);
if (srvID != null)
{
return srvID.AddServerSideDynamicProperty(prop);
}
else
{
// identity not found, we can't set a sink for this object.
throw new RemotingException(
Environment.GetResourceString("Remoting_NoIdentityEntry"));
}
}
}
[System.Security.SecurityCritical] // auto-generated
internal static bool RemoveDynamicProperty(MarshalByRefObject obj, String name)
{
if (RemotingServices.IsObjectOutOfContext(obj))
{
// We have to add a proxy side property, get the identity
RealProxy rp = RemotingServices.GetRealProxy(obj);
return rp.IdentityObject.RemoveProxySideDynamicProperty(name);
}
else
{
MarshalByRefObject realObj =
(MarshalByRefObject)
RemotingServices.AlwaysUnwrap((ContextBoundObject)obj);
// This is a real object. See if we have an identity for it
ServerIdentity srvID = (ServerIdentity)MarshalByRefObject.GetIdentity(realObj);
if (srvID != null)
{
return srvID.RemoveServerSideDynamicProperty(name);
}
else
{
// identity not found, we can't set a sink for this object.
throw new RemotingException(
Environment.GetResourceString("Remoting_NoIdentityEntry"));
}
}
}
} // class IdentityHolder
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit
{
using System;
using Newtonsoft.Json;
using Serialization;
public static class SerializerConfigurationExtensions
{
/// <summary>
/// Serialize messages using the JSON serializer
/// </summary>
/// <param name="configurator"></param>
public static void UseJsonSerializer(this IBusFactoryConfigurator configurator)
{
configurator.SetMessageSerializer(() => new JsonMessageSerializer());
}
/// <summary>
/// Serialize messages using the JSON serializer
/// </summary>
/// <param name="configurator"></param>
public static void UseJsonSerializer(this IReceiveEndpointConfigurator configurator)
{
configurator.SetMessageSerializer(() => new JsonMessageSerializer());
}
/// <summary>
/// Configure the serialization settings used to create the message serializer
/// </summary>
/// <param name="configurator"></param>
/// <param name="configure"></param>
public static void ConfigureJsonSerializer(this IBusFactoryConfigurator configurator,
Func<JsonSerializerSettings, JsonSerializerSettings> configure)
{
JsonMessageSerializer.SerializerSettings = configure(JsonMessageSerializer.SerializerSettings);
}
/// <summary>
/// Configure the serialization settings used to create the message deserializer
/// </summary>
/// <param name="configurator"></param>
/// <param name="configure"></param>
public static void ConfigureJsonDeserializer(this IBusFactoryConfigurator configurator,
Func<JsonSerializerSettings, JsonSerializerSettings> configure)
{
JsonMessageSerializer.DeserializerSettings = configure(JsonMessageSerializer.DeserializerSettings);
}
/// <summary>
/// Serialize messages using the BSON message serializer
/// </summary>
/// <param name="configurator"></param>
public static void UseBsonSerializer(this IBusFactoryConfigurator configurator)
{
configurator.SetMessageSerializer(() => new BsonMessageSerializer());
}
/// <summary>
/// Serialize messages using the BSON message serializer
/// </summary>
/// <param name="configurator"></param>
public static void UseBsonSerializer(this IReceiveEndpointConfigurator configurator)
{
configurator.SetMessageSerializer(() => new BsonMessageSerializer());
}
public static void UseEncryptedSerializer(this IBusFactoryConfigurator configurator, ICryptoStreamProvider streamProvider)
{
configurator.SetMessageSerializer(() => new EncryptedMessageSerializer(streamProvider));
configurator.AddMessageDeserializer(EncryptedMessageSerializer.EncryptedContentType,
() => new EncryptedMessageDeserializer(BsonMessageSerializer.Deserializer, streamProvider));
}
public static void UseEncryptedSerializer(this IReceiveEndpointConfigurator configurator, ICryptoStreamProvider streamProvider)
{
configurator.SetMessageSerializer(() => new EncryptedMessageSerializer(streamProvider));
configurator.AddMessageDeserializer(EncryptedMessageSerializer.EncryptedContentType,
() => new EncryptedMessageDeserializer(BsonMessageSerializer.Deserializer, streamProvider));
}
/// <summary>
/// Serialize messages using the BSON message serializer with AES Encryption
/// </summary>
/// <param name="configurator"></param>
/// <param name="symmetricKey">Cryptographic key for both encryption of plaintext message and decryption of ciphertext message</param>
public static void UseEncryption(this IBusFactoryConfigurator configurator, byte[] symmetricKey)
{
var keyProvider = new ConstantSecureKeyProvider(symmetricKey);
var streamProvider = new AesCryptoStreamProviderV2(keyProvider);
configurator.UseEncryptedSerializerV2(streamProvider);
}
/// <summary>
/// Serialize messages using the BSON message serializer with AES Encryption
/// </summary>
/// <param name="configurator"></param>
/// <param name="symmetricKey">Cryptographic key for both encryption of plaintext message and decryption of ciphertext message</param>
public static void UseEncryption(this IReceiveEndpointConfigurator configurator, byte[] symmetricKey)
{
var keyProvider = new ConstantSecureKeyProvider(symmetricKey);
var streamProvider = new AesCryptoStreamProviderV2(keyProvider);
configurator.UseEncryptedSerializerV2(streamProvider);
}
/// <summary>
/// Serialize messages using the BSON message serializer with AES Encryption
/// </summary>
/// <param name="configurator"></param>
/// <param name="keyProvider">The custom key provider to provide the symmetric key for encryption of plaintext message and decryption of ciphertext message</param>
public static void UseEncryption(this IBusFactoryConfigurator configurator, ISecureKeyProvider keyProvider)
{
var streamProvider = new AesCryptoStreamProviderV2(keyProvider);
configurator.UseEncryptedSerializerV2(streamProvider);
}
/// <summary>
/// Serialize messages using the BSON message serializer with AES Encryption
/// </summary>
/// <param name="configurator"></param>
/// <param name="keyProvider">The custom key provider to provide the symmetric key for encryption of plaintext message and decryption of ciphertext message</param>
public static void UseEncryption(this IReceiveEndpointConfigurator configurator, ISecureKeyProvider keyProvider)
{
var streamProvider = new AesCryptoStreamProviderV2(keyProvider);
configurator.UseEncryptedSerializerV2(streamProvider);
}
/// <summary>
/// Serialize messages using the BSON message serializer with AES Encryption
/// </summary>
/// <param name="configurator"></param>
/// <param name="streamProvider"></param>
public static void UseEncryptedSerializerV2(this IBusFactoryConfigurator configurator, ICryptoStreamProviderV2 streamProvider)
{
configurator.SetMessageSerializer(() => new EncryptedMessageSerializerV2(streamProvider));
configurator.AddMessageDeserializer(EncryptedMessageSerializerV2.EncryptedContentType,
() => new EncryptedMessageDeserializerV2(BsonMessageSerializer.Deserializer, streamProvider));
}
/// <summary>
/// Serialize messages using the BSON message serializer with AES Encryption
/// </summary>
/// <param name="configurator"></param>
/// <param name="streamProvider"></param>
public static void UseEncryptedSerializerV2(this IReceiveEndpointConfigurator configurator, ICryptoStreamProviderV2 streamProvider)
{
configurator.SetMessageSerializer(() => new EncryptedMessageSerializerV2(streamProvider));
configurator.AddMessageDeserializer(EncryptedMessageSerializerV2.EncryptedContentType,
() => new EncryptedMessageDeserializerV2(BsonMessageSerializer.Deserializer, streamProvider));
}
/// <summary>
/// Serialize messages using the XML message serializer
/// </summary>
/// <param name="configurator"></param>
public static void UseXmlSerializer(this IBusFactoryConfigurator configurator)
{
configurator.SetMessageSerializer(() => new XmlMessageSerializer());
}
/// <summary>
/// Serialize messages using the XML message serializer
/// </summary>
/// <param name="configurator"></param>
public static void UseXmlSerializer(this IReceiveEndpointConfigurator configurator)
{
configurator.SetMessageSerializer(() => new XmlMessageSerializer());
}
#if !NETCORE
/// <summary>
/// Serialize message using the .NET binary formatter (also adds support for the binary deserializer)
/// </summary>
/// <param name="configurator"></param>
public static void UseBinarySerializer(this IBusFactoryConfigurator configurator)
{
configurator.SetMessageSerializer(() => new BinaryMessageSerializer());
configurator.SupportBinaryMessageDeserializer();
}
/// <summary>
/// Serialize message using the .NET binary formatter (also adds support for the binary deserializer)
/// </summary>
/// <param name="configurator"></param>
public static void UseBinarySerializer(this IReceiveEndpointConfigurator configurator)
{
configurator.SetMessageSerializer(() => new BinaryMessageSerializer());
configurator.SupportBinaryMessageDeserializer();
}
/// <summary>
/// Add support for the binary message deserializer to the bus. This serializer is not supported
/// by default.
/// </summary>
/// <param name="configurator"></param>
/// <returns></returns>
public static void SupportBinaryMessageDeserializer(this IBusFactoryConfigurator configurator)
{
configurator.AddMessageDeserializer(BinaryMessageSerializer.BinaryContentType, () => new BinaryMessageDeserializer());
}
/// <summary>
/// Add support for the binary message deserializer to the bus. This serializer is not supported
/// by default.
/// </summary>
/// <param name="configurator"></param>
/// <returns></returns>
public static void SupportBinaryMessageDeserializer(this IReceiveEndpointConfigurator configurator)
{
configurator.AddMessageDeserializer(BinaryMessageSerializer.BinaryContentType, () => new BinaryMessageDeserializer());
}
#endif
}
}
| |
using TribalWars.Controls.Common;
using TribalWars.Controls.Common.ToolStripControlHostWrappers;
using TribalWars.Controls.XPTables;
using TribalWars.Worlds.Events.Impls;
namespace TribalWars.Controls.AccordeonDetails
{
partial class DetailsControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DetailsControl));
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.DetailsGrid = new System.Windows.Forms.PropertyGrid();
this.CommentsPanel = new System.Windows.Forms.Panel();
this.CommentsLabel = new System.Windows.Forms.Label();
this.Comments = new System.Windows.Forms.TextBox();
this.Table = new TribalWars.Controls.XPTables.TableWrapperControl();
this.QuickFinderLayout = new System.Windows.Forms.TableLayoutPanel();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.SelectedVillage = new TribalWars.Controls.Common.ToolStripControlHostWrappers.ToolStripVillageTextBox();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.UndoButton = new System.Windows.Forms.ToolStripButton();
this.RedoButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.ViewVillageDetails = new System.Windows.Forms.ToolStripButton();
this.ViewPlayerDetails = new System.Windows.Forms.ToolStripButton();
this.ViewTribeDetails = new System.Windows.Forms.ToolStripButton();
this.ContextStripPanel = new System.Windows.Forms.Panel();
this.ContextStrip = new System.Windows.Forms.ToolStrip();
this.AttackFlag = new System.Windows.Forms.ToolStripButton();
this.CatapultFlag = new System.Windows.Forms.ToolStripButton();
this.DefenseFlag = new System.Windows.Forms.ToolStripButton();
this.NobleFlag = new System.Windows.Forms.ToolStripButton();
this.ScoutFlag = new System.Windows.Forms.ToolStripButton();
this.FarmFlag = new System.Windows.Forms.ToolStripButton();
this.VillageSeperator = new System.Windows.Forms.ToolStripSeparator();
this.VillageCurrentSituation = new System.Windows.Forms.ToolStripButton();
this.MarkPlayerOrTribe = new TribalWars.Maps.Markers.MarkerSettingsControl();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.CommentsPanel.SuspendLayout();
this.QuickFinderLayout.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.ContextStripPanel.SuspendLayout();
this.ContextStrip.SuspendLayout();
this.SuspendLayout();
//
// splitContainer2
//
resources.ApplyResources(this.splitContainer2, "splitContainer2");
this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer2.Name = "splitContainer2";
//
// splitContainer2.Panel1
//
resources.ApplyResources(this.splitContainer2.Panel1, "splitContainer2.Panel1");
this.splitContainer2.Panel1.Controls.Add(this.DetailsGrid);
//
// splitContainer2.Panel2
//
resources.ApplyResources(this.splitContainer2.Panel2, "splitContainer2.Panel2");
this.splitContainer2.Panel2.Controls.Add(this.CommentsPanel);
this.splitContainer2.Panel2.Controls.Add(this.Table);
//
// DetailsGrid
//
resources.ApplyResources(this.DetailsGrid, "DetailsGrid");
this.DetailsGrid.CategoryForeColor = System.Drawing.SystemColors.InactiveCaptionText;
this.DetailsGrid.Name = "DetailsGrid";
this.DetailsGrid.ToolbarVisible = false;
//
// CommentsPanel
//
resources.ApplyResources(this.CommentsPanel, "CommentsPanel");
this.CommentsPanel.Controls.Add(this.CommentsLabel);
this.CommentsPanel.Controls.Add(this.Comments);
this.CommentsPanel.Name = "CommentsPanel";
//
// CommentsLabel
//
resources.ApplyResources(this.CommentsLabel, "CommentsLabel");
this.CommentsLabel.Name = "CommentsLabel";
//
// Comments
//
this.Comments.AcceptsReturn = true;
resources.ApplyResources(this.Comments, "Comments");
this.Comments.Name = "Comments";
//
// Table
//
resources.ApplyResources(this.Table, "Table");
this.Table.AutoSelectSingleRow = false;
this.Table.BackColor = System.Drawing.Color.Transparent;
this.Table.DisplayType = TribalWars.Controls.XPTables.TableWrapperControl.ColumnDisplayTypeEnum.Custom;
this.Table.Name = "Table";
this.Table.RowSelectionAction = TribalWars.Controls.XPTables.TableWrapperControl.RowSelectionActionEnum.RaiseSelectEvent;
this.Table.VisiblePlayerFields = ((TribalWars.Controls.XPTables.PlayerFields)(((((TribalWars.Controls.XPTables.PlayerFields.Name | TribalWars.Controls.XPTables.PlayerFields.Points)
| TribalWars.Controls.XPTables.PlayerFields.PointsDifference)
| TribalWars.Controls.XPTables.PlayerFields.Villages)
| TribalWars.Controls.XPTables.PlayerFields.VillagesDifference)));
this.Table.VisibleReportFields = ((TribalWars.Controls.XPTables.ReportFields)((((((TribalWars.Controls.XPTables.ReportFields.Type | TribalWars.Controls.XPTables.ReportFields.Status)
| TribalWars.Controls.XPTables.ReportFields.Village)
| TribalWars.Controls.XPTables.ReportFields.Player)
| TribalWars.Controls.XPTables.ReportFields.Date)
| TribalWars.Controls.XPTables.ReportFields.Flag)));
this.Table.VisibleTribeFields = ((TribalWars.Controls.XPTables.TribeFields)((((((TribalWars.Controls.XPTables.TribeFields.Tag | TribalWars.Controls.XPTables.TribeFields.Name)
| TribalWars.Controls.XPTables.TribeFields.Players)
| TribalWars.Controls.XPTables.TribeFields.Points)
| TribalWars.Controls.XPTables.TribeFields.Villages)
| TribalWars.Controls.XPTables.TribeFields.Rank)));
this.Table.VisibleVillageFields = ((TribalWars.Controls.XPTables.VillageFields)((((((TribalWars.Controls.XPTables.VillageFields.Type | TribalWars.Controls.XPTables.VillageFields.Coordinates)
| TribalWars.Controls.XPTables.VillageFields.Name)
| TribalWars.Controls.XPTables.VillageFields.Points)
| TribalWars.Controls.XPTables.VillageFields.PointsDifference)
| TribalWars.Controls.XPTables.VillageFields.HasReport)));
//
// QuickFinderLayout
//
resources.ApplyResources(this.QuickFinderLayout, "QuickFinderLayout");
this.QuickFinderLayout.Controls.Add(this.splitContainer2, 0, 2);
this.QuickFinderLayout.Controls.Add(this.toolStrip1, 0, 0);
this.QuickFinderLayout.Controls.Add(this.ContextStripPanel, 0, 1);
this.QuickFinderLayout.Name = "QuickFinderLayout";
//
// toolStrip1
//
resources.ApplyResources(this.toolStrip1, "toolStrip1");
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SelectedVillage,
this.toolStripSeparator2,
this.UndoButton,
this.RedoButton,
this.toolStripSeparator3,
this.ViewVillageDetails,
this.ViewPlayerDetails,
this.ViewTribeDetails});
this.toolStrip1.Name = "toolStrip1";
//
// SelectedVillage
//
resources.ApplyResources(this.SelectedVillage, "SelectedVillage");
this.SelectedVillage.AllowPlayer = true;
this.SelectedVillage.AllowTribe = true;
this.SelectedVillage.BackColor = System.Drawing.Color.White;
this.SelectedVillage.ForeColor = System.Drawing.SystemColors.WindowText;
this.SelectedVillage.Name = "SelectedVillage";
this.SelectedVillage.Player = null;
this.SelectedVillage.Tribe = null;
this.SelectedVillage.Village = null;
this.SelectedVillage.VillageSelected += new System.EventHandler<TribalWars.Worlds.Events.Impls.VillageEventArgs>(this.SelectedVillage_VillageSelected);
this.SelectedVillage.PlayerSelected += new System.EventHandler<TribalWars.Worlds.Events.Impls.PlayerEventArgs>(this.SelectedVillage_PlayerSelected);
this.SelectedVillage.TribeSelected += new System.EventHandler<TribalWars.Worlds.Events.Impls.TribeEventArgs>(this.SelectedVillage_TribeSelected);
//
// toolStripSeparator2
//
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
this.toolStripSeparator2.Name = "toolStripSeparator2";
//
// UndoButton
//
resources.ApplyResources(this.UndoButton, "UndoButton");
this.UndoButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.UndoButton.Name = "UndoButton";
this.UndoButton.Click += new System.EventHandler(this.UndoButton_Click);
//
// RedoButton
//
resources.ApplyResources(this.RedoButton, "RedoButton");
this.RedoButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.RedoButton.Name = "RedoButton";
this.RedoButton.Click += new System.EventHandler(this.RedoButton_Click);
//
// toolStripSeparator3
//
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
this.toolStripSeparator3.Name = "toolStripSeparator3";
//
// ViewVillageDetails
//
resources.ApplyResources(this.ViewVillageDetails, "ViewVillageDetails");
this.ViewVillageDetails.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.ViewVillageDetails.Image = global::TribalWars.Properties.Resources.Village;
this.ViewVillageDetails.Name = "ViewVillageDetails";
this.ViewVillageDetails.Click += new System.EventHandler(this.ViewVillageDetails_Click);
//
// ViewPlayerDetails
//
resources.ApplyResources(this.ViewPlayerDetails, "ViewPlayerDetails");
this.ViewPlayerDetails.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.ViewPlayerDetails.Image = global::TribalWars.Properties.Resources.Player;
this.ViewPlayerDetails.Name = "ViewPlayerDetails";
this.ViewPlayerDetails.Click += new System.EventHandler(this.ViewPlayerDetails_Click);
//
// ViewTribeDetails
//
resources.ApplyResources(this.ViewTribeDetails, "ViewTribeDetails");
this.ViewTribeDetails.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.ViewTribeDetails.Image = global::TribalWars.Properties.Resources.Tribe;
this.ViewTribeDetails.Name = "ViewTribeDetails";
this.ViewTribeDetails.Click += new System.EventHandler(this.ViewTribeDetails_Click);
//
// ContextStripPanel
//
resources.ApplyResources(this.ContextStripPanel, "ContextStripPanel");
this.ContextStripPanel.Controls.Add(this.ContextStrip);
this.ContextStripPanel.Controls.Add(this.MarkPlayerOrTribe);
this.ContextStripPanel.Name = "ContextStripPanel";
//
// ContextStrip
//
resources.ApplyResources(this.ContextStrip, "ContextStrip");
this.ContextStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AttackFlag,
this.CatapultFlag,
this.DefenseFlag,
this.NobleFlag,
this.ScoutFlag,
this.FarmFlag,
this.VillageSeperator,
this.VillageCurrentSituation});
this.ContextStrip.Name = "ContextStrip";
//
// AttackFlag
//
resources.ApplyResources(this.AttackFlag, "AttackFlag");
this.AttackFlag.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.AttackFlag.Name = "AttackFlag";
this.AttackFlag.Click += new System.EventHandler(this.AttackFlag_Click);
//
// CatapultFlag
//
resources.ApplyResources(this.CatapultFlag, "CatapultFlag");
this.CatapultFlag.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.CatapultFlag.Image = global::TribalWars.Properties.Resources.catapult;
this.CatapultFlag.Name = "CatapultFlag";
this.CatapultFlag.Click += new System.EventHandler(this.CatapultFlag_Click);
//
// DefenseFlag
//
resources.ApplyResources(this.DefenseFlag, "DefenseFlag");
this.DefenseFlag.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.DefenseFlag.Image = global::TribalWars.Properties.Resources.Defense;
this.DefenseFlag.Name = "DefenseFlag";
this.DefenseFlag.Click += new System.EventHandler(this.DefenseFlag_Click);
//
// NobleFlag
//
resources.ApplyResources(this.NobleFlag, "NobleFlag");
this.NobleFlag.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.NobleFlag.Image = global::TribalWars.Properties.Resources.nobleman;
this.NobleFlag.Name = "NobleFlag";
this.NobleFlag.Click += new System.EventHandler(this.NobleFlag_Click);
//
// ScoutFlag
//
resources.ApplyResources(this.ScoutFlag, "ScoutFlag");
this.ScoutFlag.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.ScoutFlag.Image = global::TribalWars.Properties.Resources.scout;
this.ScoutFlag.Name = "ScoutFlag";
this.ScoutFlag.Click += new System.EventHandler(this.ScoutFlag_Click);
//
// FarmFlag
//
resources.ApplyResources(this.FarmFlag, "FarmFlag");
this.FarmFlag.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.FarmFlag.Image = global::TribalWars.Properties.Resources.farm;
this.FarmFlag.Name = "FarmFlag";
this.FarmFlag.Click += new System.EventHandler(this.FarmFlag_Click);
//
// VillageSeperator
//
resources.ApplyResources(this.VillageSeperator, "VillageSeperator");
this.VillageSeperator.Name = "VillageSeperator";
//
// VillageCurrentSituation
//
resources.ApplyResources(this.VillageCurrentSituation, "VillageCurrentSituation");
this.VillageCurrentSituation.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.VillageCurrentSituation.Name = "VillageCurrentSituation";
this.VillageCurrentSituation.Click += new System.EventHandler(this.VillageCurrentSituation_Click);
//
// MarkPlayerOrTribe
//
resources.ApplyResources(this.MarkPlayerOrTribe, "MarkPlayerOrTribe");
this.MarkPlayerOrTribe.AllowBarbarianViews = false;
this.MarkPlayerOrTribe.AutoUpdateMarkers = true;
this.MarkPlayerOrTribe.BackColor = System.Drawing.Color.White;
this.MarkPlayerOrTribe.CanDeactivate = true;
this.MarkPlayerOrTribe.DefaultExtraMarkerColor = System.Drawing.Color.Transparent;
this.MarkPlayerOrTribe.DefaultMarkerColor = System.Drawing.Color.Black;
this.MarkPlayerOrTribe.Name = "MarkPlayerOrTribe";
//
// DetailsControl
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.QuickFinderLayout);
this.Name = "DetailsControl";
this.Load += new System.EventHandler(this.DetailsControl_Load);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
this.splitContainer2.ResumeLayout(false);
this.CommentsPanel.ResumeLayout(false);
this.CommentsPanel.PerformLayout();
this.QuickFinderLayout.ResumeLayout(false);
this.QuickFinderLayout.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ContextStripPanel.ResumeLayout(false);
this.ContextStripPanel.PerformLayout();
this.ContextStrip.ResumeLayout(false);
this.ContextStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel QuickFinderLayout;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton ViewPlayerDetails;
private System.Windows.Forms.ToolStripButton ViewTribeDetails;
private System.Windows.Forms.ToolStripButton ViewVillageDetails;
private ToolStripVillageTextBox SelectedVillage;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private TableWrapperControl Table;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.PropertyGrid DetailsGrid;
private System.Windows.Forms.Panel ContextStripPanel;
private System.Windows.Forms.ToolStrip ContextStrip;
private System.Windows.Forms.ToolStripButton DefenseFlag;
private System.Windows.Forms.ToolStripButton AttackFlag;
private System.Windows.Forms.ToolStripButton ScoutFlag;
private System.Windows.Forms.ToolStripButton NobleFlag;
private System.Windows.Forms.ToolStripButton FarmFlag;
private System.Windows.Forms.ToolStripButton UndoButton;
private System.Windows.Forms.ToolStripButton RedoButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripSeparator VillageSeperator;
private System.Windows.Forms.ToolStripButton VillageCurrentSituation;
private Maps.Markers.MarkerSettingsControl MarkPlayerOrTribe;
private System.Windows.Forms.ToolStripButton CatapultFlag;
private System.Windows.Forms.TextBox Comments;
private System.Windows.Forms.Panel CommentsPanel;
private System.Windows.Forms.Label CommentsLabel;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.Data;
using gView.Framework.FDB;
using gView.Framework.Geometry;
using gView.Framework.SpatialAlgorithms;
using gView.Framework.Topology;
namespace gView.Framework.GeoProcessing
{
[gView.Framework.system.RegisterPlugIn("F08AD765-E0F9-471c-B729-ACA08A6668D2")]
public class Voronoi : gView.Framework.GeoProcessing.ActivityBase.SimpleActivity
{
#region IActivity Member
public override string CategoryName
{
get { return "Trianguation"; }
}
public override string DisplayName
{
get { return "Voronoi Graph"; }
}
public override List<IActivityData> Process()
{
IDatasetElement sElement = base.SourceDatasetElement;
IFeatureClass sFc = base.SourceFeatureClass;
ActivityBase.TargetDatasetElement tElement = base.TargetDatasetElement;
IDataset tDs = base.TargetDataset;
//IFeatureDatabase tDatabase = base.TargetFeatureDatabase;
GeometryDef geomDef = new GeometryDef(
geometryType.Polyline,
null,
false);
IFeatureClass tFc = base.CreateTargetFeatureclass(geomDef, sFc.Fields);
IFeatureDatabase tDatabase = FeatureDatabase(tFc);
Report.featureMax = sFc.CountFeatures;
Report.featurePos = 0;
ReportProgess("Query Filter: " + SourceData.FilterClause);
Nodes nodes = new Nodes();
using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty))
{
if (cursor == null) return null;
IFeature feature;
while ((feature = cursor.NextFeature) != null)
{
if (Report.featurePos++ % 100 == 0)
ReportProgess();
if (feature.Shape is IPoint)
nodes.Add((IPoint)feature.Shape);
}
}
VoronoiGraph voronoi = new VoronoiGraph();
voronoi.ProgressMessage += new VoronoiGraph.ProgressMessageEventHandler(voronoi_ProgressMessage);
voronoi.Progress += new VoronoiGraph.ProgressEventHandler(voronoi_Progress);
voronoi.Calc(nodes);
List<IPoint> vertices = voronoi.Nodes;
Edges edges = voronoi.Edges;
ReportProgess("Write Lines");
Report.featurePos = 0;
List<IFeature> features = new List<IFeature>();
foreach (Edge edge in edges)
{
Polyline pLine = new Polyline();
Path path = new Path();
path.AddPoint(vertices[edge.p1]);
path.AddPoint(vertices[edge.p2]);
pLine.AddPath(path);
Feature feature = new Feature();
feature.Shape = pLine;
features.Add(feature);
Report.featurePos++;
if (features.Count >= 100)
{
if (!tDatabase.Insert(tFc, features))
throw new Exception(tDatabase.lastErrorMsg);
features.Clear();
ReportProgess();
}
}
if (features.Count > 0)
{
ReportProgess();
if (!tDatabase.Insert(tFc, features))
throw new Exception(tDatabase.lastErrorMsg);
}
ReportProgess("Flush Features");
base.FlushFeatureClass(tFc);
return base.ToProcessResult(tFc);
}
void voronoi_ProgressMessage(string msg)
{
ReportProgess(msg);
}
void voronoi_Progress(int pos, int max)
{
Report.featureMax = max;
Report.featurePos = pos;
ReportProgess();
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("FF2854AB-866E-4395-941B-BEFB2203E611")]
public class Delaunay : gView.Framework.GeoProcessing.ActivityBase.SimpleActivity
{
#region IActivity Member
public override string CategoryName
{
get { return "Trianguation"; }
}
public override string DisplayName
{
get { return "Delaunay Graph"; }
}
public override List<IActivityData> Process()
{
IDatasetElement sElement = base.SourceDatasetElement;
IFeatureClass sFc = base.SourceFeatureClass;
ActivityBase.TargetDatasetElement tElement = base.TargetDatasetElement;
IDataset tDs = base.TargetDataset;
//IFeatureDatabase tDatabase = base.TargetFeatureDatabase;
GeometryDef geomDef = new GeometryDef(
geometryType.Polyline,
null,
false);
IFeatureClass tFc = base.CreateTargetFeatureclass(geomDef, sFc.Fields);
IFeatureDatabase tDatabase = FeatureDatabase(tFc);
Report.featureMax = sFc.CountFeatures;
Report.featurePos = 0;
ReportProgess("Query Filter: " + SourceData.FilterClause);
Nodes nodes = new Nodes();
using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty))
{
if (cursor == null) return null;
IFeature feature;
while ((feature = cursor.NextFeature) != null)
{
if (Report.featurePos++ % 100 == 0)
ReportProgess();
if (feature.Shape is IPoint)
nodes.Add((IPoint)feature.Shape);
}
}
DelaunayTriangulation triangulation = new DelaunayTriangulation();
triangulation.Progress += new DelaunayTriangulation.ProgressEventHandler(triangulation_Progress);
ReportProgess("Calculate Triangles");
Triangles triangles = triangulation.Triangulate(nodes);
ReportProgess("Extract Edges");
Edges edges = triangulation.TriangleEdges(triangles);
Report.featurePos = 0;
List<IFeature> features = new List<IFeature>();
foreach (Edge edge in edges)
{
Polyline pLine = new Polyline();
Path path = new Path();
path.AddPoint(nodes[edge.p1]);
path.AddPoint(nodes[edge.p2]);
pLine.AddPath(path);
Feature feature = new Feature();
feature.Shape = pLine;
Report.featurePos++;
features.Add(feature);
if (features.Count >= 100)
{
if (!tDatabase.Insert(tFc, features))
throw new Exception(tDatabase.lastErrorMsg);
features.Clear();
ReportProgess();
}
}
if (features.Count > 0)
{
ReportProgess();
if (!tDatabase.Insert(tFc, features))
throw new Exception(tDatabase.lastErrorMsg);
}
ReportProgess("Flush Features");
base.FlushFeatureClass(tFc);
return base.ToProcessResult(tFc);
}
void triangulation_Progress(int pos, int max)
{
Report.featureMax = max;
Report.featurePos = pos;
ReportProgess();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;
using Amazon.Util;
using AspNetCore.Identity.DynamoDB.Extensions;
using Microsoft.AspNetCore.Identity;
namespace AspNetCore.Identity.DynamoDB
{
public class DynamoRoleStore<TRole> : IRoleClaimStore<TRole>
where TRole : DynamoIdentityRole
{
private IDynamoDBContext _context;
public Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(role.GetClaims());
}
public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
role.AddClaim(claim);
return Task.FromResult(0);
}
public Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
role.RemoveClaim(claim);
return Task.FromResult(0);
}
public async Task<IdentityResult> CreateAsync(TRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
cancellationToken.ThrowIfCancellationRequested();
await _context.SaveAsync(role, cancellationToken);
return IdentityResult.Success;
}
public async Task<IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
cancellationToken.ThrowIfCancellationRequested();
await _context.SaveAsync(role, cancellationToken);
return IdentityResult.Success;
}
public async Task<IdentityResult> DeleteAsync(TRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
cancellationToken.ThrowIfCancellationRequested();
role.Delete();
await _context.SaveAsync(role, cancellationToken);
return IdentityResult.Success;
}
public Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(role.Id);
}
public Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(role.Name);
}
public Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken)
{
throw new NotSupportedException("Changing the role name is not supported.");
}
public Task<string> GetNormalizedRoleNameAsync(TRole role, CancellationToken cancellationToken)
{
if (role == null)
{
throw new ArgumentNullException(nameof(role));
}
return Task.FromResult(role.NormalizedName);
}
public Task SetNormalizedRoleNameAsync(TRole role, string normalizedName, CancellationToken cancellationToken)
{
throw new NotSupportedException("Changing the role normalized name is not supported.");
}
public async Task<TRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
{
if (roleId == null)
{
throw new ArgumentNullException(nameof(roleId));
}
cancellationToken.ThrowIfCancellationRequested();
var role = await _context.LoadAsync<TRole>(roleId, default(DateTimeOffset), cancellationToken);
return role?.DeletedOn == default(DateTimeOffset) ? role : null;
}
public async Task<TRole> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken)
{
if (normalizedRoleName == null)
{
throw new ArgumentNullException(nameof(normalizedRoleName));
}
cancellationToken.ThrowIfCancellationRequested();
var search = _context.FromQueryAsync<TRole>(new QueryOperationConfig
{
IndexName = "NormalizedName-DeletedOn-index",
KeyExpression = new Expression
{
ExpressionStatement = "NormalizedName = :name AND DeletedOn = :deletedOn",
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{":name", normalizedRoleName},
{":deletedOn", default(DateTimeOffset).ToString("o")}
}
},
Limit = 1
});
var roles = await search.GetRemainingAsync(cancellationToken);
return roles?.FirstOrDefault();
}
public void Dispose() {}
public Task EnsureInitializedAsync(IAmazonDynamoDB client, IDynamoDBContext context,
string rolesTableName = Constants.DefaultRolesTableName)
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
_context = context;
if (rolesTableName != Constants.DefaultRolesTableName)
{
AWSConfigsDynamoDB.Context.AddAlias(new TableAlias(rolesTableName, Constants.DefaultRolesTableName));
}
return EnsureInitializedImplAsync(client, rolesTableName);
}
private async Task EnsureInitializedImplAsync(IAmazonDynamoDB client, string rolesTableName)
{
var defaultProvisionThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 5
};
var globalSecondaryIndexes = new List<GlobalSecondaryIndex>
{
new GlobalSecondaryIndex
{
IndexName = "NormalizedName-DeletedOn-index",
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement("NormalizedName", KeyType.HASH),
new KeySchemaElement("DeletedOn", KeyType.RANGE)
},
ProvisionedThroughput = defaultProvisionThroughput,
Projection = new Projection
{
ProjectionType = ProjectionType.ALL
}
}
};
var tableNames = await client.ListAllTablesAsync();
if (!tableNames.Contains(rolesTableName))
{
await CreateTableAsync(client, rolesTableName, defaultProvisionThroughput, globalSecondaryIndexes);
return;
}
var response = await client.DescribeTableAsync(new DescribeTableRequest {TableName = rolesTableName});
var table = response.Table;
var indexesToAdd =
globalSecondaryIndexes.Where(
g => !table.GlobalSecondaryIndexes.Exists(gd => gd.IndexName.Equals(g.IndexName)));
var indexUpdates = indexesToAdd.Select(index => new GlobalSecondaryIndexUpdate
{
Create = new CreateGlobalSecondaryIndexAction
{
IndexName = index.IndexName,
KeySchema = index.KeySchema,
ProvisionedThroughput = index.ProvisionedThroughput,
Projection = index.Projection
}
}).ToList();
if (indexUpdates.Count > 0)
{
await UpdateTableAsync(client, rolesTableName, indexUpdates);
}
}
private async Task CreateTableAsync(IAmazonDynamoDB client, string rolesTableName,
ProvisionedThroughput provisionedThroughput, List<GlobalSecondaryIndex> globalSecondaryIndexes)
{
var response = await client.CreateTableAsync(new CreateTableRequest
{
TableName = rolesTableName,
ProvisionedThroughput = provisionedThroughput,
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = KeyType.HASH
}
},
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "DeletedOn",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "NormalizedName",
AttributeType = ScalarAttributeType.S
}
},
GlobalSecondaryIndexes = globalSecondaryIndexes
});
if (response.HttpStatusCode != HttpStatusCode.OK)
{
throw new Exception($"Couldn't create table {rolesTableName}");
}
await DynamoUtils.WaitForActiveTableAsync(client, rolesTableName);
}
private async Task UpdateTableAsync(IAmazonDynamoDB client, string rolesTableName,
List<GlobalSecondaryIndexUpdate> indexUpdates)
{
await client.UpdateTableAsync(new UpdateTableRequest
{
TableName = rolesTableName,
GlobalSecondaryIndexUpdates = indexUpdates
});
await DynamoUtils.WaitForActiveTableAsync(client, rolesTableName);
}
}
}
| |
#region License
//
// Command Line Library: HelpTextFixture.cs
//
// Author:
// Giacomo Stelluti Scala (gsscoder@gmail.com)
// Contributor(s):
// Steven Evans
//
// Copyright (C) 2005 - 2012 Giacomo Stelluti Scala
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
#region Using Directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Globalization;
using NUnit.Framework;
using CommandLine.Tests.Mocks;
#endregion
namespace CommandLine.Text.Tests
{
[TestFixture]
public sealed class HelpTextFixture
{
#region Mock Objects
class MockOptions
{
[Option("v", "verbose")]
public bool Verbose { get; set; }
[Option(null, "input-file")]
public string FileName { get; set; }
}
class MockOptionsWithDescription
{
[Option("v", "verbose", HelpText = "Comment extensively every operation.")]
public bool Verbose { get; set; }
[Option("i", "input-file", Required = true, HelpText = "Specify input file to be processed.")]
public string FileName { get; set; }
}
private class MockOptionsWithLongDescription
{
[Option("v", "verbose", HelpText = "This is the description of the verbosity to test out the wrapping capabilities of the Help Text.")]
public bool Verbose { get; set; }
[Option(null, "input-file", HelpText = "This is a very long description of the Input File argument that gets passed in. It should be passed in as a string.")]
public string FileName { get; set; }
}
private class MockOptionsWithLongDescriptionAndNoSpaces
{
[Option("v", "verbose", HelpText = "Before 012345678901234567890123 After")]
public bool Verbose { get; set; }
[Option(null, "input-file", HelpText = "Before 012345678901234567890123456789 After")]
public string FileName { get; set; }
}
public class MockOptionsSimple
{
[Option("s", "something", HelpText = "Input something here.")]
public string Something { get; set; }
}
public class ComplexOptionsWithHelp : ComplexOptions
{
[Option("a", "all", HelpText = "Read the file completely.", MutuallyExclusiveSet = "reading")]
public bool ReadAll { get; set; }
[Option("p", "part", HelpText = "Read the file partially.", MutuallyExclusiveSet = "reading")]
public bool ReadPartially { get; set; }
[HelpOption(HelpText ="Displays this help screen.")]
public string GetUsage()
{
var help = new HelpText(new HeadingInfo("unittest", "1.9"));
help.AdditionalNewLineAfterOption = true;
help.Copyright = new CopyrightInfo("CommandLine.dll Author", 2005, 2011);
// handling parsing error code
string errors = help.RenderParsingErrorsText(this, 2); // indent with two spaces
if (!string.IsNullOrEmpty(errors))
{
help.AddPreOptionsLine(string.Concat(Environment.NewLine, "ERROR(S):"));
help.AddPreOptionsLine(errors);
}
help.AddPreOptionsLine("This is free software. You may redistribute copies of it under the terms of");
help.AddPreOptionsLine("the MIT License <http://www.opensource.org/licenses/mit-license.php>.");
help.AddPreOptionsLine("Usage: Please run the unit...");
help.AddOptions(this);
return help;
}
}
#endregion
private HelpText _helpText;
[SetUp]
public void SetUp()
{
_helpText = new HelpText(new HeadingInfo(_ThisAssembly.Title, _ThisAssembly.Version));
}
[Test]
public void AddAnEmptyPreOptionsLineIsAllowed()
{
_helpText.AddPreOptionsLine(string.Empty);
}
/// <summary>
/// Ref.: #REQ0002
/// </summary>
[Test]
public void PostOptionsLinesFeatureAdded()
{
var local = new HelpText("Heading Info.");
local.AddPreOptionsLine("This is a first pre-options line.");
local.AddPreOptionsLine("This is a second pre-options line.");
local.AddOptions(new MockOptions());
local.AddPostOptionsLine("This is a first post-options line.");
local.AddPostOptionsLine("This is a second post-options line.");
string help = local.ToString();
string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual(lines[lines.Length - 2], "This is a first post-options line.");
Assert.AreEqual(lines[lines.Length - 1], "This is a second post-options line.");
}
[Test]
public void WhenHelpTextIsLongerThanWidthItWillWrapAroundAsIfInAColumn()
{
_helpText.MaximumDisplayWidth = 40;
_helpText.AddOptions(new MockOptionsWithLongDescription());
string help = _helpText.ToString();
string[] lines = help.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
Assert.AreEqual(lines[2], " v, verbose This is the description", "The first line should have the arguments and the start of the Help Text.");
string formattingMessage = "Beyond the second line should be formatted as though it's in a column.";
Assert.AreEqual(lines[3], " of the verbosity to ", formattingMessage);
Assert.AreEqual(lines[4], " test out the wrapping ", formattingMessage);
Assert.AreEqual(lines[5], " capabilities of the ", formattingMessage);
Assert.AreEqual(lines[6], " Help Text.", formattingMessage);
}
[Test]
public void LongHelpTextWithoutSpaces()
{
_helpText.MaximumDisplayWidth = 40;
_helpText.AddOptions(new MockOptionsWithLongDescriptionAndNoSpaces());
string help = _helpText.ToString();
string[] lines = help.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual(" v, verbose Before ", lines[2]);
Assert.AreEqual(" 012345678901234567890123", lines[3]);
Assert.AreEqual(" After", lines[4]);
Assert.AreEqual(" input-file Before ", lines[5]);
Assert.AreEqual(" 012345678901234567890123", lines[6]);
Assert.AreEqual(" 456789 After", lines[7]);
}
[Test]
public void LongPreAndPostLinesWithoutSpaces()
{
var local = new HelpText("Heading Info.");
local.MaximumDisplayWidth = 40;
local.AddPreOptionsLine("Before 0123456789012345678901234567890123456789012 After");
local.AddOptions(new MockOptions());
local.AddPostOptionsLine("Before 0123456789012345678901234567890123456789 After");
string help = local.ToString();
string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual("Before ", lines[1]);
Assert.AreEqual("0123456789012345678901234567890123456789", lines[2]);
Assert.AreEqual("012 After", lines[3]);
Assert.AreEqual("Before ", lines[lines.Length - 3]);
Assert.AreEqual("0123456789012345678901234567890123456789", lines[lines.Length - 2]);
Assert.AreEqual(" After", lines[lines.Length - 1]);
}
[Test]
public void CustomizeOptionsFormat()
{
var local = new HelpText("Customizing Test.");
local.FormatOptionHelpText += new EventHandler<FormatOptionHelpTextEventArgs>(CustomizeOptionsFormat_FormatOptionHelpText);
local.AddPreOptionsLine("Pre-Options.");
local.AddOptions(new MockOptionsWithDescription());
local.AddPostOptionsLine("Post-Options.");
string help = local.ToString();
Console.WriteLine(help);
string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual("Customizing Test.", lines[0]);
Assert.AreEqual("Pre-Options.", lines[1]);
Assert.AreEqual(" v, verbose Kommentar umfassend Operationen.", lines[3]);
Assert.AreEqual(" i, input-file Erforderlich. Gibt den Eingang an zu bearbeitenden Datei.", lines[4]);
Assert.AreEqual("Post-Options.", lines[6]);
}
[Test]
public void InstancingWithParameterlessConstructor()
{
var year = DateTime.Now.Year;
var local = new HelpText();
local.Heading = new HeadingInfo("Parameterless Constructor Test.");
local.Copyright = new CopyrightInfo("Author", year);
local.AddPreOptionsLine("Pre-Options.");
local.AddOptions(new MockOptionsSimple());
local.AddPostOptionsLine("Post-Options.");
string help = local.ToString();
Console.WriteLine(help);
string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual("Parameterless Constructor Test.", lines[0]);
Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "Copyright (C) {0} Author", year), lines[1]);
Assert.AreEqual("Pre-Options.", lines[2]);
Assert.AreEqual(" s, something Input something here.", lines[4]);
Assert.AreEqual("Post-Options.", lines[6]);
}
[Test]
public void AddOptionsWithDashes()
{
var local = new HelpText {
AddDashesToOption = true,
Heading = new HeadingInfo("AddOptionsWithDashes"),
Copyright = new CopyrightInfo("Author", DateTime.Now.Year)
};
local.AddOptions(new MockOptionsSimple());
string help = local.ToString();
Console.WriteLine(help);
string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual(" -s, --something Input something here.", lines[3]);
}
[Test]
public void CreateBasicInstance()
{
var local = new HelpText();
Assert.AreEqual("", local.ToString());
}
[Test]
public void InvokeRenderParsingErrorsText()
{
var sw = new StringWriter();
var options = new RPEOptions();
var parser = new CommandLineParser(new CommandLineParserSettings {
MutuallyExclusive = true, CaseSensitive = true, HelpWriter = sw});
var result = parser.ParseArguments(new string[] {"--option-b", "hello", "-cWORLD"}, options);
Assert.IsFalse(result);
var outsw = sw.ToString();
Console.WriteLine(outsw);
var lines = outsw.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual(lines[0], "--option-b option violates format.");
Assert.AreEqual(lines[1], "-c/--option-c option violates format.");
Assert.AreEqual(lines[2], "-a required option is missing.");
}
/*
[Test]
public void AutoBuildWithRenderParsingErrorsHelper()
{
var sw = new StringWriter();
var options = new RPEOptionsForAutoBuild();
var parser = new CommandLineParser(new CommandLineParserSettings {
MutuallyExclusive = true, CaseSensitive = true, HelpWriter = sw});
var result = parser.ParseArguments(new string[] {"--option-b", "hello", "-cWORLD"}, options);
Assert.IsFalse(result);
var outsw = sw.ToString();
Console.WriteLine(outsw);
var lines = outsw.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual(lines[0], "CommandLine.Tests 1.9");
Assert.AreEqual(lines[1], "Copyright (C) 2005 - 2012 Giacomo Stelluti Scala");
Assert.AreEqual(lines[3], "ERROR(S):");
Assert.AreEqual(lines[4], " --option-b option violates format.");
Assert.AreEqual(lines[5], " -c/--option-c option violates format.");
Assert.AreEqual(lines[6], " -a required option is missing.");
Assert.AreEqual(lines[8], "This is free software. You may redistribute copies of it under the terms of");
Assert.AreEqual(lines[9], "the MIT License <http://www.opensource.org/licenses/mit-license.php>.");
Assert.AreEqual(lines[10], "[no usage, this is a dll]");
Assert.AreEqual(lines[12], " -a Required. This string option is defined A.");
Assert.AreEqual(lines[14], " --option-b This integer option is defined B.");
Assert.AreEqual(lines[16], " -c, --option-c This double option is defined C.");
Assert.AreEqual(lines[18], " --help Display this help screen.");
}
[Test]
public void AutoBuild()
{
var sw = new StringWriter();
var options = new SimpleOptionsForAutoBuid();
var parser = new CommandLineParser(new CommandLineParserSettings {
MutuallyExclusive = true, CaseSensitive = true, HelpWriter = sw});
var result = parser.ParseArguments(new string[] {}, options);
Assert.IsFalse(result);
var outsw = sw.ToString();
Console.WriteLine(outsw);
var lines = outsw.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.AreEqual(lines[0], "CommandLine.Tests 1.9");
Assert.AreEqual(lines[1], "Copyright (C) 2005 - 2012 Giacomo Stelluti Scala");
Assert.AreEqual(lines[2], "This is free software. You may redistribute copies of it under the terms of");
Assert.AreEqual(lines[3], "the MIT License <http://www.opensource.org/licenses/mit-license.php>.");
Assert.AreEqual(lines[4], "[no usage, this is a dll]");
Assert.AreEqual(lines[6], " -m, --mock Required. Force required.");
Assert.AreEqual(lines[8], " -s, --string ");
Assert.AreEqual(lines[10], " -i ");
Assert.AreEqual(lines[12], " --switch ");
Assert.AreEqual(lines[14], " --help Display this help screen.");
}*/
#region Parsing Errors Subsystem Test, related to Help Text building
[Test]
public void DetailedHelpWithBadFormat()
{
var options = new ComplexOptionsWithHelp();
bool result = new CommandLineParser(new CommandLineParserSettings(Console.Out)).ParseArguments(
new string[] { "-iIN.FILE", "-oOUT.FILE", "--offset", "abc" }, options);
Assert.IsFalse(result);
}
[Test]
public void DetailedHelpWithMissingRequired()
{
var options = new ComplexOptionsWithHelp();
bool result = new CommandLineParser(new CommandLineParserSettings(Console.Out)).ParseArguments(
new string[] { "-j0" }, options);
Assert.IsFalse(result);
}
[Test]
public void DetailedHelpWithMissingRequiredAndBadFormat()
{
var options = new ComplexOptionsWithHelp();
bool result = new CommandLineParser(new CommandLineParserSettings(Console.Out)).ParseArguments(
new string[] { "-i0" }, options);
Assert.IsFalse(result);
}
[Test]
public void DetailedHelpWithBadMutualExclusiveness()
{
var options = new ComplexOptionsWithHelp();
bool result = new CommandLineParser(new CommandLineParserSettings(true, true, Console.Out)).ParseArguments(
new string[] { "-iIN.FILE", "-oOUT.FILE", "--offset", "0", "-ap" }, options);
Assert.IsFalse(result);
}
[Test]
public void DetailedHelpWithBadFormatAndMutualExclusiveness()
{
var options = new ComplexOptionsWithHelp();
bool result = new CommandLineParser(new CommandLineParserSettings(true, true, Console.Out)).ParseArguments(
new string[] { "-iIN.FILE", "-oOUT.FILE", "--offset", "zero", "-pa" }, options);
Assert.IsFalse(result);
}
#endregion
private void CustomizeOptionsFormat_FormatOptionHelpText(object sender, FormatOptionHelpTextEventArgs e)
{
// Simulating a localization process.
string optionHelp = null;
switch (e.Option.ShortName)
{
case "v":
optionHelp = "Kommentar umfassend Operationen.";
break;
case "i":
optionHelp = "Gibt den Eingang an zu bearbeitenden Datei.";
break;
}
if (e.Option.Required)
optionHelp = "Erforderlich. " + optionHelp;
e.Option.HelpText = optionHelp;
}
}
}
| |
/*
* 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;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Code 39 barcodes. Supports "Full ASCII Code 39" if USE_CODE_39_EXTENDED_MODE is set.</p>
/// <author>Sean Owen</author>
/// @see Code93Reader
/// </summary>
public sealed class Code39Reader : OneDReader
{
internal static String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";
/// <summary>
/// Returns a string with all possible characters
/// </summary>
public static string Alphabet
{
get { return ALPHABET_STRING; }
}
/// <summary>
/// These represent the encodings of characters, as patterns of wide and narrow bars.
/// The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
/// with 1s representing "wide" and 0s representing narrow.
/// </summary>
internal static int[] CHARACTER_ENCODINGS = {
0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x0A8, // U-$
0x0A2, 0x08A, 0x02A // /-%
};
internal static readonly int ASTERISK_ENCODING = 0x094;
private readonly bool usingCheckDigit;
private readonly bool extendedMode;
private readonly StringBuilder decodeRowResult;
private readonly int[] counters;
/// <summary>
/// Creates a reader that assumes all encoded data is data, and does not treat the final
/// character as a check digit. It will not decoded "extended Code 39" sequences.
/// </summary>
public Code39Reader()
: this(false)
{
}
/// <summary>
/// Creates a reader that can be configured to check the last character as a check digit.
/// It will not decoded "extended Code 39" sequences.
/// </summary>
/// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not
/// data, and verify that the checksum passes.</param>
public Code39Reader(bool usingCheckDigit)
: this(usingCheckDigit, false)
{
}
/// <summary>
/// Creates a reader that can be configured to check the last character as a check digit,
/// or optionally attempt to decode "extended Code 39" sequences that are used to encode
/// the full ASCII character set.
/// </summary>
/// <param name="usingCheckDigit">if true, treat the last data character as a check digit, not
/// data, and verify that the checksum passes.</param>
/// <param name="extendedMode">if true, will attempt to decode extended Code 39 sequences in the text.</param>
public Code39Reader(bool usingCheckDigit, bool extendedMode)
{
this.usingCheckDigit = usingCheckDigit;
this.extendedMode = extendedMode;
decodeRowResult = new StringBuilder(20);
counters = new int[9];
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns><see cref="Result"/>containing encoded string and start/end of barcode</returns>
override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
decodeRowResult.Length = 0;
int[] start = findAsteriskPattern(row, counters);
if (start == null)
return null;
// Read off white space
int nextStart = row.getNextSet(start[1]);
int end = row.Size;
char decodedChar;
int lastStart;
do
{
if (!recordPattern(row, nextStart, counters))
return null;
int pattern = toNarrowWidePattern(counters);
if (pattern < 0)
{
return null;
}
if (!patternToChar(pattern, out decodedChar))
return null;
decodeRowResult.Append(decodedChar);
lastStart = nextStart;
foreach (int counter in counters)
{
nextStart += counter;
}
// Read off white space
nextStart = row.getNextSet(nextStart);
} while (decodedChar != '*');
decodeRowResult.Length = decodeRowResult.Length - 1; // remove asterisk
// Look for whitespace after pattern:
int lastPatternSize = 0;
foreach (int counter in counters)
{
lastPatternSize += counter;
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if (nextStart != end && (whiteSpaceAfterEnd << 1) < lastPatternSize)
{
return null;
}
// overriding constructor value is possible
bool useCode39CheckDigit = usingCheckDigit;
if (hints != null && hints.ContainsKey(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT))
{
useCode39CheckDigit = (bool)hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT];
}
if (useCode39CheckDigit)
{
int max = decodeRowResult.Length - 1;
int total = 0;
for (int i = 0; i < max; i++)
{
total += ALPHABET_STRING.IndexOf(decodeRowResult[i]);
}
if (decodeRowResult[max] != ALPHABET_STRING[total % 43])
{
return null;
}
decodeRowResult.Length = max;
}
if (decodeRowResult.Length == 0)
{
// false positive
return null;
}
// overriding constructor value is possible
bool useCode39ExtendedMode = extendedMode;
if (hints != null && hints.ContainsKey(DecodeHintType.USE_CODE_39_EXTENDED_MODE))
{
useCode39ExtendedMode = (bool)hints[DecodeHintType.USE_CODE_39_EXTENDED_MODE];
}
String resultString;
if (useCode39ExtendedMode)
{
resultString = decodeExtended(decodeRowResult.ToString());
if (resultString == null)
{
if (hints != null &&
hints.ContainsKey(DecodeHintType.RELAXED_CODE_39_EXTENDED_MODE) &&
Convert.ToBoolean(hints[DecodeHintType.RELAXED_CODE_39_EXTENDED_MODE]))
resultString = decodeRowResult.ToString();
else
return null;
}
}
else
{
resultString = decodeRowResult.ToString();
}
float left = (start[1] + start[0]) / 2.0f;
float right = lastStart + lastPatternSize / 2.0f;
var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
? null
: (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
var resultObject = new Result(
resultString,
null,
new[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODE_39);
resultObject.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]A0");
return resultObject;
}
private static int[] findAsteriskPattern(BitArray row, int[] counters)
{
int width = row.Size;
int rowOffset = row.getNextSet(0);
int counterPosition = 0;
int patternStart = rowOffset;
bool isWhite = false;
int patternLength = counters.Length;
for (int i = rowOffset; i < width; i++)
{
if (row[i] != isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (toNarrowWidePattern(counters) == ASTERISK_ENCODING)
{
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.Max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false))
{
return new int[] { patternStart, i };
}
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, counterPosition - 1);
counters[counterPosition - 1] = 0;
counters[counterPosition] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
// per image when using some of our blackbox images.
private static int toNarrowWidePattern(int[] counters)
{
int numCounters = counters.Length;
int maxNarrowCounter = 0;
int wideCounters;
do
{
int minCounter = Int32.MaxValue;
foreach (var counter in counters)
{
if (counter < minCounter && counter > maxNarrowCounter)
{
minCounter = counter;
}
}
maxNarrowCounter = minCounter;
wideCounters = 0;
int totalWideCountersWidth = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++)
{
int counter = counters[i];
if (counter > maxNarrowCounter)
{
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
totalWideCountersWidth += counter;
}
}
if (wideCounters == 3)
{
// Found 3 wide counters, but are they close enough in width?
// We can perform a cheap, conservative check to see if any individual
// counter is more than 1.5 times the average:
for (int i = 0; i < numCounters && wideCounters > 0; i++)
{
int counter = counters[i];
if (counter > maxNarrowCounter)
{
wideCounters--;
// totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
if ((counter << 1) >= totalWideCountersWidth)
{
return -1;
}
}
}
return pattern;
}
} while (wideCounters > 3);
return -1;
}
private static bool patternToChar(int pattern, out char c)
{
for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++)
{
if (CHARACTER_ENCODINGS[i] == pattern)
{
c = ALPHABET_STRING[i];
return true;
}
}
c = '*';
return pattern == ASTERISK_ENCODING;
}
private static String decodeExtended(String encoded)
{
int length = encoded.Length;
StringBuilder decoded = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
char c = encoded[i];
if (c == '+' || c == '$' || c == '%' || c == '/')
{
if (i + 1 >= encoded.Length)
{
return null;
}
char next = encoded[i + 1];
char decodedChar = '\0';
switch (c)
{
case '+':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next + 32);
}
else
{
return null;
}
break;
case '$':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next - 64);
}
else
{
return null;
}
break;
case '%':
// %A to %E map to control codes ESC to US
if (next >= 'A' && next <= 'E')
{
decodedChar = (char)(next - 38);
}
else if (next >= 'F' && next <= 'J')
{
decodedChar = (char)(next - 11);
}
else if (next >= 'K' && next <= 'O')
{
decodedChar = (char)(next + 16);
}
else if (next >= 'P' && next <= 'T')
{
decodedChar = (char)(next + 43);
}
else if (next == 'U')
{
decodedChar = (char)0;
}
else if (next == 'V')
{
decodedChar = '@';
}
else if (next == 'W')
{
decodedChar = '`';
}
else if (next == 'X' || next == 'Y' || next == 'Z')
{
decodedChar = (char)127;
}
else
{
return null;
}
break;
case '/':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O')
{
decodedChar = (char)(next - 32);
}
else if (next == 'Z')
{
decodedChar = ':';
}
else
{
return null;
}
break;
}
decoded.Append(decodedChar);
// bump up i again since we read two characters
i++;
}
else
{
decoded.Append(c);
}
}
return decoded.ToString();
}
}
}
| |
/*
* 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 cloudfront-2015-07-27.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.CloudFront;
using Amazon.CloudFront.Model;
using Amazon.CloudFront.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public partial class CloudFrontMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("cloudfront-2015-07-27.normal.json", "cloudfront.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void CreateCloudFrontOriginAccessIdentityMarshallTest()
{
var operation = service_model.FindOperation("CreateCloudFrontOriginAccessIdentity");
var request = InstantiateClassGenerator.Execute<CreateCloudFrontOriginAccessIdentityRequest>();
var marshaller = new CreateCloudFrontOriginAccessIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateCloudFrontOriginAccessIdentity", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"Location","Location_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateCloudFrontOriginAccessIdentityResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateCloudFrontOriginAccessIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void CreateDistributionMarshallTest()
{
var operation = service_model.FindOperation("CreateDistribution");
var request = InstantiateClassGenerator.Execute<CreateDistributionRequest>();
var marshaller = new CreateDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateDistribution", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"Location","Location_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateDistributionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateDistributionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void CreateInvalidationMarshallTest()
{
var operation = service_model.FindOperation("CreateInvalidation");
var request = InstantiateClassGenerator.Execute<CreateInvalidationRequest>();
var marshaller = new CreateInvalidationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateInvalidation", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"Location","Location_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateInvalidationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateInvalidationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void CreateStreamingDistributionMarshallTest()
{
var operation = service_model.FindOperation("CreateStreamingDistribution");
var request = InstantiateClassGenerator.Execute<CreateStreamingDistributionRequest>();
var marshaller = new CreateStreamingDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateStreamingDistribution", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"Location","Location_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateStreamingDistributionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateStreamingDistributionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void DeleteCloudFrontOriginAccessIdentityMarshallTest()
{
var operation = service_model.FindOperation("DeleteCloudFrontOriginAccessIdentity");
var request = InstantiateClassGenerator.Execute<DeleteCloudFrontOriginAccessIdentityRequest>();
var marshaller = new DeleteCloudFrontOriginAccessIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteCloudFrontOriginAccessIdentity", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void DeleteDistributionMarshallTest()
{
var operation = service_model.FindOperation("DeleteDistribution");
var request = InstantiateClassGenerator.Execute<DeleteDistributionRequest>();
var marshaller = new DeleteDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteDistribution", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void DeleteStreamingDistributionMarshallTest()
{
var operation = service_model.FindOperation("DeleteStreamingDistribution");
var request = InstantiateClassGenerator.Execute<DeleteStreamingDistributionRequest>();
var marshaller = new DeleteStreamingDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteStreamingDistribution", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetCloudFrontOriginAccessIdentityMarshallTest()
{
var operation = service_model.FindOperation("GetCloudFrontOriginAccessIdentity");
var request = InstantiateClassGenerator.Execute<GetCloudFrontOriginAccessIdentityRequest>();
var marshaller = new GetCloudFrontOriginAccessIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetCloudFrontOriginAccessIdentity", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetCloudFrontOriginAccessIdentityResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetCloudFrontOriginAccessIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetCloudFrontOriginAccessIdentityConfigMarshallTest()
{
var operation = service_model.FindOperation("GetCloudFrontOriginAccessIdentityConfig");
var request = InstantiateClassGenerator.Execute<GetCloudFrontOriginAccessIdentityConfigRequest>();
var marshaller = new GetCloudFrontOriginAccessIdentityConfigRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetCloudFrontOriginAccessIdentityConfig", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetCloudFrontOriginAccessIdentityConfigResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetCloudFrontOriginAccessIdentityConfigResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetDistributionMarshallTest()
{
var operation = service_model.FindOperation("GetDistribution");
var request = InstantiateClassGenerator.Execute<GetDistributionRequest>();
var marshaller = new GetDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetDistribution", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetDistributionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetDistributionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetDistributionConfigMarshallTest()
{
var operation = service_model.FindOperation("GetDistributionConfig");
var request = InstantiateClassGenerator.Execute<GetDistributionConfigRequest>();
var marshaller = new GetDistributionConfigRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetDistributionConfig", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetDistributionConfigResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetDistributionConfigResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetInvalidationMarshallTest()
{
var operation = service_model.FindOperation("GetInvalidation");
var request = InstantiateClassGenerator.Execute<GetInvalidationRequest>();
var marshaller = new GetInvalidationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetInvalidation", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetInvalidationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetInvalidationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetStreamingDistributionMarshallTest()
{
var operation = service_model.FindOperation("GetStreamingDistribution");
var request = InstantiateClassGenerator.Execute<GetStreamingDistributionRequest>();
var marshaller = new GetStreamingDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetStreamingDistribution", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetStreamingDistributionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetStreamingDistributionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void GetStreamingDistributionConfigMarshallTest()
{
var operation = service_model.FindOperation("GetStreamingDistributionConfig");
var request = InstantiateClassGenerator.Execute<GetStreamingDistributionConfigRequest>();
var marshaller = new GetStreamingDistributionConfigRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetStreamingDistributionConfig", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetStreamingDistributionConfigResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetStreamingDistributionConfigResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void ListCloudFrontOriginAccessIdentitiesMarshallTest()
{
var operation = service_model.FindOperation("ListCloudFrontOriginAccessIdentities");
var request = InstantiateClassGenerator.Execute<ListCloudFrontOriginAccessIdentitiesRequest>();
var marshaller = new ListCloudFrontOriginAccessIdentitiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListCloudFrontOriginAccessIdentities", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListCloudFrontOriginAccessIdentitiesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListCloudFrontOriginAccessIdentitiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void ListDistributionsMarshallTest()
{
var operation = service_model.FindOperation("ListDistributions");
var request = InstantiateClassGenerator.Execute<ListDistributionsRequest>();
var marshaller = new ListDistributionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListDistributions", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListDistributionsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListDistributionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void ListDistributionsByWebACLIdMarshallTest()
{
var operation = service_model.FindOperation("ListDistributionsByWebACLId");
var request = InstantiateClassGenerator.Execute<ListDistributionsByWebACLIdRequest>();
var marshaller = new ListDistributionsByWebACLIdRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListDistributionsByWebACLId", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListDistributionsByWebACLIdResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListDistributionsByWebACLIdResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void ListInvalidationsMarshallTest()
{
var operation = service_model.FindOperation("ListInvalidations");
var request = InstantiateClassGenerator.Execute<ListInvalidationsRequest>();
var marshaller = new ListInvalidationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListInvalidations", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListInvalidationsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListInvalidationsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void ListStreamingDistributionsMarshallTest()
{
var operation = service_model.FindOperation("ListStreamingDistributions");
var request = InstantiateClassGenerator.Execute<ListStreamingDistributionsRequest>();
var marshaller = new ListStreamingDistributionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListStreamingDistributions", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListStreamingDistributionsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListStreamingDistributionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void UpdateCloudFrontOriginAccessIdentityMarshallTest()
{
var operation = service_model.FindOperation("UpdateCloudFrontOriginAccessIdentity");
var request = InstantiateClassGenerator.Execute<UpdateCloudFrontOriginAccessIdentityRequest>();
var marshaller = new UpdateCloudFrontOriginAccessIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateCloudFrontOriginAccessIdentity", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateCloudFrontOriginAccessIdentityResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateCloudFrontOriginAccessIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void UpdateDistributionMarshallTest()
{
var operation = service_model.FindOperation("UpdateDistribution");
var request = InstantiateClassGenerator.Execute<UpdateDistributionRequest>();
var marshaller = new UpdateDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateDistribution", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateDistributionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateDistributionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Xml")]
[TestCategory("CloudFront")]
public void UpdateStreamingDistributionMarshallTest()
{
var operation = service_model.FindOperation("UpdateStreamingDistribution");
var request = InstantiateClassGenerator.Execute<UpdateStreamingDistributionRequest>();
var marshaller = new UpdateStreamingDistributionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateStreamingDistribution", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"ETag","ETag_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute();
var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateStreamingDistributionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateStreamingDistributionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
using FakeItEasy;
using System;
using Xunit;
public class ReactTests
{
[Fact]
public void Input_cells_have_a_value()
{
var sut = new Reactor();
var input = sut.CreateInputCell(10);
Assert.Equal(10, input.Value);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void An_input_cells_value_can_be_set()
{
var sut = new Reactor();
var input = sut.CreateInputCell(4);
input.Value = 20;
Assert.Equal(20, input.Value);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Compute_cells_calculate_initial_value()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
Assert.Equal(2, output.Value);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Compute_cells_take_inputs_in_the_right_order()
{
var sut = new Reactor();
var one = sut.CreateInputCell(1);
var two = sut.CreateInputCell(2);
var output = sut.CreateComputeCell(new[] { one, two }, inputs => inputs[0] + inputs[1] * 10);
Assert.Equal(21, output.Value);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Compute_cells_update_value_when_dependencies_are_changed()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
input.Value = 3;
Assert.Equal(4, output.Value);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Compute_cells_can_depend_on_other_compute_cells()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var timesTwo = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] * 2);
var timesThirty = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] * 30);
var output = sut.CreateComputeCell(new[] { timesTwo, timesThirty }, inputs => inputs[0] + inputs[1]);
Assert.Equal(32, output.Value);
input.Value = 3;
Assert.Equal(96, output.Value);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Compute_cells_fire_callbacks()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var callback1 = A.Fake<EventHandler<int>>();
output.Changed += callback1;
input.Value = 3;
A.CallTo(() => callback1.Invoke(A<object>._, 4)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Callback_cells_only_fire_on_change()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] < 3 ? 111 : 222);
var callback1 = A.Fake<EventHandler<int>>();
output.Changed += callback1;
input.Value = 2;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
input.Value = 4;
A.CallTo(() => callback1.Invoke(A<object>._, 222)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Callbacks_do_not_report_already_reported_values()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var callback1 = A.Fake<EventHandler<int>>();
output.Changed += callback1;
input.Value = 2;
A.CallTo(() => callback1.Invoke(A<object>._, 3)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
input.Value = 3;
A.CallTo(() => callback1.Invoke(A<object>._, 4)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Callbacks_can_fire_from_multiple_cells()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var plusOne = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var minusOne = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] - 1);
var callback1 = A.Fake<EventHandler<int>>();
plusOne.Changed += callback1;
var callback2 = A.Fake<EventHandler<int>>();
minusOne.Changed += callback2;
input.Value = 10;
A.CallTo(() => callback1.Invoke(A<object>._, 11)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
A.CallTo(() => callback2.Invoke(A<object>._, 9)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback2);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Callbacks_can_be_added_and_removed()
{
var sut = new Reactor();
var input = sut.CreateInputCell(11);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var callback1 = A.Fake<EventHandler<int>>();
output.Changed += callback1;
var callback2 = A.Fake<EventHandler<int>>();
output.Changed += callback2;
input.Value = 31;
A.CallTo(() => callback1.Invoke(A<object>._, 32)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
A.CallTo(() => callback2.Invoke(A<object>._, 32)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback2);
output.Changed -= callback1;
var callback3 = A.Fake<EventHandler<int>>();
output.Changed += callback3;
input.Value = 41;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Removing_a_callback_multiple_times_doesnt_interfere_with_other_callbacks()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var output = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var callback1 = A.Fake<EventHandler<int>>();
output.Changed += callback1;
var callback2 = A.Fake<EventHandler<int>>();
output.Changed += callback2;
output.Changed -= callback1;
output.Changed -= callback1;
output.Changed -= callback1;
input.Value = 2;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Callbacks_should_only_be_called_once_even_if_multiple_dependencies_change()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var plusOne = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var minusOne1 = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] - 1);
var minusOne2 = sut.CreateComputeCell(new[] { minusOne1 }, inputs => inputs[0] - 1);
var output = sut.CreateComputeCell(new[] { plusOne, minusOne2 }, inputs => inputs[0] * inputs[1]);
var callback1 = A.Fake<EventHandler<int>>();
output.Changed += callback1;
input.Value = 4;
A.CallTo(() => callback1.Invoke(A<object>._, 10)).MustHaveHappenedOnceExactly();
Fake.ClearRecordedCalls(callback1);
}
[Fact(Skip = "Remove this Skip property to run this test")]
public void Callbacks_should_not_be_called_if_dependencies_change_but_output_value_doesnt_change()
{
var sut = new Reactor();
var input = sut.CreateInputCell(1);
var plusOne = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] + 1);
var minusOne = sut.CreateComputeCell(new[] { input }, inputs => inputs[0] - 1);
var alwaysTwo = sut.CreateComputeCell(new[] { plusOne, minusOne }, inputs => inputs[0] - inputs[1]);
var callback1 = A.Fake<EventHandler<int>>();
alwaysTwo.Changed += callback1;
input.Value = 2;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
input.Value = 3;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
input.Value = 4;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
input.Value = 5;
A.CallTo(() => callback1.Invoke(A<object>._, A<int>._)).MustNotHaveHappened();
}
}
| |
/**
******************************************************************************
* @file USBDeviceInfo.cs
* @author Mitter Gilbert
* @version V1.0.0
* @date 26.04.2017
* @brief Represents a USB object.
******************************************************************************
*/
using System;
using System.Text;
using System.Management;
using Microsoft.Win32;
using System.Security.Cryptography;
namespace BadUSB_Firewall
{
/// <summary>
/// Description
/// </summary>
/// <param name="">Param Description</param>
public class USBDeviceInfo : IEquatable<USBDeviceInfo>
{
//Creates an empty USBDeviceInfo object and assigns the values for device detection.
public USBDeviceInfo()
{
Checksum = "";
ClassGuid = ""; //Guid for the device's setup class
CompatibleID = ""; //ID string(s) containign the device's class and (optional) subclass and protocol
Description = "";
DateAdded = "";
DateConnected = "";
DeviceID = "";
DeviceType = "";
HardwareID = ""; //ID string containing the device's Vendor ID and Product ID
FirstUsage = "Yes";
FirstLocationInformation = ""; //USB device or iProduct string
LastLocationInformation = ""; //USB device or iProduct string
Manufacturer = ""; //device manufacturer
Name = "";
ProductID = "";
ProductName = "";
SerialNumber = "";
Service = ""; //Name of the device's Service key
Status = "";
USB_Class = "";
USB_SubClass = "";
USB_Protocol = "";
VendorID = "";
VendorName = "";
}
/// <summary>
/// Obtain a USBDeviceInfo object from a ManaementBase object (obtained through a WMI query).
/// </summary>
/// <param name="">Param Description</param>
public USBDeviceInfo(ManagementBaseObject device)
{
try
{
ClassGuid = device.Properties["ClassGuid"].Value == null ? "" : device.Properties["ClassGuid"].Value.ToString();
if (device.Properties["CompatibleID"].Value != null)
{
string[] value = (string[])device.Properties["CompatibleID"].Value;
if (value == null) { CompatibleID = ""; }
else
{
for (int i = 0; i < value.Length; i++)
{
CompatibleID += value[i];
if (i < value.Length - 1)
{
CompatibleID += " ";
}
}
}
}
else
{
CompatibleID = "";
}
DateConnected = DateTime.Now.ToString();
DateAdded = "";
Description = device.Properties["Description"].Value == null ? "" : device.Properties["Description"].Value.ToString();
DeviceID = device.Properties["DeviceID"].Value == null ? "" : device.Properties["DeviceID"].Value.ToString();
if (device.Properties["HardwareID"].Value != null)
{
string[] value = (string[])device.Properties["HardwareID"].Value;
if (value == null)
{
HardwareID = "";
}
else
{
if (value.Length > 0)
{
HardwareID = value[0];
}
else
{
HardwareID = "";
}
}
}
else
{
HardwareID = "";
}
Manufacturer = device.Properties["Manufacturer"].Value == null ? "" : device.Properties["Manufacturer"].Value.ToString();
Name = device.Properties["Name"].Value == null ? "" : device.Properties["Name"].Value.ToString();
Service = device.Properties["Service"].Value == null ? "" : device.Properties["Service"].Value.ToString();
Status = device.Properties["Status"].Value == null ? "" : device.Properties["Status"].Value.ToString();
FirstLocationInformation = GetDeviceLocation(DeviceID);
FirstUsage = "Yes";
LastLocationInformation = FirstLocationInformation;
USB_Class = "";
USB_SubClass = "";
USB_Protocol = "";
if (!string.IsNullOrEmpty(CompatibleID))
{
int classStart = CompatibleID.IndexOf("Class_");
if (classStart > -1)
{
USB_Class = CompatibleID.Substring(classStart + 6, 2);
int subClassStart = CompatibleID.IndexOf("SubClass_");
if (subClassStart > -1)
{
USB_SubClass = CompatibleID.Substring(subClassStart + 9, 2);
int protocolStart = CompatibleID.IndexOf("Prot_");
if (protocolStart > -1)
{
USB_Protocol = CompatibleID.Substring(protocolStart + 5, 2);
}
}
}
}
VendorName = "";
ProductName = "";
ProductID = "";
VendorID = "";
int serialStart = 0;
//get vendor id and product id
if (!string.IsNullOrEmpty(DeviceID))
{
int vidStart = DeviceID.IndexOf("VID_");
if (vidStart > -1)
{
//remove VID_ and get Vendor ID
VendorID = DeviceID.Substring(vidStart + 4, 4);
int pidStart = DeviceID.IndexOf("PID_");
if (pidStart > -1)
{
//remove PID_ and get Product ID
ProductID = DeviceID.Substring(pidStart + 4, 4);
serialStart = pidStart + 9;
}
}
}
if (DeviceID.Length - serialStart > 0)
{
string sNum = DeviceID.Substring(serialStart, (DeviceID.Length - serialStart));
if (!sNum.Contains("&")) { SerialNumber = sNum; }
else { SerialNumber = ""; }
}
else { SerialNumber = ""; }
//get the device type if possible
DeviceType = DeviceClass.GetClassDevice(this);
//generate the checksum
Checksum = GenerateHashCode(ClassGuid + Description + DeviceType + HardwareID +
ProductID + ProductName + SerialNumber + Service +
USB_Class + USB_SubClass + USB_Protocol + VendorID + VendorName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);//change to log file
}
}
/// <summary>
/// Description
/// </summary>
/// <param name="">Param Description</param>
public bool Equals(USBDeviceInfo other)
{
if (other != null && Checksum != other.Checksum) return false;
return true;
}
public string Checksum { get; set; }
public string ClassGuid { get; set; }
public string CompatibleID { get; set; }
public string Description { get; set; }
public string DateAdded { get; set; }
public string DateConnected { get; set; }
public string DeviceID { get; set; }
public string DeviceType { get; set; }
public string HardwareID { get; set; }
public string FirstLocationInformation { get; set; }
public string FirstUsage { get; set; }
public string LastLocationInformation { get; set; }
public string Manufacturer { get; set; }
public string Name { get; set; }
public string ProductID { get; set; }
public string ProductName { get; set; }
public string SerialNumber { get; set; }
public string Service { get; set; }
public string Status { get; set; }
public string USB_Class { get; set; }
public string USB_SubClass { get; set; }
public string USB_Protocol { get; set; }
public string VendorID { get; set; }
public string VendorName { get; set; }
/// <summary>
/// Create checksum
/// </summary>
/// <param name="">Param Description</param>
public static string GenerateHashCode(string data)
{
string generatedHash = "";
try
{
MD5 md5Hash = MD5.Create();
// Convert string to a byte array and compute the hash.
byte[] hashData = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
StringBuilder sBuilder = new StringBuilder();
// Loop through the hashed data and build a hexadecimal string
for (int i = 0; i < hashData.Length; i++)
{
sBuilder.Append(hashData[i].ToString("x2"));
}
// Build string from hex-value
generatedHash = sBuilder.ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);//change to log file
return string.Empty;
}
return generatedHash;
}
/// <summary>
/// Description
/// </summary>
/// <param name="">Param Description</param>
//Outsorce code generation to c++ dll ?
public void generate_HashCodeParentDevice(string childData)
{
try
{
string data = GenerateHashCode(Checksum + childData);
Checksum = data;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);//change to log file
}
}
/// <summary>
/// Port connection of a device via the registry
/// </summary>
/// <param name="">Param Description</param>
private string GetDeviceLocation(string deviceID)
{
string location = "";
string[] parts = deviceID.Split(@"\".ToCharArray());
if (parts.Length >= 3)
{
string devRegPath = @"SYSTEM\CurrentControlSet\Enum\" + parts[0] + "\\" + parts[1] + "\\" + parts[2];
RegistryKey key = Registry.LocalMachine.OpenSubKey(devRegPath);
if (key != null)
{
object result2 = key.GetValue("LocationInformation");
if (result2 != null)
{
location = result2.ToString();
}
key.Close();
}
}
return location;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Sql.DataMasking.Model;
using Microsoft.Azure.Commands.Sql.Server.Services;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Microsoft.Azure.Commands.Sql.DataMasking.Services
{
/// <summary>
/// The SqlDataMaskingClient class is responsible for transforming the data that was received form the endpoints to the cmdlets model of data masking policy and vice versa
/// </summary>
public class SqlDataMaskingAdapter
{
/// <summary>
/// Gets or sets the Azure subscription
/// </summary>
private IAzureSubscription Subscription { get; set; }
/// <summary>
/// The communicator that this adapter uses
/// </summary>
private DataMaskingEndpointsCommunicator Communicator { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
public SqlDataMaskingAdapter(IAzureContext context)
{
Context = context;
Subscription = context.Subscription;
Communicator = new DataMaskingEndpointsCommunicator(Context);
}
/// <summary>
/// Checks whether the server is applicable for dynamic data masking
/// </summary>
private bool IsRightServerVersionForDataMasking(string resourceGroupName, string serverName)
{
AzureSqlServerCommunicator dbCommunicator = new AzureSqlServerCommunicator(Context);
Management.Sql.Models.Server server = dbCommunicator.Get(resourceGroupName, serverName);
return server.Version == "12.0";
}
/// <summary>
/// Provides a cmdlet model representation of a specific database's data making policy
/// </summary>
public DatabaseDataMaskingPolicyModel GetDatabaseDataMaskingPolicy(string resourceGroup, string serverName, string databaseName)
{
if (!IsRightServerVersionForDataMasking(resourceGroup, serverName))
{
throw new Exception(Properties.Resources.ServerNotApplicableForDataMasking);
}
DataMaskingPolicy policy = Communicator.GetDatabaseDataMaskingPolicy(resourceGroup, serverName, databaseName);
DatabaseDataMaskingPolicyModel dbPolicyModel = ModelizeDatabaseDataMaskingPolicy(policy);
dbPolicyModel.ResourceGroupName = resourceGroup;
dbPolicyModel.ServerName = serverName;
dbPolicyModel.DatabaseName = databaseName;
return dbPolicyModel;
}
/// <summary>
/// Sets the data masking policy of a specific database to be based on the information provided by the model object
/// </summary>
public void SetDatabaseDataMaskingPolicy(DatabaseDataMaskingPolicyModel model)
{
if (!IsRightServerVersionForDataMasking(model.ResourceGroupName, model.ServerName))
{
throw new Exception(Properties.Resources.ServerNotApplicableForDataMasking);
}
DataMaskingPolicyCreateOrUpdateParameters parameters = PolicizeDatabaseDataMaskingModel(model);
Communicator.SetDatabaseDataMaskingPolicy(model.ResourceGroupName, model.ServerName, model.DatabaseName, parameters);
}
/// <summary>
/// Provides the data masking rule model for a specific data masking rule
/// </summary>
public IList<DatabaseDataMaskingRuleModel> GetDatabaseDataMaskingRules(string resourceGroup, string serverName, string databaseName)
{
return Communicator.ListDataMaskingRules(resourceGroup, serverName, databaseName).
Select(r => ModelizeDatabaseDataMaskingRule(r, resourceGroup, serverName, databaseName)).
ToList();
}
/// <summary>
/// Sets a data masking rule based on the information provided by the model object
/// </summary>
public void SetDatabaseDataMaskingRule(DatabaseDataMaskingRuleModel model)
{
if (!IsRightServerVersionForDataMasking(model.ResourceGroupName, model.ServerName))
{
throw new Exception(Properties.Resources.ServerNotApplicableForDataMasking);
}
DatabaseDataMaskingPolicyModel policyModel = GetDatabaseDataMaskingPolicy(model.ResourceGroupName, model.ServerName, model.DatabaseName);
if (policyModel.DataMaskingState == DataMaskingStateType.Uninitialized)
{
policyModel.DataMaskingState = DataMaskingStateType.Enabled;
SetDatabaseDataMaskingPolicy(policyModel);
}
DataMaskingRuleCreateOrUpdateParameters parameters = PolicizeDatabaseDataRuleModel(model);
Communicator.SetDatabaseDataMaskingRule(model.ResourceGroupName, model.ServerName, model.DatabaseName, ExtractDataMaskingRuleId(model), parameters);
}
/// <summary>
/// Removes a data masking rule based on the information provided by the model object
/// </summary>
public void RemoveDatabaseDataMaskingRule(DatabaseDataMaskingRuleModel model)
{
if (!IsRightServerVersionForDataMasking(model.ResourceGroupName, model.ServerName))
{
throw new Exception(Properties.Resources.ServerNotApplicableForDataMasking);
}
DataMaskingRuleCreateOrUpdateParameters parameters = PolicizeDatabaseDataRuleModel(model);
parameters.Properties.RuleState = SecurityConstants.Disabled;
string ruleId = ExtractDataMaskingRuleId(model);
Communicator.SetDatabaseDataMaskingRule(model.ResourceGroupName, model.ServerName, model.DatabaseName, ruleId, parameters);
}
private string ExtractDataMaskingRuleId(DatabaseDataMaskingRuleModel model)
{
var baseId = string.Format("{0}_{1}_{2}", model.SchemaName, model.TableName, model.ColumnName);
Regex rgx = new Regex("[/\\\\#+=<>*%&:?.]");
return rgx.Replace(baseId, "");
}
/// <summary>
/// Takes the cmdlets model object and transform it to the policy as expected by the endpoint
/// </summary>
/// <param name="model">The data masking Policy model object</param>
/// <returns>The communication model object</returns>
private DataMaskingRuleCreateOrUpdateParameters PolicizeDatabaseDataRuleModel(DatabaseDataMaskingRuleModel model)
{
DataMaskingRuleCreateOrUpdateParameters updateParameters = new DataMaskingRuleCreateOrUpdateParameters();
DataMaskingRuleProperties properties = new DataMaskingRuleProperties();
updateParameters.Properties = properties;
properties.Id = ExtractDataMaskingRuleId(model);
properties.TableName = model.TableName;
properties.SchemaName = model.SchemaName;
properties.ColumnName = model.ColumnName;
properties.MaskingFunction = PolicizeMaskingFunction(model.MaskingFunction);
properties.PrefixSize = (model.PrefixSize == null) ? null : model.PrefixSize.ToString();
properties.ReplacementString = model.ReplacementString;
properties.SuffixSize = (model.SuffixSize == null) ? null : model.SuffixSize.ToString();
properties.NumberFrom = (model.NumberFrom == null) ? null : model.NumberFrom.ToString();
properties.NumberTo = (model.NumberTo == null) ? null : model.NumberTo.ToString();
properties.RuleState = SecurityConstants.Enabled;
return updateParameters;
}
/// <summary>
/// Transforms a masking function in its model representation to its string representation
/// </summary>
private string PolicizeMaskingFunction(MaskingFunction maskingFunction)
{
switch (maskingFunction)
{
case MaskingFunction.NoMasking: return SecurityConstants.DataMaskingEndpoint.NoMasking;
case MaskingFunction.Default: return SecurityConstants.DataMaskingEndpoint.Default;
case MaskingFunction.CreditCardNumber: return SecurityConstants.DataMaskingEndpoint.CCN;
case MaskingFunction.SocialSecurityNumber: return SecurityConstants.DataMaskingEndpoint.SSN;
case MaskingFunction.Number: return SecurityConstants.DataMaskingEndpoint.Number;
case MaskingFunction.Text: return SecurityConstants.DataMaskingEndpoint.Text;
case MaskingFunction.Email: return SecurityConstants.DataMaskingEndpoint.Email;
}
return null;
}
/// <summary>
/// Transforms a data masking rule to its cmdlet model representation
/// </summary>
private DatabaseDataMaskingRuleModel ModelizeDatabaseDataMaskingRule(DataMaskingRule rule, string resourceGroup, string serverName, string databaseName)
{
DatabaseDataMaskingRuleModel dbRuleModel = new DatabaseDataMaskingRuleModel();
DataMaskingRuleProperties properties = rule.Properties;
dbRuleModel.ResourceGroupName = resourceGroup;
dbRuleModel.ServerName = serverName;
dbRuleModel.DatabaseName = databaseName;
dbRuleModel.ColumnName = properties.ColumnName;
dbRuleModel.TableName = properties.TableName;
dbRuleModel.SchemaName = properties.SchemaName;
dbRuleModel.MaskingFunction = ModelizeMaskingFunction(properties.MaskingFunction);
dbRuleModel.PrefixSize = ModelizeNullableUint(properties.PrefixSize);
dbRuleModel.ReplacementString = properties.ReplacementString;
dbRuleModel.SuffixSize = ModelizeNullableUint(properties.SuffixSize);
dbRuleModel.NumberFrom = ModelizeNullableDouble(properties.NumberFrom);
dbRuleModel.NumberTo = ModelizeNullableDouble(properties.NumberTo);
return dbRuleModel;
}
/// <summary>
/// Transforms a data masking function from its string representation to its model representation
/// </summary>
private MaskingFunction ModelizeMaskingFunction(string maskingFunction)
{
if (maskingFunction == SecurityConstants.DataMaskingEndpoint.Text) return MaskingFunction.Text;
if (maskingFunction == SecurityConstants.DataMaskingEndpoint.Default) return MaskingFunction.Default;
if (maskingFunction == SecurityConstants.DataMaskingEndpoint.Number) return MaskingFunction.Number;
if (maskingFunction == SecurityConstants.DataMaskingEndpoint.SSN) return MaskingFunction.SocialSecurityNumber;
if (maskingFunction == SecurityConstants.DataMaskingEndpoint.CCN) return MaskingFunction.CreditCardNumber;
if (maskingFunction == SecurityConstants.DataMaskingEndpoint.Email) return MaskingFunction.Email;
return MaskingFunction.NoMasking;
}
/// <summary>
/// Transforms a value from its string representation to its nullable uint representation
/// </summary>
private uint? ModelizeNullableUint(string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return Convert.ToUInt32(value);
}
/// <summary>
/// Transforms a value from its string representation to its nullable double representation
/// </summary>
private double? ModelizeNullableDouble(string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
return Convert.ToDouble(value);
}
/// <summary>
/// Transforms a data masking policy state from its string representation to its model representation
/// </summary>
private DataMaskingStateType ModelizePolicyState(string policyState)
{
if (SecurityConstants.DataMaskingEndpoint.Enabled == policyState)
{
return DataMaskingStateType.Enabled;
}
if (SecurityConstants.DataMaskingEndpoint.Disabled == policyState)
{
return DataMaskingStateType.Disabled;
}
return DataMaskingStateType.Uninitialized;
}
/// <summary>
/// Transforms a data masking policy to its cmdlet model representation
/// </summary>
private DatabaseDataMaskingPolicyModel ModelizeDatabaseDataMaskingPolicy(DataMaskingPolicy policy)
{
DatabaseDataMaskingPolicyModel dbPolicyModel = new DatabaseDataMaskingPolicyModel();
DataMaskingPolicyProperties properties = policy.Properties;
dbPolicyModel.DataMaskingState = ModelizePolicyState(properties.DataMaskingState);
dbPolicyModel.PrivilegedUsers = properties.ExemptPrincipals;
return dbPolicyModel;
}
/// <summary>
/// Takes the cmdlets model object and transform it to the policy as expected by the endpoint
/// </summary>
/// <param name="model">The data masking Policy model object</param>
/// <returns>The communication model object</returns>
private DataMaskingPolicyCreateOrUpdateParameters PolicizeDatabaseDataMaskingModel(DatabaseDataMaskingPolicyModel model)
{
DataMaskingPolicyCreateOrUpdateParameters updateParameters = new DataMaskingPolicyCreateOrUpdateParameters();
DataMaskingPolicyProperties properties = new DataMaskingPolicyProperties();
updateParameters.Properties = properties;
properties.DataMaskingState = (model.DataMaskingState == DataMaskingStateType.Disabled) ? SecurityConstants.DataMaskingEndpoint.Disabled : SecurityConstants.DataMaskingEndpoint.Enabled;
properties.ExemptPrincipals = model.PrivilegedUsers ?? "";
return updateParameters;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.ObjectModel;
using System.Management.Automation.Language;
using System.Diagnostics;
using System.Management.Automation.Host;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Runspaces;
namespace System.Management.Automation.Internal
{
/// <summary>
/// Defines members used by Cmdlets.
/// All Cmdlets must derive from
/// <see cref="System.Management.Automation.Cmdlet"/>.
/// </summary>
/// <remarks>
/// Only use <see cref="System.Management.Automation.Internal.InternalCommand"/>
/// as a subclass of
/// <see cref="System.Management.Automation.Cmdlet"/>.
/// Do not attempt to create instances of
/// <see cref="System.Management.Automation.Internal.InternalCommand"/>
/// independently, or to derive other classes than
/// <see cref="System.Management.Automation.Cmdlet"/> from
/// <see cref="System.Management.Automation.Internal.InternalCommand"/>.
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet"/>
/// <!--
/// These are the Cmdlet members which are also used by other
/// non-public command types.
///
/// Ideally this would be an internal class, but C# does not support
/// public classes deriving from internal classes.
/// -->
[DebuggerDisplay("Command = {commandInfo}")]
public abstract class InternalCommand
{
#region private_members
internal ICommandRuntime commandRuntime;
#endregion private_members
#region ctor
/// <summary>
/// Initializes the new instance of Cmdlet class.
/// </summary>
/// <remarks>
/// The only constructor is internal, so outside users cannot create
/// an instance of this class.
/// </remarks>
internal InternalCommand()
{
this.CommandInfo = null;
}
#endregion ctor
#region internal_members
/// <summary>
/// Allows you to access the calling token for this command invocation...
/// </summary>
/// <value></value>
internal IScriptExtent InvocationExtent { get; set; }
private InvocationInfo _myInvocation = null;
/// <summary>
/// Return the invocation data object for this command.
/// </summary>
/// <value>The invocation object for this command.</value>
internal InvocationInfo MyInvocation
{
get { return _myInvocation ?? (_myInvocation = new InvocationInfo(this)); }
}
/// <summary>
/// Represents the current pipeline object under consideration.
/// </summary>
internal PSObject currentObjectInPipeline = AutomationNull.Value;
/// <summary>
/// Gets or sets the current pipeline object under consideration
/// </summary>
internal PSObject CurrentPipelineObject
{
get { return currentObjectInPipeline; }
set
{
currentObjectInPipeline = value;
}
}
/// <summary>
/// Internal helper. Interface that should be used for interaction with host.
/// </summary>
internal PSHost PSHostInternal
{
get { return _CBhost; }
}
private PSHost _CBhost;
/// <summary>
/// Internal helper to get to SessionState
/// </summary>
///
internal SessionState InternalState
{
get { return _state; }
}
private SessionState _state;
/// <summary>
/// Internal helper. Indicates whether stop has been requested on this command.
/// </summary>
internal bool IsStopping
{
get
{
MshCommandRuntime mcr = this.commandRuntime as MshCommandRuntime;
return (mcr != null && mcr.IsStopping);
}
}
/// <summary>
/// The information about the command.
/// </summary>
private CommandInfo _commandInfo;
/// <summary>
/// Gets or sets the command information for the command.
/// </summary>
internal CommandInfo CommandInfo
{
get { return _commandInfo; }
set { _commandInfo = value; }
}
#endregion internal_members
#region public_properties
/// <summary>
/// Gets or sets the execution context.
/// </summary>
/// <exception cref="System.ArgumentNullException">
/// may not be set to null
/// </exception>
internal ExecutionContext Context
{
get { return _context; }
set
{
if (value == null)
{
throw PSTraceSource.NewArgumentNullException("Context");
}
_context = value;
Diagnostics.Assert(_context.EngineHostInterface is InternalHost, "context.EngineHostInterface is not an InternalHost");
_CBhost = (InternalHost)_context.EngineHostInterface;
// Construct the session state API set from the new context
_state = new SessionState(_context.EngineSessionState);
}
}
private ExecutionContext _context;
/// <summary>
/// This property tells you if you were being invoked inside the runspace or
/// if it was an external request.
/// </summary>
public CommandOrigin CommandOrigin
{
get { return CommandOriginInternal; }
}
internal CommandOrigin CommandOriginInternal = CommandOrigin.Internal;
#endregion public_properties
#region Override
/// <summary>
/// When overridden in the derived class, performs initialization
/// of command execution.
/// Default implementation in the base class just returns.
/// </summary>
internal virtual void DoBeginProcessing()
{
}
/// <summary>
/// When overridden in the derived class, performs execution
/// of the command.
/// </summary>
internal virtual void DoProcessRecord()
{
}
/// <summary>
/// When overridden in the derived class, performs clean-up
/// after the command execution.
/// Default implementation in the base class just returns.
/// </summary>
internal virtual void DoEndProcessing()
{
}
/// <summary>
/// When overridden in the derived class, interrupts currently
/// running code within the command. It should interrupt BeginProcessing,
/// ProcessRecord, and EndProcessing.
/// Default implementation in the base class just returns.
/// </summary>
internal virtual void DoStopProcessing()
{
}
#endregion Override
/// <summary>
/// throws if the pipeline is stopping
/// </summary>
/// <exception cref="System.Management.Automation.PipelineStoppedException"></exception>
internal void ThrowIfStopping()
{
if (IsStopping)
throw new PipelineStoppedException();
}
#region Dispose
/// <summary>
/// IDisposable implementation
/// When the command is complete, release the associated memmbers
/// </summary>
/// <remarks>
/// Using InternalDispose instead of Dispose pattern because this
/// interface was shipped in PowerShell V1 and 3rd cmdlets indirectly
/// derive from this inerface. If we depend on Dispose() and 3rd
/// party cmdlets do not call base.Dispose (which is the case), we
/// will still end up having this leak.
/// </remarks>
internal void InternalDispose(bool isDisposing)
{
_myInvocation = null;
_state = null;
_commandInfo = null;
_context = null;
}
#endregion
}
}
namespace System.Management.Automation
{
#region ActionPreference
/// <summary>
/// Defines the Action Preference options. These options determine
/// what will happen when a particular type of event occurs.
/// For example, setting shell variable ErrorActionPreference to "Stop"
/// will cause the command to stop when an otherwise non-terminating
/// error occurs.
/// </summary>
public enum ActionPreference
{
/// <summary>Ignore this event and continue</summary>
SilentlyContinue,
/// <summary>Stop the command</summary>
Stop,
/// <summary>Handle this event as normal and continue</summary>
Continue,
/// <summary>Ask whether to stop or continue</summary>
Inquire,
/// <summary>Ignore the event completely (not even logging it to the target stream)</summary>
Ignore,
/// <summary>Suspend the command for further diagnosis. Supported only for workflows.</summary>
Suspend,
} // enum ActionPreference
#endregion ActionPreference
#region ConfirmImpact
/// <summary>
/// Defines the ConfirmImpact levels. These levels describe
/// the "destructiveness" of an action, and thus the degree of
/// important that the user confirm the action.
/// For example, setting the read-only flag on a file might be Low,
/// and reformatting a disk might be High.
/// These levels are also used in $ConfirmPreference to describe
/// which operations should be confirmed. Operations with ConfirmImpact
/// equal to or greater than $ConfirmPreference are confirmed.
/// Operations with ConfirmImpact.None are never confirmed, and
/// no operations are confirmed when $ConfirmPreference is ConfirmImpact.None
/// (except when explicitly requested with -Confirm).
/// </summary>
public enum ConfirmImpact
{
/// <summary>There is never any need to confirm this action.</summary>
None,
/// <summary>
/// This action only needs to be confirmed when the
/// user has requested that low-impact changes must be confirmed.
/// </summary>
Low,
/// <summary>
/// This action should be confirmed in most scenarios where
/// confirmation is requested.
/// </summary>
Medium,
/// <summary>
/// This action is potentially highly "destructive" and should be
/// confirmed by default unless otherwise specified.
/// </summary>
High,
} // enum ConfirmImpact
#endregion ConfirmImpact
/// <summary>
/// Defines members and overrides used by Cmdlets.
/// All Cmdlets must derive from <see cref="System.Management.Automation.Cmdlet"/>.
/// </summary>
/// <remarks>
/// There are two ways to create a Cmdlet: by deriving from the Cmdlet base class, and by
/// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by
/// which users create their own Cmdlets. Extending this class provides support for the most
/// common functionality, including object output and record processing.
/// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state,
/// access to the host, or information about the current Cmdlet Providers,) then you should instead
/// derive from the PSCmdlet base class.
/// The public members defined by the PSCmdlet class are not designed to be overridden; instead, they
/// provided access to different aspects of the MSH runtime.
/// In both cases, users should first develop and implement an object model to accomplish their
/// task, extending the Cmdlet or PSCmdlet classes only as a thin management layer.
/// </remarks>
/// <seealso cref="System.Management.Automation.Internal.InternalCommand"/>
public abstract partial class PSCmdlet : Cmdlet
{
#region private_members
private ProviderIntrinsics _invokeProvider = null;
#endregion private_members
#region public_properties
/// <summary>
/// Gets the host interaction APIs.
/// </summary>
public PSHost Host
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return PSHostInternal;
}
}
}
/// <summary>
/// Gets the instance of session state for the current runspace.
/// </summary>
public SessionState SessionState
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return this.InternalState;
}
}
} // SessionState
/// <summary>
/// Gets the event manager for the current runspace.
/// </summary>
public PSEventManager Events
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return this.Context.Events;
}
}
} // Events
/// <summary>
/// Repostiory for jobs
/// </summary>
public JobRepository JobRepository
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return ((LocalRunspace)this.Context.CurrentRunspace).JobRepository;
}
}
}
/// <summary>
/// Manager for JobSourceAdapters registered.
/// </summary>
public JobManager JobManager
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return ((LocalRunspace)this.Context.CurrentRunspace).JobManager;
}
}
}
/// <summary>
/// Repository for runspaces
/// </summary>
internal RunspaceRepository RunspaceRepository
{
get
{
return ((LocalRunspace)this.Context.CurrentRunspace).RunspaceRepository;
}
}
/// <summary>
/// Gets the instance of the provider interface APIs for the current runspace.
/// </summary>
public ProviderIntrinsics InvokeProvider
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this));
}
}
} // InvokeProvider
#region Provider wrappers
/// <Content contentref="System.Management.Automation.PathIntrinsics.CurrentProviderLocation" />
public PathInfo CurrentProviderLocation(string providerId)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
if (providerId == null)
{
throw PSTraceSource.NewArgumentNullException("providerId");
}
PathInfo result = SessionState.Path.CurrentProviderLocation(providerId);
Diagnostics.Assert(result != null, "DataStoreAdapterCollection.GetNamespaceCurrentLocation() should " + "throw an exception, not return null");
return result;
}
}
/// <Content contentref="System.Management.Automation.PathIntrinsics.GetUnresolvedProviderPathFromPSPath" />
public string GetUnresolvedProviderPathFromPSPath(string path)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
}
} // GetUnresolvedProviderPathFromPSPath
/// <Content contentref="System.Management.Automation.PathIntrinsics.GetResolvedProviderPathFromPSPath" />
public Collection<string> GetResolvedProviderPathFromPSPath(string path, out ProviderInfo provider)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);
}
} // GetResolvedProviderPathFromPSPath
#endregion Provider wrappers
#endregion internal_members
#region ctor
/// <summary>
/// Initializes the new instance of PSCmdlet class.
/// </summary>
/// <remarks>
/// Only subclasses of <see cref="System.Management.Automation.Cmdlet"/>
/// can be created.
/// </remarks>
protected PSCmdlet()
{
}
#endregion ctor
#region public_methods
#region PSVariable APIs
/// <Content contentref="System.Management.Automation.VariableIntrinsics.GetValue" />
public object GetVariableValue(string name)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return this.SessionState.PSVariable.GetValue(name);
}
} // GetVariableValue
/// <Content contentref="System.Management.Automation.VariableIntrinsics.GetValue" />
public object GetVariableValue(string name, object defaultValue)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return this.SessionState.PSVariable.GetValue(name, defaultValue);
}
} // GetVariableValue
#endregion PSVariable APIs
#region Parameter methods
#endregion Parameter methods
#endregion public_methods
} // PSCmdlet
}
| |
//
// ChangePhotoPathController.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// ChangePhotoPath.IChangePhotoPathController.cs: The logic to change the photo path in photos.db
//
// Author:
// Bengt Thuree (bengt@thuree.com)
//
// Copyright (C) 2007
//
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.Specialized;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Utils;
using Hyena;
/*
Need to
1) Find old base path, assuming starting /YYYY/MM/DD so look for /YY (/19 or /20)
2) Confirm old base path and display new base path
3) For each Photo, check each version, and change every instance of old base path to new path
Consider!!!
photo_store.Commit(photo) is using db.ExecuteNonQuery, which is not waiting for the command to finish. On my test set of 20.000 photos,
it took SQLite another 1 hour or so to commit all rows after this extension had finished its execution.
Consider 2!!!
A bit of mixture between URI and path. Old and New base path are in String path. Rest in URI.
*/
namespace FSpot.Tools.ChangePhotoPath
{
public enum ProcessResult {
Ok, Cancelled, Error, SamePath, NoPhotosFound, Processing
}
public class ChangePathController
{
PhotoStore photo_store = FSpot.App.Instance.Database.Photos;
List<uint> photo_id_array;
List<uint> version_id_array;
StringCollection old_path_array, new_path_array;
int total_photos;
string orig_base_path;
private const string BASE2000 = "/20";
private const string BASE1900 = "/19";
private const string BASE1800 = "/18";
private IChangePhotoPathGui gui_controller;
private bool user_cancelled;
public bool UserCancelled {
get {return user_cancelled;}
set {user_cancelled = value;}
}
public ChangePathController (IChangePhotoPathGui gui)
{
gui_controller = gui;
total_photos = photo_store.TotalPhotos;
orig_base_path = EnsureEndsWithOneDirectorySeparator (FindOrigBasePath()); // NOT URI
string new_base_path = EnsureEndsWithOneDirectorySeparator (FSpot.Settings.Global.PhotoUri.LocalPath); // NOT URI
gui_controller.DisplayDefaultPaths (orig_base_path, new_base_path);
user_cancelled = false;
}
private string EnsureEndsWithOneDirectorySeparator (string tmp_str)
{
if ( (tmp_str == null) || (tmp_str.Length == 0) )
return string.Format ("{0}", Path.DirectorySeparatorChar);
while (tmp_str.EndsWith(string.Format ("{0}", Path.DirectorySeparatorChar)))
tmp_str = tmp_str.Remove (tmp_str.Length-1, 1);
return string.Format ("{0}{1}", tmp_str, Path.DirectorySeparatorChar);
}
// Should always return TRUE, since path always ends with "/"
public bool CanWeRun ()
{
return (orig_base_path != null);
}
private string IsThisPhotoOnOrigBasePath (string check_this_path)
{
int i;
i = check_this_path.IndexOf(BASE2000);
if (i > 0)
return (check_this_path.Substring(0, i));
i = check_this_path.IndexOf(BASE1900);
if (i > 0)
return (check_this_path.Substring(0, i));
i = check_this_path.IndexOf(BASE1800);
if (i > 0)
return (check_this_path.Substring(0, i));
return null;
}
private string FindOrigBasePath()
{
string res_path = null;
foreach ( IPhoto photo in photo_store.Query ( "SELECT * FROM photos " ) ) {
string tmp_path = (photo as Photo).DefaultVersion.Uri.AbsolutePath;
res_path = IsThisPhotoOnOrigBasePath (tmp_path);
if (res_path != null)
break;
}
return res_path;
}
private void InitializeArrays()
{
photo_id_array = new List<uint> ();
version_id_array = new List<uint> ();
old_path_array = new StringCollection();
new_path_array = new StringCollection();
}
private void AddVersionToArrays ( uint photo_id, uint version_id, string old_path, string new_path)
{
photo_id_array.Add (photo_id);
version_id_array.Add (version_id);
old_path_array.Add (old_path);
new_path_array.Add (new_path);
}
private string CreateNewPath (string old_base, string new_base, PhotoVersion version)
{
return string.Format ("{0}{1}", new_base, version.Uri.AbsolutePath.Substring(old_base.Length));
}
private bool ChangeThisVersionUri (PhotoVersion version, string old_base, string new_base)
{
// Change to path from URI, since easier to compare with old_base which is not in URI format.
string tmp_path = System.IO.Path.GetDirectoryName (version.Uri.AbsolutePath);
return ( tmp_path.StartsWith (old_base) );
}
private void SearchVersionUriToChange (Photo photo, string old_base, string new_base)
{
foreach (uint version_id in photo.VersionIds) {
PhotoVersion version = photo.GetVersion (version_id) as PhotoVersion;
if ( ChangeThisVersionUri (version, old_base, new_base) )
AddVersionToArrays ( photo.Id,
version_id,
version.Uri.AbsolutePath,
CreateNewPath (old_base, new_base, version));
// else
// System.Console.WriteLine ("L : {0}", version.Uri.AbsolutePath);
}
}
public bool SearchUrisToChange (string old_base, string new_base)
{
int count = 0;
foreach ( IPhoto ibrows in photo_store.Query ( "SELECT * FROM photos " ) ) {
count++;
if (gui_controller.UpdateProgressBar ("Scanning through database", "Checking photo", total_photos))
return false;
SearchVersionUriToChange ((ibrows as Photo), old_base, new_base);
}
return true;
}
public bool StillOnSamePhotoId (int old_index, int current_index, List<uint> array)
{
try {
return (array[old_index] == array[current_index]);
} catch {
return true; // return true if out of index.
}
}
public void UpdateThisUri (int index, string path, ref Photo photo)
{
if (photo == null)
photo = photo_store.Get (photo_id_array[index]);
PhotoVersion version = photo.GetVersion ( (uint) version_id_array[index]) as PhotoVersion;
version.BaseUri = new SafeUri ( path ).GetBaseUri ();
version.Filename = new SafeUri ( path ).GetFilename ();
photo.Changes.UriChanged = true;
photo.Changes.ChangeVersion ( (uint) version_id_array[index] );
}
// FIXME: Refactor, try to use one common method....
public void RevertAllUris (int last_index)
{
gui_controller.remove_progress_dialog();
Photo photo = null;
for (int k = last_index; k >= 0; k--) {
if (gui_controller.UpdateProgressBar ("Reverting changes to database", "Reverting photo", last_index))
{} // do nothing, ignore trying to abort the revert...
if ( (photo != null) && !StillOnSamePhotoId (k+1, k, photo_id_array) ) {
photo_store.Commit (photo);
photo = null;
}
UpdateThisUri (k, old_path_array[k], ref photo);
Log.DebugFormat ("R : {0} - {1}", k, old_path_array[k]);
}
if (photo != null)
photo_store.Commit (photo);
Log.Debug ("Changing path failed due to above error. Have reverted any modification that took place.");
}
public ProcessResult ChangeAllUris ( ref int last_index)
{
gui_controller.remove_progress_dialog();
Photo photo = null;
last_index = 0;
try {
photo = null;
for (last_index = 0; last_index < photo_id_array.Count; last_index++) {
if (gui_controller.UpdateProgressBar ("Changing photos base path", "Changing photo", photo_id_array.Count)) {
Log.Debug("User aborted the change of paths...");
return ProcessResult.Cancelled;
}
if ( (photo != null) && !StillOnSamePhotoId (last_index-1, last_index, photo_id_array) ) {
photo_store.Commit (photo);
photo = null;
}
UpdateThisUri (last_index, new_path_array[last_index], ref photo);
Log.DebugFormat ("U : {0} - {1}", last_index, new_path_array[last_index]);
// DEBUG ONLY
// Cause an TEST exception on 6'th URI to be changed.
// float apa = last_index / (last_index-6);
}
if (photo != null)
photo_store.Commit (photo);
} catch (Exception e) {
Log.Exception(e);
return ProcessResult.Error;
}
return ProcessResult.Ok;
}
public ProcessResult ProcessArrays()
{
int last_index = 0;
ProcessResult tmp_res;
tmp_res = ChangeAllUris(ref last_index);
if (!(tmp_res == ProcessResult.Ok))
RevertAllUris(last_index);
return tmp_res;
}
/*
public void CheckIfUpdated (int test_index, StringCollection path_array)
{
Photo photo = photo_store.Get ( (uint) photo_id_array[test_index]) as Photo;
PhotoVersion version = photo.GetVersion ( (uint) version_id_array[test_index]) as PhotoVersion;
if (version.Uri.AbsolutePath.ToString() == path_array[ test_index ])
Log.DebugFormat ("Test URI ({0}) matches --- Should be finished", test_index);
else
Log.DebugFormat ("Test URI ({0}) DO NOT match --- Should NOT BE finished", test_index);
}
*/
/*
Check paths are different
If (Scan all photos) // user might cancel
If (Check there are photos on old path)
ChangePathsOnPhotos
*/
public bool NewOldPathSame (ref string newpath, ref string oldpath)
{
string p1 = EnsureEndsWithOneDirectorySeparator(newpath);
string p2 = EnsureEndsWithOneDirectorySeparator(oldpath);
return (p1 == p2);
}
public ProcessResult ChangePathOnPhotos (string old_base, string new_base)
{
ProcessResult tmp_res = ProcessResult.Processing;
InitializeArrays();
if (NewOldPathSame (ref new_base, ref old_base))
tmp_res = ProcessResult.SamePath;
if ( (tmp_res == ProcessResult.Processing) && (!SearchUrisToChange (old_base, new_base)) )
tmp_res = ProcessResult.Cancelled;
if ( (tmp_res == ProcessResult.Processing) && (photo_id_array.Count == 0) )
tmp_res = ProcessResult.NoPhotosFound;
if (tmp_res == ProcessResult.Processing)
tmp_res = ProcessArrays();
// if (res)
// CheckIfUpdated (photo_id_array.Count-1, new_path_array);
// else
// CheckIfUpdated (0, old_path_array);
return tmp_res;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="C06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C07_RegionObjects"/> of type <see cref="C07_RegionColl"/> (1:M relation to <see cref="C08_Region"/>)<br/>
/// This class is an item of <see cref="C05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class C06_Country : BusinessBase<C06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
private byte[] _rowVersion = new byte[] {};
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ParentSubContinentID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "ParentSubContinentID");
/// <summary>
/// Gets or sets the ParentSubContinentID.
/// </summary>
/// <value>The ParentSubContinentID.</value>
public int ParentSubContinentID
{
get { return GetProperty(ParentSubContinentIDProperty); }
set { SetProperty(ParentSubContinentIDProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C07_Country_Child> C07_Country_SingleObjectProperty = RegisterProperty<C07_Country_Child>(p => p.C07_Country_SingleObject, "C07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C07 Country Single Object ("self load" child property).
/// </summary>
/// <value>The C07 Country Single Object.</value>
public C07_Country_Child C07_Country_SingleObject
{
get { return GetProperty(C07_Country_SingleObjectProperty); }
private set { LoadProperty(C07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C07_Country_ReChild> C07_Country_ASingleObjectProperty = RegisterProperty<C07_Country_ReChild>(p => p.C07_Country_ASingleObject, "C07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C07 Country ASingle Object ("self load" child property).
/// </summary>
/// <value>The C07 Country ASingle Object.</value>
public C07_Country_ReChild C07_Country_ASingleObject
{
get { return GetProperty(C07_Country_ASingleObjectProperty); }
private set { LoadProperty(C07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<C07_RegionColl> C07_RegionObjectsProperty = RegisterProperty<C07_RegionColl>(p => p.C07_RegionObjects, "C07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C07 Region Objects ("self load" child property).
/// </summary>
/// <value>The C07 Region Objects.</value>
public C07_RegionColl C07_RegionObjects
{
get { return GetProperty(C07_RegionObjectsProperty); }
private set { LoadProperty(C07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C06_Country"/> object.</returns>
internal static C06_Country NewC06_Country()
{
return DataPortal.CreateChild<C06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="C06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="C06_Country"/> object.</returns>
internal static C06_Country GetC06_Country(SafeDataReader dr)
{
C06_Country obj = new C06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C06_Country()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C07_Country_SingleObjectProperty, DataPortal.CreateChild<C07_Country_Child>());
LoadProperty(C07_Country_ASingleObjectProperty, DataPortal.CreateChild<C07_Country_ReChild>());
LoadProperty(C07_RegionObjectsProperty, DataPortal.CreateChild<C07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID"));
LoadProperty(Country_NameProperty, dr.GetString("Country_Name"));
LoadProperty(ParentSubContinentIDProperty, dr.GetInt32("Parent_SubContinent_ID"));
_rowVersion = dr.GetValue("RowVersion") as byte[];
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(C07_Country_SingleObjectProperty, C07_Country_Child.GetC07_Country_Child(Country_ID));
LoadProperty(C07_Country_ASingleObjectProperty, C07_Country_ReChild.GetC07_Country_ReChild(Country_ID));
LoadProperty(C07_RegionObjectsProperty, C07_RegionColl.GetC07_RegionColl(Country_ID));
}
/// <summary>
/// Inserts a new <see cref="C06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddC06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateC06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", ReadProperty(ParentSubContinentIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", _rowVersion).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
_rowVersion = (byte[]) cmd.Parameters["@NewRowVersion"].Value;
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteC06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(C07_Country_SingleObjectProperty, DataPortal.CreateChild<C07_Country_Child>());
LoadProperty(C07_Country_ASingleObjectProperty, DataPortal.CreateChild<C07_Country_ReChild>());
LoadProperty(C07_RegionObjectsProperty, DataPortal.CreateChild<C07_RegionColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.AzureStack.Management.InfrastructureInsights.Admin
{
using Microsoft.AzureStack;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.InfrastructureInsights;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ResourceHealthsOperations operations.
/// </summary>
internal partial class ResourceHealthsOperations : IServiceOperations<InfrastructureInsightsAdminClient>, IResourceHealthsOperations
{
/// <summary>
/// Initializes a new instance of the ResourceHealthsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ResourceHealthsOperations(InfrastructureInsightsAdminClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the InfrastructureInsightsAdminClient
/// </summary>
public InfrastructureInsightsAdminClient Client { get; private set; }
/// <summary>
/// Get a list of resources?.
/// </summary>
/// <param name='location'>
/// Location name.
/// </param>
/// <param name='serviceRegistrationId'>
/// Service registration id.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ResourceHealth>>> ListWithHttpMessagesAsync(string location, string serviceRegistrationId, ODataQuery<ResourceHealth> odataQuery = default(ODataQuery<ResourceHealth>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (serviceRegistrationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceRegistrationId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("location", location);
tracingParameters.Add("serviceRegistrationId", serviceRegistrationId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.InfrastructureInsights.Admin/regionHealths/{location}/serviceHealths/{serviceRegistrationId}/resourceHealths").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{serviceRegistrationId}", System.Uri.EscapeDataString(serviceRegistrationId));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ResourceHealth>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceHealth>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get health information about a resources.
/// </summary>
/// <param name='location'>
/// Location name.
/// </param>
/// <param name='serviceRegistrationId'>
/// Service registration id.
/// </param>
/// <param name='resourceRegistrationId'>
/// Resource registration id.
/// </param>
/// <param name='filter'>
/// OData filter parameter.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ResourceHealth>> GetWithHttpMessagesAsync(string location, string serviceRegistrationId, string resourceRegistrationId, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (serviceRegistrationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceRegistrationId");
}
if (resourceRegistrationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceRegistrationId");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("serviceRegistrationId", serviceRegistrationId);
tracingParameters.Add("resourceRegistrationId", resourceRegistrationId);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.InfrastructureInsights.Admin/regionHealths/{location}/serviceHealths/{serviceRegistrationId}/resourceHealths/{resourceRegistrationId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{serviceRegistrationId}", System.Uri.EscapeDataString(serviceRegistrationId));
_url = _url.Replace("{resourceRegistrationId}", System.Uri.EscapeDataString(resourceRegistrationId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ResourceHealth>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceHealth>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a list of resources?.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ResourceHealth>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ResourceHealth>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ResourceHealth>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
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 OpenConnectionTimeout attribute specifies the timeout before a connection open is assumed to have failed
/// </summary>
TimeSpan OpenConnectionTimeout { get; set; }
/// <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 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>
/// The list of serialization providers
/// </summary>
List<TypeInfo> SerializationProviders { get; }
/// <summary>
/// Gets the fallback serializer, used as a last resort when no other serializer is able to serialize an object.
/// </summary>
TypeInfo FallbackSerializationProvider { get; set; }
}
/// <summary>
/// Messaging configuration that are common to client and silo.
/// </summary>
[Serializable]
public class MessagingConfiguration : IMessagingConfiguration
{
public TimeSpan OpenConnectionTimeout { get; set; }
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 int BufferPoolBufferSize { get; set; }
public int BufferPoolMaxSize { get; set; }
public int BufferPoolPreallocationSize { 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; }
public TypeInfo FallbackSerializationProvider { get; 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 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 readonly bool isSiloConfig;
internal MessagingConfiguration(bool isSilo)
{
isSiloConfig = isSilo;
OpenConnectionTimeout = Constants.DEFAULT_OPENCONNECTION_TIMEOUT;
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;
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;
}
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(" 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();
if (isSiloConfig)
{
sb.AppendFormat(" Maximum forward count: {0}", MaxForwardCount).AppendLine();
}
SerializationProviders.ForEach(sp =>
sb.AppendFormat(" Serialization provider: {0}", sp.FullName).AppendLine());
sb.AppendFormat(" Fallback serializer: {0}", this.FallbackSerializationProvider?.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("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 (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.OfType<XmlElement>().FirstOrDefault(n => n.Name == "SerializationProviders");
if (serializerNode != null && serializerNode.HasChildNodes)
{
var typeNames = serializerNode.ChildNodes.OfType<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. Type specification: '{t}'."));
foreach (var type in types)
{
var typeinfo = type.GetTypeInfo();
ConfigUtilities.ValidateSerializationProvider(typeinfo);
if (SerializationProviders.Contains(typeinfo) == false)
{
SerializationProviders.Add(typeinfo);
}
}
}
var fallbackSerializerNode = child.ChildNodes.OfType<XmlElement>().FirstOrDefault(n => n.Name == "FallbackSerializationProvider");
if (fallbackSerializerNode != null)
{
var typeName = fallbackSerializerNode.Attributes["type"]?.Value;
if (string.IsNullOrWhiteSpace(typeName))
{
var msg = "The FallbackSerializationProvider element requires a 'type' attribute specifying the fully-qualified type name of the serializer.";
throw new FormatException(msg);
}
var type = ConfigUtilities.ParseFullyQualifiedType(
typeName,
$"The type specification for the 'type' attribute of the FallbackSerializationProvider element could not be loaded. Type specification: '{typeName}'.");
this.FallbackSerializationProvider = type.GetTypeInfo();
}
}
}
}
}
| |
/*This code is managed under the Apache v2 license.
To see an overview:
http://www.tldrlegal.com/license/apache-license-2.0-(apache-2.0)
Author: Robert Gawdzik
www.github.com/rgawdzik/
THIS CODE HAS NO FORM OF ANY WARRANTY, AND IS CONSIDERED AS-IS.
*/
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 System.Threading;
using Paradox.Game.Classes;
using Paradox.Game.Classes.Ships;
using Paradox.Game.Classes.Levels;
using Paradox.Game.Classes.Engines;
using Paradox.Game.Classes.HUD;
using Paradox.Game.Classes.Inputs;
using Paradox.Menu.GameScreens;
namespace Paradox.Game
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class ParadoxGame : Microsoft.Xna.Framework.DrawableGameComponent
{
private Save _save;
public static event EventHandler FinishedLoading;
public static event EventHandler Pause;
private bool _gameActive;
public bool LoadingScreenActive { protected get; set; } //Represents the state of the loading video. The game should not draw, but can update, when the video still plays.
private SpriteBatch _spriteBatch;
private GraphicsDevice _device;
Skybox SkyboxTEST;
GameEngine GameEngineTEST;
HUDManager HUDManager;
public ParadoxGame(Paradox game, Save save)
: base(game)
{
_save = save;
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
PlayerShip.Pause += (object sender, EventArgs args) =>
{
_gameActive = false;
GameEngineTEST.RetrieveSoundEngine().StopMusic();
PauseEvent();
};
PauseMenu.Resume += (object sender, EventArgs args) =>
{
_gameActive = true;
};
EndGameMenu.Selected += (o, e) =>
{
LoadingScreenActive = true; //We still want the game to be updated, but not drawn.
GameEngineTEST.RetrieveSoundEngine().StopMusic();
};
base.Initialize();
}
protected override void LoadContent()
{
_gameActive = false;
Thread thread = new Thread(LoadingThread);
thread.Start();
// TODO: use this.Game.Content to load your game content here
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
if (_gameActive)
{
GameEngineTEST.Update(gameTime);
HUDManager.Update(gameTime, GameEngineTEST.RetrievePlayerShip(), GameEngineTEST.RetrieveEnemyList(), GameEngineTEST.RetrieveFriendList(),
GameEngineTEST.Level.PlayerStarBase, GameEngineTEST.Level.EnemyStarBase, GameEngineTEST.AmountEnemies, GameEngineTEST.AmountFriends, GameEngineTEST.Level, GameEngineTEST.Level.TimeRemaining);
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
if (_gameActive && !LoadingScreenActive)
{
//The Skybox should be relative to the camera.
SkyboxTEST.DrawSkybox(GameEngineTEST.RetrievePlayerShip().Camera, GameEngineTEST.RetrievePlayerShip().Camera.CameraPosition);
GameEngineTEST.Draw(GameEngineTEST.RetrievePlayerShip().Camera);
GameEngineTEST.RetrievePlayerShip().DrawShip();
HUDManager.Draw(GameEngineTEST.RetrievePlayerShip().Camera, GameEngineTEST.RetrieveFriendList(), GameEngineTEST.RetrieveEnemyList(), GameEngineTEST.Level.ObjectiveList);
}
}
public void LoadingThread()
{
GameEngine.CollidableList.Clear();
_save.Config.Win = false;
_save.Config.End = false;
_device = GraphicsDevice;
// Create a new SpriteBatch, which can be used to draw textures.
_spriteBatch = new SpriteBatch(GraphicsDevice);
Texture2D[] Skywalls = { Game.Content.Load<Texture2D>(@"Game/Levels/Skybox/SkyBox_Back"), Game.Content.Load<Texture2D>(@"Game/Levels/Skybox/SkyBox_Bottom"), Game.Content.Load<Texture2D>(@"Game/Levels/Skybox/SkyBox_Front"),
Game.Content.Load<Texture2D>(@"Game/Levels/Skybox/SkyBox_Left"), Game.Content.Load<Texture2D>(@"Game/Levels/Skybox/SkyBox_Right"), Game.Content.Load<Texture2D>(@"Game/Levels/Skybox/SkyBox_Top") };
SkyboxTEST = new Skybox(_device, Skywalls, Game.Content.Load<Model>(@"Game/Levels/Skybox/Skybox"));
Texture2D[] ExplosionArray = {
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen0"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen1"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen2"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen3"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen4"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen5"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen6"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen7"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen8"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen9"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen10"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen11"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen12"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet1/screen13")
};
Texture2D[] ExplosionArray2 = {
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen1"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen2"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen3"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen4"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen5"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen6"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen7"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen8"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen9"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen10"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen11"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen12"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen13"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen14"),
Game.Content.Load<Texture2D>(@"Game/Images/Explosions/ExplosionSet2/screen15")
};
#region Spawn Manager
List<ShipProfile> shipProfiles = new List<ShipProfile>();
shipProfiles.Add(new ShipProfile(6, 5, 2, 2));
shipProfiles.Add(new ShipProfile(4, 5, 3, 3));
shipProfiles.Add(new ShipProfile(2, 4, 6, 6));
SpriteFont spawnerFont = Game.Content.Load<SpriteFont>(@"Game/Fonts/SpawnerFont");
Texture2D[] arrows = { Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ArrowLeft"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ArrowLeftShaded"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ArrowRight"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ArrowRightShaded")
};
Texture2D[] bars = {
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/GreenBar"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/RedBar")
};
Texture2D overlay = Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/Overlay");
Texture2D[] shipImages = {
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ShipImage"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ShipImage"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Spawner/ShipImage")
};
SpawnerManager spawnerManager = new SpawnerManager(_device, shipProfiles, spawnerFont, arrows, bars, overlay, shipImages, 3);
#endregion
WeaponSystem2D weaponSystem2D = new WeaponSystem2D(GameEngine.CollidableList, CollidableType.PlayerBullet, 1f, SoundType.Player_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
0.25f, _device, 10, new Vector3(0, 0, 0), 150, 300, 0.001f);
WeaponSystem2D weaponSystem2D2 = new WeaponSystem2D(GameEngine.CollidableList, CollidableType.PlayerBullet, 1f, SoundType.Player_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
0.25f, _device, 10, new Vector3(0, 0, 0), 100, 300, 0.001f);
WeaponSystem2D weaponSystem2D3 = new WeaponSystem2D(GameEngine.CollidableList, CollidableType.PlayerBullet, 1f, SoundType.Player_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
0.25f, _device, 10, new Vector3(0, 0, 0), 75, 300, 0.001f);
MissleSystem2D missleSystem2D = new MissleSystem2D(GameEngine.CollidableList, CollidableType.FriendMissle, 1f, SoundType.PlayerMissle, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"), 1f,
_device, 10, new Vector3(0, 0, 0), 1400, 100, 0.0001f, 14, 600);
Model playerModel1 = Game.Content.Load<Model>("Game/Models/Viper/bomber");
float playermodelscale1 = 0.07f;
//Player Configurations
PlayerConfig[] playerConfigurations = new PlayerConfig[3];
playerConfigurations[0] = new PlayerConfig(new BasicModel(playerModel1, playermodelscale1), 13, new Vector3(0, 0.5f, -7), weaponSystem2D, missleSystem2D, 15, 25, -25, 2, 1.5f, 1.5f, 1f);
playerConfigurations[1] = new PlayerConfig(new BasicModel(Game.Content.Load<Model>(@"Game/Models/Viper/inceptor"), playermodelscale1), 10, new Vector3(0, 0.5f, -7), weaponSystem2D2, missleSystem2D, 5, 30, -30, 2, 2f, 2f, 1f);
playerConfigurations[2] = new PlayerConfig(new BasicModel(Game.Content.Load<Model>(@"Game/Models/Viper/ghoul"), playermodelscale1), 5, new Vector3(0, 0.5f, -7), weaponSystem2D3, missleSystem2D, 2, 40, -40, 2f, 2.5f, 2.5f, 1f);
PlayerShip playerShipTEST = new PlayerShip(GameEngine.CollidableList, CollidableType.FriendlyShip, playerModel1.Meshes.ToList()[0].BoundingSphere.Radius * playermodelscale1, playerModel1, new Vector3(800, 40, -200),
_device, new Vector3(0, 0.5f, -7), playermodelscale1, -30, 30, 2, 2, 1.5f, 1f, weaponSystem2D, missleSystem2D, spawnerManager, playerConfigurations);
Planet planet;
//Setting up the planet for the mission.
switch (_save.Config.Mission)
{
case 0:
planet = new Planet(Game.Content.Load<Model>("Game/Models/Planets/Planet2/earth"), new Vector3(2800, 0, 0), Quaternion.Identity, 0.01f, 15f);
break;
case 1:
planet = new Planet(Game.Content.Load<Model>("Game/Models/Planets/Planet1/dradis"), new Vector3(-300, -2800, 1300), Quaternion.Identity, 0.01f, 120f);
break;
case 2:
planet = new Planet(Game.Content.Load<Model>("Game/Models/Planets/Planet3/mars"), new Vector3(300, 2800, 1300), Quaternion.CreateFromAxisAngle(new Vector3(0,0,1), 2f), 0.01f, 60f);
break;
default:
planet = new Planet(Game.Content.Load<Model>("Game/Models/Planets/Planet2/earth"), new Vector3(2800, 0, 0), Quaternion.Identity, 0.01f, 50f);
break;
}
Starbase playerstarbase;
Model playerBaseModel;
float playerBaseScale;
//Setting up the playerbase for the mission.
switch (_save.Config.Mission)
{
case 0:
playerBaseModel = Game.Content.Load<Model>("Game/Models/Starbase/PlayerBase/Station/Battlestation");
playerBaseScale = 25f;
playerstarbase = new Starbase(CollidableType.FriendBase, playerBaseModel.Meshes.ToList()[0].BoundingSphere.Radius * playerBaseScale, playerBaseModel, new Vector3(0, -300, -1000), Quaternion.Identity, playerBaseScale);
break;
case 1:
playerBaseModel = Game.Content.Load<Model>("Game/Models/Starbase/PlayerBase/Station/Battlestation2");
playerBaseScale = 50f;
playerstarbase = new Starbase(CollidableType.FriendBase, playerBaseModel.Meshes.ToList()[0].BoundingSphere.Radius * playerBaseScale, playerBaseModel, new Vector3(0, -300, -1000), Quaternion.Identity, playerBaseScale);
break;
case 2:
playerBaseModel = Game.Content.Load<Model>("Game/Models/Starbase/PlayerBase/Station/Battlestation2");
playerBaseScale = 50f;
playerstarbase = new Starbase(CollidableType.FriendBase, playerBaseModel.Meshes.ToList()[0].BoundingSphere.Radius * playerBaseScale, playerBaseModel, new Vector3(0, -300, -1000), Quaternion.Identity, playerBaseScale);
break;
default:
playerBaseModel = Game.Content.Load<Model>("Game/Models/Starbase/PlayerBase/Station/Battlestation");
playerBaseScale = 25f;
playerstarbase = new Starbase(CollidableType.FriendBase, playerBaseModel.Meshes.ToList()[0].BoundingSphere.Radius * playerBaseScale, playerBaseModel, new Vector3(0, -300, -1000), Quaternion.Identity, playerBaseScale);
break;
}
Model enemyBaseModel = Game.Content.Load<Model>("Game/Models/Starbase/EnemyBase/Station/sleeper7");
float enemyBaseScale = 40f;
Starbase enemyStarBase = new Starbase(CollidableType.EnemyBase, enemyBaseModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyBaseScale, enemyBaseModel, new Vector3(950, 950, 950), Quaternion.CreateFromAxisAngle(Vector3.Up, 90f), enemyBaseScale);
Model asteroid1 = Game.Content.Load<Model>(@"Game/Models/Asteroids/smallAsteroid");
float asteroid1Scale = 1f;
Model asteroid3 = Game.Content.Load<Model>(@"Game/Models/Asteroids/largeAsteroid");
float asteroid3Scale = 5f;
BasicModel[] basicAsteroidModel = { new BasicModel(asteroid1, asteroid1Scale),
new BasicModel(asteroid3, asteroid3Scale) };
float[] radiusArray = { asteroid1.Meshes.ToList()[0].BoundingSphere.Radius * asteroid1Scale, asteroid3.Meshes.ToList()[0].BoundingSphere.Radius * asteroid3Scale };
Model dockModel = Game.Content.Load<Model>(@"Game/Models/Dock/Dock");
float dockScale = 0.15f;
Dock dock = new Dock(CollidableType.Dock, dockModel.Meshes.ToList()[0].BoundingSphere.Radius * dockScale, new BasicModel(dockModel, dockScale), new Vector3(800, 40, -200), Quaternion.Identity);
#region Objective Stuff
List<Objective> objectiveList = new List<Objective>();
Model Bstation = Game.Content.Load<Model>(@"Game/Models/Station/BStation");
float BstationScale = 1f;
switch (_save.Config.Mission)
{
case 0:
objectiveList.Add(new ObjectiveDestroyable(CollidableType.Station, Bstation.Meshes.ToList()[0].BoundingSphere.Radius * BstationScale, 0.05f, new BasicModel(Bstation, BstationScale),
new Vector3(600, 600, 600), Quaternion.Identity, "Protect the Relay Station for 3:00 Minutes", 800, new TimeSpan(0, 3, 0)));
objectiveList.Add(new ObjectiveEnemy("Eliminate 10 Enemies: ", 10));
objectiveList.Add(new ObjectiveEnemyFrigate("Eliminate 1 Frigate: ", 1));
break;
case 1:
objectiveList.Add(new ObjectiveDestroyable(CollidableType.Station, Bstation.Meshes.ToList()[0].BoundingSphere.Radius * BstationScale, 0.05f, new BasicModel(Bstation, BstationScale),
new Vector3(600, 600, 600), Quaternion.Identity, "Protect the Relay Station for 5:00 Minutes", 800, new TimeSpan(0, 5, 0)));
objectiveList.Add(new ObjectiveDestroyable(CollidableType.Station, Bstation.Meshes.ToList()[0].BoundingSphere.Radius * BstationScale, 0.05f, new BasicModel(Bstation, BstationScale),
new Vector3(800, 200, 500), Quaternion.CreateFromAxisAngle(new Vector3(0,0,1), 2f), "Protect the Secondary Station for 2:00 Minutes", 300, new TimeSpan(0, 2, 0)));
objectiveList.Add(new ObjectiveEnemy("Eliminate 20 Enemies: ", 20));
objectiveList.Add(new ObjectiveEnemyFrigate("Eliminate 2 Frigates: ", 2));
break;
case 2:
objectiveList.Add(new ObjectiveDestroyable(CollidableType.Station, Bstation.Meshes.ToList()[0].BoundingSphere.Radius * BstationScale, 0.05f, new BasicModel(Bstation, BstationScale),
new Vector3(600, 600, 600), Quaternion.Identity, "Protect the Relay Station for 6:00 Minutes", 800, new TimeSpan(0, 5, 0)));
objectiveList.Add(new ObjectiveDestroyable(CollidableType.Station, Bstation.Meshes.ToList()[0].BoundingSphere.Radius * BstationScale, 0.05f, new BasicModel(Bstation, BstationScale),
new Vector3(800, 200, 500), Quaternion.CreateFromAxisAngle(new Vector3(0,0,1), 2f), "Protect the Secondary Station for 4:00 Minutes", 400, new TimeSpan(0, 2, 0)));
objectiveList.Add(new ObjectiveEnemy("Eliminate 30 Enemies: ", 30));
objectiveList.Add(new ObjectiveEnemyFrigate("Eliminate 3 Frigates: ", 3));
break;
default:
objectiveList.Add(new ObjectiveDestroyable(CollidableType.Station, Bstation.Meshes.ToList()[0].BoundingSphere.Radius * BstationScale, 0.05f, new BasicModel(Bstation, BstationScale),
new Vector3(600, 600, 600), Quaternion.Identity, "Protect the Relay Station for 3:00 Minutes", 800, new TimeSpan(0, 3, 0)));
objectiveList.Add(new ObjectiveEnemy("Eliminate 10 Enemies: ", 10));
objectiveList.Add(new ObjectiveEnemyFrigate("Eliminate 1 Frigate: ", 1));
break;
}
#endregion
Sun sun;
switch (_save.Config.Mission)
{
case 0:
sun = new Sun(_device, Game.Content.Load<Texture2D>(@"Game/Images/Other/sun"), new Vector3(-300, 1300, 1300), 1000);
break;
case 1:
sun = new Sun(_device, Game.Content.Load<Texture2D>(@"Game/Images/Other/sun"), new Vector3(-300, -1300, -1300), 1000);
break;
case 2:
sun = new Sun(_device, Game.Content.Load<Texture2D>(@"Game/Images/Other/sun"), new Vector3(300, -1300, 1300), 1000);
break;
default:
sun = new Sun(_device, Game.Content.Load<Texture2D>(@"Game/Images/Other/sun"), new Vector3(-300, 1300, 1300), 1000);
break;
}
Level level = new Level(GameEngine.CollidableList, radiusArray, basicAsteroidModel, planet, playerstarbase, enemyStarBase, SkyboxTEST, dock, sun, playerShipTEST, 40, objectiveList, _device,
new TimeSpan(0, 10, 0), new Vector3(0, 0, 0), new Vector3(1000, 1000, 1000), _save);
#region Enemy Stuff
Model enemyModel = Game.Content.Load<Model>("Game/Models/Raider/fighter1");
float enemyScale = 1f;
List<Enemy> enemyList = new List<Enemy>();
enemyList.Add(new Enemy(CollidableType.EnemyShip, enemyModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyScale, new Vector3(900, 900, 900), Quaternion.CreateFromAxisAngle(Vector3.UnitX, 10), -30, 30, 30, 50, 10, 3));
WeaponSystem2D enemyWeaponSystem = new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 1f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bulletBlue"), 0.25f, _device, 125, new Vector3(0, 0, 0), 300, 300, 0.001f);
List<EnemyFrigate> enemyFrigateList = new List<EnemyFrigate>();
Model enemyFrigateModel = Game.Content.Load<Model>("Game/Models/Frigate/PirateShip");
float enemyFrigateScale = 3f;
List<WeaponSystem2D> frigateweaponSystemList = new List<WeaponSystem2D>();
switch (_save.Config.Mission)
{
case 0:
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 2.5f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(0, 0.2f, 0), 300, 300, 0.001f));
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 3f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(5f, 0.2f, 0), 300, 300, 0.001f));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1000, 1000, 1000), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
break;
case 1:
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 2.5f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(0, 0.2f, 0), 300, 300, 0.001f));
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 3f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(5f, 0.2f, 0), 300, 300, 0.001f));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1000, 1000, 1000), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1400, 1400, 1400), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
break;
case 2:
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 2.5f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(0, 0.2f, 0), 300, 300, 0.001f));
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 3f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(5f, 0.2f, 0), 300, 300, 0.001f));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1000, 1000, 1000), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1400, 1400, 1400), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1400, 900, 1400), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
break;
default:
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 2.5f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(0, 0.2f, 0), 300, 300, 0.001f));
frigateweaponSystemList.Add(new WeaponSystem2D(GameEngine.CollidableList, CollidableType.EnemyBullet, 3f, SoundType.Enemy_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bullet"),
2.5f, _device, 100, new Vector3(5f, 0.2f, 0), 300, 300, 0.001f));
enemyFrigateList.Add(new EnemyFrigate(new BasicModel(enemyFrigateModel, enemyFrigateScale), CollidableType.EnemyShip, enemyFrigateModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyFrigateScale,
new Vector3(1000, 1000, 1000), Quaternion.Identity, -10, 10, 0.1f, 20, 10, 300, frigateweaponSystemList));
break;
}
EnemySquadron enemySquadron = new EnemySquadron(GameEngine.CollidableList, CollidableType.EnemyShip, enemyModel.Meshes.ToList()[0].BoundingSphere.Radius * enemyScale, new BasicModel(enemyModel, enemyScale), enemyList, enemyFrigateList, enemyWeaponSystem, new Vector3(950, 950, 950), 10, 40, 300);
#endregion
#region Friend Stuff
Model friendModel = Game.Content.Load<Model>("Game/Models/Viper/inceptor");
float friendScale = 0.07f;
List<Friend> friendList = new List<Friend>();
friendList.Add(new Friend(CollidableType.FriendlyShip, friendModel.Meshes.ToList()[0].BoundingSphere.Radius * friendScale, new Vector3(-300, -300, -1000), Quaternion.Identity, -30, 30, 30, 2, 10, 50, 3));
//new ParticleEngine(pEngine._device, pEngine._displacement, pEngine._textureArray, pEngine.size, pEngine.size, _particleEngine._delayReset)
WeaponSystem2D friendWeaponSystem = new WeaponSystem2D(GameEngine.CollidableList, CollidableType.FriendBullet, 1f, SoundType.Friend_Shoot, Game.Content.Load<Texture2D>(@"Game/Images/Weapons/bulletRed"), 0.25f, _device, 125, new Vector3(0, 0, 0), 300, 300, 0.001f);
FriendSquadron friendSquadron = new FriendSquadron(GameEngine.CollidableList, CollidableType.FriendlyShip, friendModel.Meshes.ToList()[0].BoundingSphere.Radius * friendScale, new BasicModel(friendModel, friendScale), friendList, friendWeaponSystem, new Vector3(0, -300, -1000), 15, 20, 100);
#endregion
ExplosionEngine explosionEngine = new ExplosionEngine(_device, ExplosionArray, 20, 5);
SoundEffect[] soundEffectArray = { Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Player_Engine"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Player_Hit"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Player_Shoot"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Friend_Shoot"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Enemy_Shoot"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Explosion"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Effects/Player_Missle")
};
SoundEffect[] voiceChatterSounds = new SoundEffect[30];
for (int i = 0; i < 30; i++)
voiceChatterSounds[i] = Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Chatter/" + (i + 1));
SoundEffect[] musicSounds = new SoundEffect[6];
for (int i = 0; i < 6; i++)
musicSounds[i] = Game.Content.Load<SoundEffect>(@"Game/Audio/Music/" + (i + 1));
#region Voices
List<SoundEffect[]> SoundVoiceEffects = new List<SoundEffect[]>();
SoundEffect[] start = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/srt1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/srt2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/srt3")
};
SoundVoiceEffects.Add(start);
SoundEffect[] stationHit = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/sd1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/sd2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/sd3")
};
SoundVoiceEffects.Add(stationHit);
SoundEffect[] leaving = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/lb1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/lb2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/lb3")
};
SoundVoiceEffects.Add(leaving);
SoundEffect[] lose = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/bw1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/bw2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/bw3")
};
SoundVoiceEffects.Add(lose);
SoundEffect[] win = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/gw1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/gw2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/gw3")
};
SoundVoiceEffects.Add(win);
SoundEffect[] completed = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/boc1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/boc2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/boc3")
};
SoundVoiceEffects.Add(completed);
SoundEffect[] failed = {
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/bof1"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/bof2"),
Game.Content.Load<SoundEffect>(@"Game/Audio/Voice/Battlestation/bof3")
};
SoundVoiceEffects.Add(failed);
#endregion
SoundEngine soundEngine = new SoundEngine(soundEffectArray, voiceChatterSounds, musicSounds, SoundVoiceEffects, _save);
Texture2D[] hudOverlay = {
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Overlay/BottomLeftCorner"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Overlay/BottomRightCorner"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Overlay/TopLeftCorner"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Overlay/TopMiddle"),
Game.Content.Load<Texture2D>(@"Game/Images/HUD/Overlay/TopRightCorner")
};
GameEngineTEST = new GameEngine(playerShipTEST, level, enemySquadron, friendSquadron, explosionEngine, soundEngine);
Texture2D[] radarImages = { Game.Content.Load<Texture2D>(@"Game/Images/HUD/friend"), Game.Content.Load<Texture2D>(@"Game/Images/HUD/enemy"), Game.Content.Load<Texture2D>(@"Game/Images/HUD/friendBase"), Game.Content.Load<Texture2D>(@"Game/Images/HUD/enemyBase") };
ShipOverlay enemyOverlay = new ShipOverlay(Game.Content.Load<Texture2D>(@"Game/Images/HUD/EnemyOverlay"), _device, 3.7f);
ShipOverlay friendOverlay = new ShipOverlay(Game.Content.Load<Texture2D>(@"Game/Images/HUD/FriendOverlay"), _device, 3f);
HUDManager = new HUDManager(_device, _spriteBatch, spawnerManager, Game.Content.Load<SpriteFont>(@"Game/Fonts/Segoe"), Game.Content.Load<SpriteFont>(@"Game/Fonts/HUDFont"),
Game.Content.Load<SpriteFont>(@"Game/Fonts/SHUDFont"), radarImages, friendOverlay, enemyOverlay, hudOverlay, Game.Content.Load<Texture2D>(@"Game/Images/HUD/crosshairs"), _save);
_gameActive = true;
FinishedLoadingEvent();
}
private void FinishedLoadingEvent()
{
if (FinishedLoading != null)
{
FinishedLoading(this, EventArgs.Empty);
}
}
private static void PauseEvent()
{
if (Pause != null)
Pause(null, EventArgs.Empty);
}
}
}
| |
using Newtonsoft.Json;
using SteamKit2;
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace SteamTrade.TradeOffer
{
public class OfferSession
{
private readonly TradeOfferWebAPI webApi;
private readonly SteamWeb steamWeb;
internal JsonSerializerSettings JsonSerializerSettings { get; set; }
internal const string SendUrl = "https://steamcommunity.com/tradeoffer/new/send";
public OfferSession(TradeOfferWebAPI webApi, SteamWeb steamWeb)
{
this.webApi = webApi;
this.steamWeb = steamWeb;
JsonSerializerSettings = new JsonSerializerSettings();
JsonSerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
JsonSerializerSettings.Formatting = Formatting.None;
}
public bool Accept(string tradeOfferId, out string tradeId)
{
tradeId = "";
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("serverid", "1");
data.Add("tradeofferid", tradeOfferId);
string url = string.Format("https://steamcommunity.com/tradeoffer/{0}/accept", tradeOfferId);
string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId);
string resp = steamWeb.Fetch(url, "POST", data, false, referer);
if (!String.IsNullOrEmpty(resp))
{
try
{
var result = JsonConvert.DeserializeObject<TradeOfferAcceptResponse>(resp);
if (!String.IsNullOrEmpty(result.TradeId))
{
tradeId = result.TradeId;
return true;
}
//todo: log the error
Debug.WriteLine(result.TradeError);
}
catch (JsonException jsex)
{
Debug.WriteLine(jsex);
}
}
else
{
var state = webApi.GetOfferState(tradeOfferId);
if (state == TradeOfferState.TradeOfferStateAccepted)
{
return true;
}
}
return false;
}
public bool Decline(string tradeOfferId)
{
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("serverid", "1");
data.Add("tradeofferid", tradeOfferId);
string url = string.Format("https://steamcommunity.com/tradeoffer/{0}/decline", tradeOfferId);
//should be http://steamcommunity.com/{0}/{1}/tradeoffers - id/profile persona/id64 ideally
string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId);
var resp = steamWeb.Fetch(url, "POST", data, false, referer);
if (!String.IsNullOrEmpty(resp))
{
try
{
var json = JsonConvert.DeserializeObject<NewTradeOfferResponse>(resp);
if (json.TradeOfferId != null && json.TradeOfferId == tradeOfferId)
{
return true;
}
}
catch (JsonException jsex)
{
Debug.WriteLine(jsex);
}
}
else
{
var state = webApi.GetOfferState(tradeOfferId);
if (state == TradeOfferState.TradeOfferStateDeclined)
{
return true;
}
}
return false;
}
public bool Cancel(string tradeOfferId)
{
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("tradeofferid", tradeOfferId);
data.Add("serverid", "1");
string url = string.Format("https://steamcommunity.com/tradeoffer/{0}/cancel", tradeOfferId);
//should be http://steamcommunity.com/{0}/{1}/tradeoffers/sent/ - id/profile persona/id64 ideally
string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId);
var resp = steamWeb.Fetch(url, "POST", data, false, referer);
if (!String.IsNullOrEmpty(resp))
{
try
{
var json = JsonConvert.DeserializeObject<NewTradeOfferResponse>(resp);
if (json.TradeOfferId != null && json.TradeOfferId == tradeOfferId)
{
return true;
}
}
catch (JsonException jsex)
{
Debug.WriteLine(jsex);
}
}
else
{
var state = webApi.GetOfferState(tradeOfferId);
if (state == TradeOfferState.TradeOfferStateCanceled)
{
return true;
}
}
return false;
}
/// <summary>
/// Creates a new counter offer
/// </summary>
/// <param name="message">A message to include with the trade offer</param>
/// <param name="otherSteamId">The SteamID of the partner we are trading with</param>
/// <param name="status">The list of items we and they are going to trade</param>
/// <param name="newTradeOfferId">The trade offer Id that will be created if successful</param>
/// <param name="tradeOfferId">The trade offer Id of the offer being countered</param>
/// <returns></returns>
public bool CounterOffer(string message, SteamID otherSteamId, TradeOffer.TradeStatus status, out string newTradeOfferId, string tradeOfferId)
{
if (String.IsNullOrEmpty(tradeOfferId))
{
throw new ArgumentNullException("tradeOfferId", "Trade Offer Id must be set for counter offers.");
}
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("serverid", "1");
data.Add("partner", otherSteamId.ConvertToUInt64().ToString());
data.Add("tradeoffermessage", message);
data.Add("json_tradeoffer", JsonConvert.SerializeObject(status, JsonSerializerSettings));
data.Add("tradeofferid_countered", tradeOfferId);
data.Add("trade_offer_create_params", "{}");
string referer = string.Format("https://steamcommunity.com/tradeoffer/{0}/", tradeOfferId);
if (!Request(SendUrl, data, referer, tradeOfferId, out newTradeOfferId))
{
var state = webApi.GetOfferState(tradeOfferId);
if (state == TradeOfferState.TradeOfferStateCountered)
{
return true;
}
return false;
}
return true;
}
/// <summary>
/// Creates a new trade offer
/// </summary>
/// <param name="message">A message to include with the trade offer</param>
/// <param name="otherSteamId">The SteamID of the partner we are trading with</param>
/// <param name="status">The list of items we and they are going to trade</param>
/// <param name="newTradeOfferId">The trade offer Id that will be created if successful</param>
/// <returns>True if successfully returns a newTradeOfferId, else false</returns>
public bool SendTradeOffer(string message, SteamID otherSteamId, TradeOffer.TradeStatus status, out string newTradeOfferId)
{
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("serverid", "1");
data.Add("partner", otherSteamId.ConvertToUInt64().ToString());
data.Add("tradeoffermessage", message);
data.Add("json_tradeoffer", JsonConvert.SerializeObject(status, JsonSerializerSettings));
data.Add("trade_offer_create_params", "{}");
string referer = string.Format("https://steamcommunity.com/tradeoffer/new/?partner={0}",
otherSteamId.AccountID);
return Request(SendUrl, data, referer, null, out newTradeOfferId);
}
/// <summary>
/// Creates a new trade offer with a token
/// </summary>
/// <param name="message">A message to include with the trade offer</param>
/// <param name="otherSteamId">The SteamID of the partner we are trading with</param>
/// <param name="status">The list of items we and they are going to trade</param>
/// <param name="token">The token of the partner we are trading with</param>
/// <param name="newTradeOfferId">The trade offer Id that will be created if successful</param>
/// <returns>True if successfully returns a newTradeOfferId, else false</returns>
public bool SendTradeOfferWithToken(string message, SteamID otherSteamId, TradeOffer.TradeStatus status,
string token, out string newTradeOfferId)
{
if (String.IsNullOrEmpty(token))
{
throw new ArgumentNullException("token", "Partner trade offer token is missing");
}
var offerToken = new OfferAccessToken() { TradeOfferAccessToken = token };
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("serverid", "1");
data.Add("partner", otherSteamId.ConvertToUInt64().ToString());
data.Add("tradeoffermessage", message);
data.Add("json_tradeoffer", JsonConvert.SerializeObject(status, JsonSerializerSettings));
data.Add("trade_offer_create_params", JsonConvert.SerializeObject(offerToken, JsonSerializerSettings));
string referer = string.Format("https://steamcommunity.com/tradeoffer/new/?partner={0}&token={1}",
otherSteamId.AccountID, token);
return Request(SendUrl, data, referer, null, out newTradeOfferId);
}
internal bool Request(string url, NameValueCollection data, string referer, string tradeOfferId, out string newTradeOfferId)
{
newTradeOfferId = "";
string resp = steamWeb.Fetch(url, "POST", data, false, referer);
if (!String.IsNullOrEmpty(resp))
{
try
{
var offerResponse = JsonConvert.DeserializeObject<NewTradeOfferResponse>(resp);
if (!String.IsNullOrEmpty(offerResponse.TradeOfferId))
{
newTradeOfferId = offerResponse.TradeOfferId;
return true;
}
else
{
//todo: log possible error
Debug.WriteLine(offerResponse.TradeError);
}
}
catch (JsonException jsex)
{
Debug.WriteLine(jsex);
}
}
return false;
}
}
public class NewTradeOfferResponse
{
[JsonProperty("tradeofferid")]
public string TradeOfferId { get; set; }
[JsonProperty("strError")]
public string TradeError { get; set; }
}
public class OfferAccessToken
{
[JsonProperty("trade_offer_access_token")]
public string TradeOfferAccessToken { get; set; }
}
public class TradeOfferAcceptResponse
{
[JsonProperty("tradeid")]
public string TradeId { get; set; }
[JsonProperty("strError")]
public string TradeError { get; set; }
public TradeOfferAcceptResponse()
{
TradeId = String.Empty;
TradeError = String.Empty;
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
#if !NETCOREAPP1_1
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Tests.Assemblies;
namespace NUnitLite.Tests
{
public class NUnit3XmlOutputWriterTests
{
private XmlDocument doc;
private XmlNode topNode;
private XmlNode envNode;
private XmlNode suiteNode;
[OneTimeSetUp]
public void RunMockAssemblyTests()
{
ITestResult result = NUnit.TestUtilities.TestBuilder.RunTestFixture(typeof(MockTestFixture));
Assert.NotNull(result);
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
new NUnit3XmlOutputWriter().WriteResultFile(result, writer, null, null);
writer.Close();
#if DEBUG
StreamWriter sw = new StreamWriter("MockAssemblyResult.xml");
sw.WriteLine(sb.ToString());
sw.Close();
#endif
doc = new XmlDocument();
doc.LoadXml(sb.ToString());
topNode = doc.SelectSingleNode("/test-run");
if (topNode != null)
{
suiteNode = topNode.SelectSingleNode("test-suite");
envNode = suiteNode.SelectSingleNode("environment");
}
}
[Test]
public void Document_HasTwoChildren()
{
Assert.That(doc.ChildNodes.Count, Is.EqualTo(2));
}
[Test]
public void Document_FirstChildIsXmlDeclaration()
{
Assume.That(doc.FirstChild != null);
Assert.That(doc.FirstChild.NodeType, Is.EqualTo(XmlNodeType.XmlDeclaration));
Assert.That(doc.FirstChild.Name, Is.EqualTo("xml"));
}
[Test]
public void Document_SecondChildIsComment()
{
Assume.That(doc.ChildNodes.Count >= 2);
Assert.That(doc.ChildNodes[1].Name, Is.EqualTo("test-run"));
}
[Test]
public void Document_HasTestResults()
{
Assert.That(topNode, Is.Not.Null);
Assert.That(topNode.Name, Is.EqualTo("test-run"));
}
[Test]
public void TestResults_AssemblyPathIsCorrect()
{
Assert.That(RequiredAttribute(topNode, "fullname"), Is.EqualTo("NUnit.Tests.Assemblies.MockTestFixture"));
Assert.That(RequiredAttribute(topNode, "name"), Is.EqualTo("MockTestFixture"));
}
[TestCase("testcasecount", MockTestFixture.Tests)]
[TestCase("passed", MockTestFixture.Passed)]
[TestCase("failed", MockTestFixture.Failed)]
[TestCase("inconclusive", MockTestFixture.Inconclusive)]
[TestCase("skipped", MockTestFixture.Skipped)]
public void TestResults_CounterIsCorrect(string name, int count)
{
Assert.That(RequiredAttribute(topNode, name), Is.EqualTo(count.ToString()));
}
[Test]
public void TestResults_HasValidStartTimeAttribute()
{
string startTimeString = RequiredAttribute(topNode, "start-time");
Assert.That(DateTime.TryParseExact(startTimeString, "o", CultureInfo.InvariantCulture, DateTimeStyles.None, out _), "Invalid start time attribute: {0}. Expecting DateTime in 'o' format.", startTimeString);
}
[Test]
public void TestResults_HasValidEndTimeAttribute()
{
string endTimeString = RequiredAttribute(topNode, "end-time");
Assert.That(DateTime.TryParseExact(endTimeString, "o", CultureInfo.InvariantCulture, DateTimeStyles.None, out _), "Invalid end time attribute: {0}. Expecting DateTime in 'o' format.", endTimeString);
}
[Test]
public void Environment_HasEnvironmentElement()
{
Assert.That(envNode, Is.Not.Null, "Missing environment element");
}
[TestCase("framework-version")]
[TestCase("clr-version")]
[TestCase("os-version")]
[TestCase("platform")]
[TestCase("cwd")]
[TestCase("machine-name")]
[TestCase("user")]
[TestCase("user-domain")]
[TestCase("os-architecture")]
public void Environment_HasRequiredAttribute(string name)
{
RequiredAttribute(envNode, name);
}
[Test]
public void CultureInfo_HasCultureInfoElement()
{
Assert.That(envNode.Attributes["culture"], Is.Not.Null, "Missing culture-info attribute");
}
[TestCase("culture")]
[TestCase("uiculture")]
public void CultureInfo_HasRequiredAttribute(string name)
{
string cultureName = RequiredAttribute(envNode, name);
System.Globalization.CultureInfo culture = null;
try
{
culture = System.Globalization.CultureInfo.CreateSpecificCulture(cultureName);
}
catch (ArgumentException)
{
// Do nothing - culture will be null
}
Assert.That(culture, Is.Not.Null, "Invalid value for {0}: {1}", name, cultureName);
}
[Test]
public void TestSuite_HasTestSuiteElement()
{
Assert.That(suiteNode, Is.Not.Null, "Missing test-suite element");
}
[TestCase("type", "TestFixture")]
[TestCase("name", "MockTestFixture")]
[TestCase("fullname", "NUnit.Tests.Assemblies.MockTestFixture")]
[TestCase("classname", "NUnit.Tests.Assemblies.MockTestFixture")]
[TestCase("runstate", "Runnable")]
[TestCase("result", "Failed")]
[TestCase("asserts", "0")]
public void TestSuite_ExpectedAttribute(string name, string value)
{
Assert.That(RequiredAttribute(suiteNode, name), Is.EqualTo(value));
}
[Test]
public void TestSuite_HasValidStartTimeAttribute()
{
var startTimeString = RequiredAttribute(suiteNode, "start-time");
var success = DateTime.TryParse(startTimeString, out _);
Assert.That(success, "{0} is an invalid value for start time", startTimeString);
}
[Test]
public void TestSuite_HasValidEndTimeAttribute()
{
var endTimeString = RequiredAttribute(suiteNode, "end-time");
var success = DateTime.TryParse(endTimeString, out _);
Assert.That(success, "{0} is an invalid value for end time", endTimeString);
}
[Test]
public void IgnoredTestCases_HaveValidStartAndEndTimeAttributes()
{
DateTime.TryParse(RequiredAttribute(topNode, "start-time"), out var testRunStartTime);
DateTime.TryParse(RequiredAttribute(topNode, "end-time"), out var testRunEndTime);
var testCaseNodes = suiteNode.SelectNodes("test-suite[@name='SkippedTest']/test-case");
Assert.That(testCaseNodes, Is.Not.Null.And.Count.EqualTo(3));
foreach (XmlNode testCase in testCaseNodes)
{
string startTimeStr = RequiredAttribute(testCase, "start-time");
string endTimeStr = RequiredAttribute(testCase, "end-time");
Assert.That(startTimeStr, Does.EndWith("Z"), "Ignored start-time is not UTC");
Assert.That(endTimeStr, Does.EndWith("Z"), "Ignored end-time is not UTC");
Assert.IsTrue(DateTime.TryParse(startTimeStr, out var startTime));
Assert.IsTrue(DateTime.TryParse(endTimeStr, out var endTime));
Assert.That(startTime, Is.InRange(testRunStartTime, testRunEndTime), "Ignored test cases should be set to approximately the start time of test suite");
Assert.That(endTime, Is.InRange(testRunStartTime, testRunEndTime), "Ignored test cases should be set to approximately the end time of test suite");
}
}
[Test]
public void ExplicitTest_HasValidStartAndEndTimeAttributes()
{
DateTime.TryParse(RequiredAttribute(topNode, "start-time"), out var testRunStartTime);
DateTime.TryParse(RequiredAttribute(topNode, "end-time"), out var testRunEndTime);
var testCaseNodes = suiteNode.SelectNodes("test-case[@name='ExplicitTest']");
Assert.That(testCaseNodes, Is.Not.Null.And.Count.EqualTo(1));
XmlNode testCase = testCaseNodes[0];
string startTimeStr = RequiredAttribute(testCase, "start-time");
string endTimeStr = RequiredAttribute(testCase, "end-time");
Assert.That(startTimeStr, Does.EndWith("Z"), "Explicit start-time is not UTC");
Assert.That(endTimeStr, Does.EndWith("Z"), "Explicit end-time is not UTC");
Assert.IsTrue(DateTime.TryParse(startTimeStr, out var startTime));
Assert.IsTrue(DateTime.TryParse(endTimeStr, out var endTime));
Assert.That(startTime, Is.InRange(testRunStartTime, testRunEndTime), "Explicit test cases should be set to approximately the start time of test suite");
Assert.That(endTime, Is.InRange(testRunStartTime, testRunEndTime), "Explicit test cases should be set to approximately the end time of test suite");
}
#region Helper Methods
private string RequiredAttribute(XmlNode node, string name)
{
XmlAttribute attr = node.Attributes[name];
Assert.That(attr, Is.Not.Null, "Missing attribute {0} on element {1}", name, node.Name);
return attr.Value;
}
#endregion
}
}
#endif
| |
// ***********************************************************************
// Copyright (c) 2007-2013 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using NUnit.Framework.Internal;
using NUnit.TestUtilities.Comparers;
namespace NUnit.Framework.Constraints
{
[TestFixture]
public class EqualConstraintTests : ConstraintTestBase
{
[SetUp]
public void SetUp()
{
theConstraint = new EqualConstraint(4);
expectedDescription = "4";
stringRepresentation = "<equal 4>";
}
static object[] SuccessData = new object[] {4, 4.0f, 4.0d, 4.0000m};
static object[] FailureData = new object[]
{
new TestCaseData(5, "5"),
new TestCaseData(null, "null"),
new TestCaseData("Hello", "\"Hello\""),
new TestCaseData(double.NaN, double.NaN.ToString()),
new TestCaseData(double.PositiveInfinity, double.PositiveInfinity.ToString())
};
#region DateTimeEquality
public class DateTimeEquality
{
[Test]
public void CanMatchDates()
{
DateTime expected = new DateTime(2007, 4, 1);
DateTime actual = new DateTime(2007, 4, 1);
Assert.That(actual, new EqualConstraint(expected));
}
[Test]
public void CanMatchDatesWithinTimeSpan()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
TimeSpan tolerance = TimeSpan.FromMinutes(5.0);
Assert.That(actual, new EqualConstraint(expected).Within(tolerance));
}
[Test]
public void CanMatchDatesWithinDays()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 4, 13, 0, 0);
Assert.That(actual, new EqualConstraint(expected).Within(5).Days);
}
[Test]
public void CanMatchDatesWithinHours()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 16, 0, 0);
Assert.That(actual, new EqualConstraint(expected).Within(5).Hours);
}
[Test]
public void CanMatchUsingIsEqualToWithinTimeSpan()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, Is.EqualTo(expected).Within(TimeSpan.FromMinutes(2)));
}
[Test]
public void CanMatchDatesWithinMinutes()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
}
[Test]
public void CanMatchTimeSpanWithinMinutes()
{
TimeSpan expected = new TimeSpan(10, 0, 0);
TimeSpan actual = new TimeSpan(10, 2, 30);
Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
}
[Test]
public void CanMatchDatesWithinSeconds()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds);
}
[Test]
public void CanMatchDatesWithinMilliseconds()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds);
}
[Test]
public void CanMatchDatesWithinTicks()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks);
}
[Test]
public void ErrorIfDaysPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Days.Within(5)));
}
[Test]
public void ErrorIfHoursPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Hours.Within(5)));
}
[Test]
public void ErrorIfMinutesPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Minutes.Within(5)));
}
[Test]
public void ErrorIfSecondsPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Seconds.Within(5)));
}
[Test]
public void ErrorIfMillisecondsPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Milliseconds.Within(5)));
}
[Test]
public void ErrorIfTicksPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Ticks.Within(5)));
}
}
#endregion
#region DateTimeOffsetEquality
public class DateTimeOffsetShouldBeSame
{
[Datapoints]
public static readonly DateTimeOffset[] sameDateTimeOffsets =
{
new DateTimeOffset(new DateTime(2014, 1, 30, 12, 34, 56), new TimeSpan(6, 15, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 0, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 1, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 55), new TimeSpan(3, 0, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 55), new TimeSpan(3, 50, 0))
};
[Theory]
public void PositiveEqualityTest(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That(value1 == value2);
Assert.That(value1, Is.EqualTo(value2));
}
[Theory]
public void NegativeEqualityTest(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That(value1 != value2);
Assert.That(value1, Is.Not.EqualTo(value2));
}
[Theory]
public void PositiveEqualityTestWithTolerance(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
Assert.That(value1, Is.EqualTo(value2).Within(1).Minutes);
}
[Theory]
public void NegativeEqualityTestWithTolerance(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() > new TimeSpan(0, 1, 0));
Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes);
}
[Theory]
public void NegativeEqualityTestWithToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() > new TimeSpan(0, 1, 0));
Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes.WithSameOffset);
}
[Theory]
public void PositiveEqualityTestWithToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
Assume.That(value1.Offset == value2.Offset);
Assert.That(value1, Is.EqualTo(value2).Within(1).Minutes.WithSameOffset);
}
[Theory]
public void NegativeEqualityTestWithinToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
Assume.That(value1.Offset != value2.Offset);
Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes.WithSameOffset);
}
}
public class DateTimeOffSetEquality
{
[Test]
public void CanMatchDates()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1));
Assert.That(actual, new EqualConstraint(expected));
}
[Test]
public void CanMatchDatesWithinTimeSpan()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
var tolerance = TimeSpan.FromMinutes(5.0);
Assert.That(actual, new EqualConstraint(expected).Within(tolerance));
}
[Test]
public void CanMatchDatesWithinDays()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 4, 13, 0, 0));
Assert.That(actual, new EqualConstraint(expected).Within(5).Days);
}
[Test]
public void CanMatchUsingIsEqualToWithinTimeSpan()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, Is.EqualTo(expected).Within(TimeSpan.FromMinutes(2)));
}
[Test]
public void CanMatchDatesWithinMinutes()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
}
[Test]
public void CanMatchDatesWithinSeconds()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds);
}
[Test]
public void CanMatchDatesWithinMilliseconds()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds);
}
[Test]
public void CanMatchDatesWithinTicks()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks);
}
[Test]
public void DTimeOffsetCanMatchDatesWithinHours()
{
var a = DateTimeOffset.Parse("2012-01-01T12:00Z");
var b = DateTimeOffset.Parse("2012-01-01T12:01Z");
Assert.That(a, Is.EqualTo(b).Within(TimeSpan.FromMinutes(2)));
}
}
#endregion
#region DictionaryEquality
public class DictionaryEquality
{
[Test]
public void CanMatchDictionaries_SameOrder()
{
Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}});
}
[Test]
public void CanMatchDictionaries_Failure()
{
Assert.Throws<AssertionException>(
() => Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {1, 5}, {2, 2}}));
}
[Test]
public void CanMatchDictionaries_DifferentOrder()
{
Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {2, 2}, {1, 1}});
}
#if !NETCOREAPP1_1
[Test]
public void CanMatchHashtables_SameOrder()
{
Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Hashtable {{0, 0}, {1, 1}, {2, 2}});
}
[Test]
public void CanMatchHashtables_Failure()
{
Assert.Throws<AssertionException>(
() => Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Hashtable {{0, 0}, {1, 5}, {2, 2}}));
}
[Test]
public void CanMatchHashtables_DifferentOrder()
{
Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Hashtable {{0, 0}, {2, 2}, {1, 1}});
}
[Test]
public void CanMatchHashtableWithDictionary()
{
Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {2, 2}, {1, 1}});
}
#endif
}
#endregion
#region FloatingPointEquality
public class FloatingPointEquality
{
[TestCase(double.NaN)]
[TestCase(double.PositiveInfinity)]
[TestCase(double.NegativeInfinity)]
[TestCase(float.NaN)]
[TestCase(float.PositiveInfinity)]
[TestCase(float.NegativeInfinity)]
public void CanMatchSpecialFloatingPointValues(object value)
{
Assert.That(value, new EqualConstraint(value));
}
[TestCase(20000000000000004.0)]
[TestCase(19999999999999996.0)]
public void CanMatchDoublesWithUlpTolerance(object value)
{
Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps);
}
[TestCase(20000000000000008.0)]
[TestCase(19999999999999992.0)]
public void FailsOnDoublesOutsideOfUlpTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps));
Assert.That(ex.Message, Does.Contain("+/- 1 Ulps"));
}
[TestCase(19999998.0f)]
[TestCase(20000002.0f)]
public void CanMatchSinglesWithUlpTolerance(object value)
{
Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps);
}
[TestCase(19999996.0f)]
[TestCase(20000004.0f)]
public void FailsOnSinglesOutsideOfUlpTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps));
Assert.That(ex.Message, Does.Contain("+/- 1 Ulps"));
}
[TestCase(9500.0)]
[TestCase(10000.0)]
[TestCase(10500.0)]
public void CanMatchDoublesWithRelativeTolerance(object value)
{
Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent);
}
[TestCase(8500.0)]
[TestCase(11500.0)]
public void FailsOnDoublesOutsideOfRelativeTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent));
Assert.That(ex.Message, Does.Contain("+/- 10.0d Percent"));
}
[TestCase(9500.0f)]
[TestCase(10000.0f)]
[TestCase(10500.0f)]
public void CanMatchSinglesWithRelativeTolerance(object value)
{
Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent);
}
[TestCase(8500.0f)]
[TestCase(11500.0f)]
public void FailsOnSinglesOutsideOfRelativeTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent));
Assert.That(ex.Message, Does.Contain("+/- 10.0f Percent"));
}
/// <summary>Applies both the Percent and Ulps modifiers to cause an exception</summary>
[Test]
public void ErrorWithPercentAndUlpsToleranceModes()
{
Assert.Throws<InvalidOperationException>(() =>
{
var shouldFail = new EqualConstraint(100.0f).Within(10.0f).Percent.Ulps;
});
}
/// <summary>Applies both the Ulps and Percent modifiers to cause an exception</summary>
[Test]
public void ErrorWithUlpsAndPercentToleranceModes()
{
Assert.Throws<InvalidOperationException>(() =>
{
EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Ulps.Percent;
});
}
[Test]
public void ErrorIfPercentPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(1010, Is.EqualTo(1000).Percent.Within(5)));
}
[Test]
public void ErrorIfUlpsPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(1010.0, Is.EqualTo(1000.0).Ulps.Within(5)));
}
[TestCase(1000, 1010)]
[TestCase(1000U, 1010U)]
[TestCase(1000L, 1010L)]
[TestCase(1000UL, 1010UL)]
public void ErrorIfUlpsIsUsedOnIntegralType(object x, object y)
{
Assert.Throws<InvalidOperationException>(() => Assert.That(y, Is.EqualTo(x).Within(2).Ulps));
}
[Test]
public void ErrorIfUlpsIsUsedOnDecimal()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(100m, Is.EqualTo(100m).Within(2).Ulps));
}
}
#endregion
#region UsingModifier
public class UsingModifier
{
[Test]
public void UsesProvidedIComparer()
{
var comparer = new ObjectComparer();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void CanCompareUncomparableTypes()
{
Assert.That(2 + 2, Is.Not.EqualTo("4"));
var comparer = new ConvertibleComparer();
Assert.That(2 + 2, Is.EqualTo("4").Using(comparer));
}
[Test]
public void UsesProvidedEqualityComparer()
{
var comparer = new ObjectEqualityComparer();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.Called, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericEqualityComparer()
{
var comparer = new GenericEqualityComparer<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericComparer()
{
var comparer = new GenericComparer<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericComparison()
{
var comparer = new GenericComparison<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer.Delegate));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericEqualityComparison()
{
var comparer = new GenericEqualityComparison<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using<int>(comparer.Delegate));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesBooleanReturningDelegate()
{
Assert.That(2 + 2, Is.EqualTo(4).Using<int>((x, y) => x.Equals(y)));
}
[Test]
public void UsesProvidedLambda_IntArgs()
{
Assert.That(2 + 2, Is.EqualTo(4).Using<int>((x, y) => x.CompareTo(y)));
}
[Test]
public void UsesProvidedLambda_StringArgs()
{
Assert.That("hello", Is.EqualTo("HELLO").Using<string>((x, y) => StringUtil.Compare(x, y, true)));
}
[Test]
public void UsesProvidedListComparer()
{
var list1 = new List<int>() {2, 3};
var list2 = new List<int>() {3, 4};
var list11 = new List<List<int>>() {list1};
var list22 = new List<List<int>>() {list2};
var comparer = new IntListEqualComparer();
Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer));
}
public class IntListEqualComparer : IEqualityComparer<List<int>>
{
public bool Equals(List<int> x, List<int> y)
{
return x.Count == y.Count;
}
public int GetHashCode(List<int> obj)
{
return obj.Count.GetHashCode();
}
}
[Test]
public void UsesProvidedArrayComparer()
{
var array1 = new int[] {2, 3};
var array2 = new int[] {3, 4};
var list11 = new List<int[]>() {array1};
var list22 = new List<int[]>() {array2};
var comparer = new IntArrayEqualComparer();
Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer));
}
public class IntArrayEqualComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
return x.Length == y.Length;
}
public int GetHashCode(int[] obj)
{
return obj.Length.GetHashCode();
}
}
[Test]
public void HasMemberHonorsUsingWhenCollectionsAreOfDifferentTypes()
{
ICollection strings = new List<string> { "1", "2", "3" };
Assert.That(strings, Has.Member(2).Using<string, int>((s, i) => i.ToString() == s));
}
}
#endregion
#region TypeEqualityMessages
private readonly string NL = Environment.NewLine;
private static IEnumerable DifferentTypeSameValueTestData
{
get
{
var ptr = new System.IntPtr(0);
var ExampleTestA = new ExampleTest.classA(0);
var ExampleTestB = new ExampleTest.classB(0);
var clipTestA = new ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere();
var clipTestB = new ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere();
yield return new object[] { 0, ptr };
yield return new object[] { ExampleTestA, ExampleTestB };
yield return new object[] { clipTestA, clipTestB };
}
}
[Test]
public void SameValueDifferentTypeExactMessageMatch()
{
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(0, new System.IntPtr(0)));
Assert.AreEqual(ex.Message, " Expected: 0 (Int32)"+ NL + " But was: 0 (IntPtr)"+ NL);
}
class Dummy
{
internal readonly int value;
public Dummy(int value)
{
this.value = value;
}
public override string ToString()
{
return "Dummy " + value;
}
}
class Dummy1
{
internal readonly int value;
public Dummy1(int value)
{
this.value = value;
}
public override string ToString()
{
return "Dummy " + value;
}
}
class DummyGenericClass<T>
{
private object _obj;
public DummyGenericClass(object obj)
{
_obj = obj;
}
public override string ToString()
{
return _obj.ToString();
}
}
[Test]
public void TestSameValueDifferentTypeUsingGenericTypes()
{
var d1 = new Dummy(12);
var d2 = new Dummy1(12);
var dc1 = new DummyGenericClass<Dummy>(d1);
var dc2 = new DummyGenericClass<Dummy1>(d2);
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dc1, dc2));
var expectedMsg =
" Expected: <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy])" + Environment.NewLine +
" But was: <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy1])" + Environment.NewLine;
Assert.AreEqual(expectedMsg, ex.Message);
}
[Test]
public void SameValueAndTypeButDifferentReferenceShowNotShowTypeDifference()
{
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Is.Zero, Is.Zero));
Assert.AreEqual(ex.Message, " Expected: <<equal 0>>"+ NL + " But was: <<equal 0>>"+ NL);
}
[Test, TestCaseSource("DifferentTypeSameValueTestData")]
public void SameValueDifferentTypeRegexMatch(object expected, object actual)
{
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(expected, actual));
Assert.That(ex.Message, Does.Match(@"\s*Expected\s*:\s*.*\s*\(.+\)\r?\n\s*But\s*was\s*:\s*.*\s*\(.+\)"));
}
}
namespace ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip {
class ReallyLongClassNameShouldBeHere {
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return obj.ToString() == this.ToString();
}
public override int GetHashCode()
{
return "a".GetHashCode();
}
public override string ToString()
{
return "a";
}
}
}
namespace ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip
{
class ReallyLongClassNameShouldBeHere {
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return obj.ToString()==this.ToString();
}
public override int GetHashCode()
{
return "a".GetHashCode();
}
public override string ToString()
{
return "a";
}
}
}
namespace ExampleTest {
class baseTest {
readonly int _value;
public baseTest()
{
_value = 0;
}
public baseTest(int value) {
_value = value;
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return _value.Equals(((baseTest)obj)._value);
}
public override string ToString()
{
return _value.ToString();
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
class classA : baseTest {
public classA(int x) : base(x) { }
}
class classB : baseTest
{
public classB(int x) : base(x) { }
}
}
#endregion
/// <summary>
/// ConvertibleComparer is used in testing to ensure that objects
/// of different types can be compared when appropriate.
/// </summary>
/// <remark>Introduced when testing issue 1897.
/// https://github.com/nunit/nunit/issues/1897
/// </remark>
public class ConvertibleComparer : IComparer<IConvertible>
{
public int Compare(IConvertible x, IConvertible y)
{
var str1 = Convert.ToString(x, CultureInfo.InvariantCulture);
var str2 = Convert.ToString(y, CultureInfo.InvariantCulture);
return string.Compare(str1, str2, StringComparison.Ordinal);
}
}
}
| |
using System;
using System.IO;
/*
* This stream handles sending and receiving SSL/TLS records (unencrypted).
*
* In output mode:
* -- data is buffered until a full record is obtained
* -- an explicit Flush() call terminates and sends the current record
* (only if there is data to send)
* -- record type is set explicitly
*
* In input mode:
* -- records MUST have the set expected type, or be alerts
* -- warning-level alerts are ignored
* -- fatal-level alerts trigger SSLAlertException
* -- record type mismatch triggers exceptions
* -- first received record sets version (from record header); all
* subsequent records MUST have the same version
*/
class SSLRecord : Stream {
const int MAX_RECORD_LEN = 16384;
Stream sub;
byte[] outBuf = new byte[MAX_RECORD_LEN + 5];
int outPtr;
int outVersion;
int outType;
byte[] inBuf = new byte[MAX_RECORD_LEN];
int inPtr;
int inEnd;
int inVersion;
int inType;
int inExpectedType;
bool dumpBytes;
/*
* Create an instance over the provided stream (normally a
* network socket).
*/
internal SSLRecord(Stream sub)
{
this.sub = sub;
outPtr = 5;
inPtr = 0;
inEnd = 0;
dumpBytes = false;
}
internal bool DumpBytes {
get {
return dumpBytes;
}
set {
dumpBytes = value;
}
}
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Length {
get { throw new NotSupportedException(); }
}
public override long Position {
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/*
* Set record type. If it differs from the a previously set
* record type, then an automatic flush is performed.
*/
internal void SetOutType(int type)
{
if (outType != 0 && outType != type) {
Flush();
}
outType = type;
}
/*
* Set the version for the next outgoing record.
*/
internal void SetOutVersion(int version)
{
outVersion = version;
}
/*
* Flush accumulated data. Nothing is done if there is no
* accumulated data.
*/
public override void Flush()
{
if (outPtr > 5) {
outBuf[0] = (byte)outType;
M.Enc16be(outVersion, outBuf, 1);
M.Enc16be(outPtr - 5, outBuf, 3);
if (dumpBytes) {
Console.WriteLine(">>> record header");
Dump(outBuf, 0, 5);
Console.WriteLine(">>> record data");
Dump(outBuf, 5, outPtr - 5);
}
sub.Write(outBuf, 0, outPtr);
outPtr = 5;
}
sub.Flush();
}
public override void WriteByte(byte b)
{
outBuf[outPtr ++] = b;
if (outPtr == outBuf.Length) {
Flush();
}
}
public void Write(byte[] buf)
{
Write(buf, 0, buf.Length);
}
public override void Write(byte[] buf, int off, int len)
{
while (len > 0) {
int clen = Math.Min(outBuf.Length - outPtr, len);
Array.Copy(buf, off, outBuf, outPtr, clen);
outPtr += clen;
off += clen;
len -= clen;
if (outPtr == outBuf.Length) {
Flush();
}
}
}
/*
* Raw write: write some data on the underlying stream,
* bypassing the record layer. This is used to send a ClientHello
* in V2 format.
*/
internal void RawWrite(byte[] buf)
{
RawWrite(buf, 0, buf.Length);
}
/*
* Raw write: write some data on the underlying stream,
* bypassing the record layer. This is used to send a ClientHello
* in V2 format.
*/
internal void RawWrite(byte[] buf, int off, int len)
{
if (dumpBytes) {
Console.WriteLine(">>> raw write");
Dump(buf, off, len);
}
sub.Write(buf, off, len);
}
/*
* Set expected type for incoming records.
*/
internal void SetExpectedType(int expectedType)
{
this.inExpectedType = expectedType;
}
/*
* Get the version advertised in the last incoming record.
*/
internal int GetInVersion()
{
return inVersion;
}
/*
* Obtain next record. Incoming alerts are processed; this method
* exists when the next record of the expected type is received
* (though it may contain an empty payload).
*/
void Refill()
{
for (;;) {
M.ReadFully(sub, inBuf, 0, 5);
if (dumpBytes) {
Console.WriteLine("<<< record header");
Dump(inBuf, 0, 5);
}
inType = inBuf[0];
int v = M.Dec16be(inBuf, 1);
inEnd = M.Dec16be(inBuf, 3);
if ((v >> 8) != 0x03) {
throw new IOException(string.Format(
"not an SSL 3.x record (0x{0:X4})", v));
}
if (inVersion != 0 && inVersion != v) {
throw new IOException(string.Format(
"record version change"
+ " (0x{0:X4} -> 0x{1:X4})",
inVersion, v));
}
inVersion = v;
if (inEnd > inBuf.Length) {
throw new IOException(string.Format(
"oversized input payload (len={0})",
inEnd));
}
if (inType != inExpectedType && inType != M.ALERT) {
throw new IOException(string.Format(
"unexpected record type ({0})",
inType));
}
M.ReadFully(sub, inBuf, 0, inEnd);
if (dumpBytes) {
Console.WriteLine("<<< record data");
Dump(inBuf, 0, inEnd);
}
inPtr = 0;
if (inType == M.ALERT) {
for (int k = 0; k < inEnd; k += 2) {
int at = inBuf[k];
if (at != 0x01) {
throw new SSLAlertException(at);
}
}
/*
* We just ignore warnings.
*/
continue;
}
return;
}
}
public override int ReadByte()
{
while (inPtr == inEnd) {
Refill();
}
return inBuf[inPtr ++];
}
public override int Read(byte[] buf, int off, int len)
{
while (inPtr == inEnd) {
Refill();
}
int clen = Math.Min(inEnd - inPtr, len);
Array.Copy(inBuf, inPtr, buf, off, clen);
inPtr += clen;
return clen;
}
static void Dump(byte[] buf, int off, int len)
{
for (int i = 0; i < len; i += 16) {
Console.Write(" {0:x8} ", i);
for (int j = 0; j < 16 && (i + j) < len; j ++) {
if (j == 8) {
Console.Write(" ");
}
Console.Write(" {0:x2}", buf[off + i + j]);
}
Console.WriteLine();
}
}
}
| |
/*
*
* Copyright (c) 2007-2013 MindTouch. All rights reserved.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using SgmlCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SGMLTestsCore {
[TestClass]
public partial class Tests {
//--- Methods ---
[TestMethod]
public void Convert_attribute_without_value_01() {
Test("01.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_attribute_with_missing_closing_quote_before_closing_tag_char_02() {
Test("02.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_attribute_with_missing_closing_quote_before_opening_tag_char_03() {
Test("03.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_text_with_wrong_entities_or_entities_with_missing_trailing_semicolon_04() {
Test("04.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Read_text_with_32bit_numeric_entity_05() {
Test("05.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Read_text_from_ms_office_06() {
Test("06.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_attribute_with_nested_quotes_07() {
Test("07.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Allow_CData_section_with_xml_chars_08() {
Test("08.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Convert_tags_to_lower_09() {
Test("09.test", XmlRender.Passthrough, CaseFolding.ToLower, "html", true);
}
[TestMethod]
public void Test_whitespace_aware_processing_10() {
Test("10.test", XmlRender.Passthrough, CaseFolding.None, "html", false);
}
[TestMethod]
public void Recover_from_attribute_value_with_extra_quote_11() {
Test("11.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_unclosed_xml_comment_12() {
Test("12.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Allow_xml_only_apos_entity_in_html_13() {
Test("13.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_script_tag_as_root_element_14() {
Test("14.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Read_namespaced_attributes_with_missing_namespace_declaration_15() {
Test("15.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Decode_entity_16() {
Test("16.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Convert_element_with_illegal_tag_name_17() {
Test("17.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Strip_comments_in_CData_section_18() {
Test("18.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Nest_contents_of_style_element_into_a_CData_section_19() {
Test("19.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Dont_push_elements_out_of_the_body_element_even_when_illegal_inside_body_20() {
Test("20.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Clone_document_with_invalid_attribute_declarations_21() {
Test("21.test", XmlRender.DocClone, CaseFolding.None, "html", true);
}
[TestMethod]
public void Ignore_conditional_comments_22() {
Test("22.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Preserve_explicit_and_implicit_attribute_and_element_namespaces_23() {
Test("23.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Preserve_explicit_attribute_and_element_namespaces_24() {
Test("24.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Clone_document_with_explicit_attribute_and_element_namespaces_25() {
Test("25.test", XmlRender.DocClone, CaseFolding.None, "html", true);
}
[TestMethod]
public void Preserve_explicit_attribute_namespaces_26() {
Test("26.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Clone_document_with_explicit_attribute_namespaces_with_clone_27() {
Test("27.test", XmlRender.DocClone, CaseFolding.None, "html", true);
}
[TestMethod]
public void Clone_document_with_explicit_element_namespaces_with_clone_28() {
Test("28.test", XmlRender.DocClone, CaseFolding.None, "html", true);
}
[TestMethod]
public void Read_namespaced_elements_with_missing_namespace_declaration_29() {
Test("29.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Clone_document_with_namespaced_elements_with_missing_namespace_declaration_with_clone_30() {
Test("30.test", XmlRender.DocClone, CaseFolding.None, "html", true);
}
[TestMethod]
public void Parse_html_document_without_closing_body_tag_31() {
Test("31.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Parse_html_document_with_leading_whitespace_and_missing_closing_tag_32() {
Test("32.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Parse_doctype_33() {
Test("33.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[Ignore("marked as ignore, because it conflicts with another behavior of never pushing elements from the body tag")]
public void Push_invalid_element_out_of_body_tag_34() {
// NOTE (bjorg): marked as ignore, because it conflicts with another behavior of never pushing elements from the body tag.
Test("34.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Add_missing_closing_element_tags_35() {
Test("35.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Preserve_xml_comments_inside_script_element_36() {
Test("36.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Allow_CDData_section_with_markup_37() {
Test("37.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Recover_from_rogue_open_tag_char_38() {
Test("38.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Ignore_invalid_char_after_tag_name_39() {
Test("39.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Convert_entity_to_char_code_40() {
Test("40.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Attribute_with_missing_equal_sign_between_key_and_value_41() {
Test("41.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Script_element_with_explicit_CDData_section_42() {
Test("42.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Convert_tags_to_lower_43() {
Test("43.test", XmlRender.Passthrough, CaseFolding.ToLower, "html", true);
}
[TestMethod]
public void Load_document_44() {
Test("44.test", XmlRender.Doc, CaseFolding.None, "html", true);
}
[TestMethod]
public void Load_document_with_text_before_root_node_45() {
Test("45.test", XmlRender.Doc, CaseFolding.None, "html", true);
}
[TestMethod]
public void Load_document_with_text_before_root_node_46() {
// NOTE (steveb): this is a dup of the previous test
Test("46.test", XmlRender.Doc, CaseFolding.None, "html", true);
}
[TestMethod]
public void Load_document_with_xml_comment_before_root_node_47() {
Test("47.test", XmlRender.Doc, CaseFolding.None, "html", true);
}
[TestMethod]
public void Decode_numeric_entities_for_non_html_content_48() {
Test("48.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Load_document_with_nested_xml_declaration_49() {
Test("49.test", XmlRender.Doc, CaseFolding.None, "html", true);
}
[TestMethod]
public void Handle_xml_processing_instruction_with_illegal_xml_namespace_50() {
Test("50.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Close_elements_with_missing_closing_tags_51() {
Test("51.test", XmlRender.Passthrough, CaseFolding.None, "html", true);
}
[TestMethod]
public void Clone_document_with_elements_with_missing_closing_tags_52() {
Test("52.test", XmlRender.DocClone, CaseFolding.None, "html", true);
}
[TestMethod]
public void Read_ofx_content_53() {
Test("53.test", XmlRender.Passthrough, CaseFolding.None, "ofx", true);
}
[TestMethod]
public void Read_simple_html_54() {
Test("54.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Decode_xml_entity_55() {
Test("55.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Decode_Surrogate_Pairs_56()
{
Test("56.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
public void Read_html_with_invalid_entity_reference_57()
{
Test("57.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Read_html_with_invalid_entity_reference_58()
{
Test("58.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Read_html_with_invalid_entity_reference_59()
{
Test("59.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Read_html_with_invalid_entity_reference_60()
{
Test("60.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Read_html_with_invalid_surrogate_pairs_61()
{
Test("61.test", XmlRender.Passthrough, CaseFolding.None, null, true);
}
[TestMethod]
public void Test_MoveToNextAttribute()
{
// Make sure we can do MoveToElement after reading multiple attributes.
var r = new SgmlReader {
InputStream = new StringReader("<test id='10' x='20'><a/><!--comment-->test</test>")
};
Assert.IsTrue(r.Read());
while(r.MoveToNextAttribute()) {
_log.Debug(r.Name);
}
if(r.MoveToElement()) {
_log.Debug(r.ReadInnerXml());
}
}
[TestMethod]
public void Test_for_illegal_char_value()
{
const string source = "&test";
var reader = new SgmlReader {
DocType = "HTML",
WhitespaceHandling = WhitespaceHandling.All,
StripDocType = true,
InputStream = new StringReader(source),
CaseFolding = CaseFolding.ToLower
};
// test
var element = System.Xml.Linq.XElement.Load(reader);
string value = element.Value;
Assert.IsFalse(string.IsNullOrEmpty(value), "element has no value");
Assert.AreNotEqual<char>((char)65535, value[value.Length - 1]);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type PlannerTasksCollectionRequest.
/// </summary>
public partial class PlannerTasksCollectionRequest : BaseRequest, IPlannerTasksCollectionRequest
{
/// <summary>
/// Constructs a new PlannerTasksCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public PlannerTasksCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified PlannerTask to the collection via POST.
/// </summary>
/// <param name="plannerTask">The PlannerTask to add.</param>
/// <returns>The created PlannerTask.</returns>
public System.Threading.Tasks.Task<PlannerTask> AddAsync(PlannerTask plannerTask)
{
return this.AddAsync(plannerTask, CancellationToken.None);
}
/// <summary>
/// Adds the specified PlannerTask to the collection via POST.
/// </summary>
/// <param name="plannerTask">The PlannerTask to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created PlannerTask.</returns>
public System.Threading.Tasks.Task<PlannerTask> AddAsync(PlannerTask plannerTask, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<PlannerTask>(plannerTask, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IPlannerTasksCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IPlannerTasksCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<PlannerTasksCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Expand(Expression<Func<PlannerTask, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Select(Expression<Func<PlannerTask, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IPlannerTasksCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// Copyright 2006 Herre Kuijpers - <herre@xs4all.nl>
//
// This source file(s) may be redistributed, altered and custimized
// by any means PROVIDING the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Oranikle.Studio.Controls
{
public partial class OutlookBar : UserControl
{
/// <summary>
/// the OutlookBarButtons class contains the list of buttons
/// it manages adding and removing buttons, and updates the Outlookbar control
/// respectively. Note that this is a class, not a control!
/// </summary>
#region OutlookBarButtons list
public class OutlookBarButtons : CollectionBase
{
//protected ArrayList List;
protected OutlookBar parent;
public OutlookBar Parent
{
get { return parent; }
}
internal OutlookBarButtons(OutlookBar parent) : base()
{
this.parent = parent;
}
public OutlookBarButton this[int index]
{
get { return (OutlookBarButton)List[index]; }
}
public void Add(OutlookBarButton item)
{
if (List.Count == 0) Parent.SelectedButton = item;
List.Add(item);
item.Parent = this.Parent;
Parent.ButtonlistChanged();
}
public OutlookBarButton Add(string text, Image image)
{
OutlookBarButton b = new OutlookBarButton(this.parent);
b.Text = text;
b.Image = image;
this.Add(b);
return b;
}
public OutlookBarButton Add(string text)
{
return this.Add(text, null);
}
public OutlookBarButton Add()
{
return this.Add();
}
public void Remove(OutlookBarButton button)
{
List.Remove(button);
Parent.ButtonlistChanged();
}
public int IndexOf(object value)
{
return List.IndexOf(value);
}
#region handle CollectionBase events
protected override void OnInsertComplete(int index, object value)
{
OutlookBarButton b = (OutlookBarButton)value;
b.Parent = this.parent;
Parent.ButtonlistChanged();
base.OnInsertComplete(index, value);
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
OutlookBarButton b = (OutlookBarButton)newValue;
b.Parent = this.parent;
Parent.ButtonlistChanged();
base.OnSetComplete(index, oldValue, newValue);
}
protected override void OnClearComplete()
{
Parent.ButtonlistChanged();
base.OnClearComplete();
}
#endregion handle CollectionBase events
}
#endregion OutlookBarButtons list
#region OutlookBar property definitions
/// <summary>
/// buttons contains the list of clickable OutlookBarButtons
/// </summary>
protected OutlookBarButtons buttons;
/// <summary>
/// this variable remembers which button is currently selected
/// </summary>
protected OutlookBarButton selectedButton = null;
/// <summary>
/// this variable remembers the button index over which the mouse is moving
/// </summary>
protected int hoveringButtonIndex = -1;
/// <summary>
/// property to set the buttonHeigt
/// default is 30
/// </summary>
protected int buttonHeight;
[Description("Specifies the height of each button on the OutlookBar"), Category("Layout")]
public int ButtonHeight
{
get { return buttonHeight; }
set {
if (value > 18)
buttonHeight = value;
else
buttonHeight = 18;
}
}
protected Color gradientButtonDark = Color.FromArgb(178, 193, 140);
[Description("Dark gradient color of the button"), Category("Appearance")]
public Color GradientButtonNormalDark
{
get { return gradientButtonDark; }
set { gradientButtonDark = value; }
}
protected Color gradientButtonLight = Color.FromArgb(234, 240, 207);
[Description("Light gradient color of the button"), Category("Appearance")]
public Color GradientButtonNormalLight
{
get { return gradientButtonLight; }
set { gradientButtonLight = value; }
}
protected Color gradientButtonHoverDark = Color.FromArgb(247, 192, 91);
[Description("Dark gradient color of the button when the mouse is moving over it"), Category("Appearance")]
public Color GradientButtonHoverDark
{
get { return gradientButtonHoverDark; }
set { gradientButtonHoverDark = value; }
}
protected Color gradientButtonHoverLight = Color.FromArgb(255, 255, 220);
[Description("Light gradient color of the button when the mouse is moving over it"), Category("Appearance")]
public Color GradientButtonHoverLight
{
get { return gradientButtonHoverLight; }
set { gradientButtonHoverLight = value; }
}
protected Color gradientButtonSelectedDark = Color.FromArgb(239, 150, 21);
[Description("Dark gradient color of the seleced button"), Category("Appearance")]
public Color GradientButtonSelectedDark
{
get { return gradientButtonSelectedDark; }
set { gradientButtonSelectedDark = value; }
}
protected Color gradientButtonSelectedLight = Color.FromArgb(251, 230, 148);
[Description("Light gradient color of the seleced button"), Category("Appearance")]
public Color GradientButtonSelectedLight
{
get { return gradientButtonSelectedLight; }
set { gradientButtonSelectedLight = value; }
}
/// <summary>
/// when a button is selected programatically, it must update the control
/// and repaint the buttons
/// </summary>
[Browsable(false)]
public OutlookBarButton SelectedButton
{
get { return selectedButton; }
set {
// assign new selected button
PaintSelectedButton(selectedButton, value);
// assign new selected button
selectedButton = value;
}
}
/// <summary>
/// readonly list of buttons
/// </summary>
//[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public OutlookBarButtons Buttons
{
get { return buttons; }
}
#endregion OutlookBar property definitions
#region OutlookBar events
[Serializable]
public class ButtonClickEventArgs : MouseEventArgs
{
public ButtonClickEventArgs(OutlookBarButton button, MouseEventArgs evt) : base(evt.Button, evt.Clicks, evt.X, evt.Y, evt.Delta)
{
SelectedButton = button;
}
public readonly OutlookBarButton SelectedButton;
}
public delegate void ButtonClickEventHandler(object sender, ButtonClickEventArgs e);
public new event ButtonClickEventHandler Click;
#endregion OutlookBar events
#region OutlookBar functions
public OutlookBar()
{
InitializeComponent();
buttons = new OutlookBarButtons(this);
buttonHeight = 30; // set default to 30
}
private void PaintSelectedButton(OutlookBarButton prevButton,OutlookBarButton newButton)
{
if (prevButton == newButton)
return; // no change so return immediately
int selIdx = -1;
int valIdx = -1;
// find the indexes of the previous and new button
selIdx = buttons.IndexOf(prevButton);
valIdx = buttons.IndexOf(newButton);
// now reset selected button
// mouse is leaving control, so unhighlight anythign that is highlighted
Graphics g = Graphics.FromHwnd(this.Handle);
if (selIdx >= 0)
// un-highlight current hovering button
buttons[selIdx].PaintButton(g, 1, selIdx * (buttonHeight + 1) + 1, false, false);
if (valIdx >= 0)
// highlight newly selected button
buttons[valIdx].PaintButton(g, 1, valIdx * (buttonHeight + 1) + 1, true, false);
g.Dispose();
}
/// <summary>
/// returns the button given the coordinates relative to the Outlookbar control
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public OutlookBarButton HitTest(int x, int y)
{
int index = (y - 1) / (buttonHeight + 1);
if (index >= 0 && index < buttons.Count)
return buttons[index];
else
return null;
}
/// <summary>
/// this function will setup the control to cope with changes in the buttonlist
/// that is, addition and removal of buttons
/// </summary>
private void ButtonlistChanged()
{
if (!this.DesignMode) // only set sizes automatically at runtime
this.MaximumSize = new Size(0, buttons.Count * (buttonHeight + 1) + 1);
this.Invalidate();
}
#endregion OutlookBar functions
#region OutlookBar control event handlers
private void OutlookBar_Load(object sender, EventArgs e)
{
// initiate the render style flags of the control
SetStyle(
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.DoubleBuffer |
ControlStyles.Selectable |
ControlStyles.UserMouse,
true
);
}
private void OutlookBar_Paint(object sender, PaintEventArgs e)
{
int top = 1;
foreach (OutlookBarButton b in Buttons)
{
b.PaintButton(e.Graphics, 1, top, b.Equals(this.selectedButton), false);
top += b.Height+1;
}
}
private void OutlookBar_Click(object sender, EventArgs e)
{
if (!(e is MouseEventArgs)) return;
// case to MouseEventArgs so position and mousebutton clicked can be used
MouseEventArgs mea = (MouseEventArgs) e;
// only continue if left mouse button was clicked
if (mea.Button != MouseButtons.Left) return;
int index = (mea.Y - 1) / (buttonHeight + 1);
if (index < 0 || index >= buttons.Count)
return;
OutlookBarButton button = buttons[index];
if (button == null) return;
if (!button.Enabled) return;
// ok, all checks passed so assign the new selected button
// and raise the event
SelectedButton = button;
ButtonClickEventArgs bce = new ButtonClickEventArgs(selectedButton, mea);
if (Click != null) // only invoke on left mouse click
Click.Invoke(this, bce);
}
private void OutlookBar_DoubleClick(object sender, EventArgs e)
{
//TODO: only if you intend to support a doubleclick
// this can be implemented exactly like the click event
}
private void OutlookBar_MouseLeave(object sender, EventArgs e)
{
// mouse is leaving control, so unhighlight anything that is highlighted
if (hoveringButtonIndex >= 0)
{
// so we need to change the hoveringButtonIndex to the new index
Graphics g = Graphics.FromHwnd(this.Handle);
OutlookBarButton b1 = buttons[hoveringButtonIndex];
// un-highlight current hovering button
b1.PaintButton(g, 1, hoveringButtonIndex * (buttonHeight + 1) + 1, b1.Equals(selectedButton), false);
hoveringButtonIndex = -1;
g.Dispose();
}
}
private void OutlookBar_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.None)
{
// determine over which button the mouse is moving
int index = (e.Location.Y - 1) / (buttonHeight + 1);
if (index >= 0 && index < buttons.Count)
{
if (hoveringButtonIndex == index )
return; // nothing changed so we're done, current button stays highlighted
// so we need to change the hoveringButtonIndex to the new index
Graphics g = Graphics.FromHwnd(this.Handle);
if (hoveringButtonIndex >= 0)
{
OutlookBarButton b1 = buttons[hoveringButtonIndex];
// un-highlight current hovering button
b1.PaintButton(g, 1, hoveringButtonIndex * (buttonHeight + 1) + 1, b1.Equals(selectedButton), false);
}
// highlight new hovering button
OutlookBarButton b2 = buttons[index];
b2.PaintButton(g, 1, index * (buttonHeight + 1) + 1, b2.Equals(selectedButton), true);
hoveringButtonIndex = index; // set to new index
g.Dispose();
}
else
{
// no hovering button, so un-highlight all.
if (hoveringButtonIndex >= 0)
{
// so we need to change the hoveringButtonIndex to the new index
Graphics g = Graphics.FromHwnd(this.Handle);
OutlookBarButton b1 = buttons[hoveringButtonIndex];
// un-highlight current hovering button
b1.PaintButton(g, 1, hoveringButtonIndex * (buttonHeight + 1) + 1, b1.Equals(selectedButton), false);
hoveringButtonIndex = -1;
g.Dispose();
}
}
}
}
/// <summary>
/// isResizing is used as a signal, so this method is not called recusively
/// this prevents a stack overflow
/// </summary>
private bool isResizing = false;
private void OutlookBar_Resize(object sender, EventArgs e)
{
// only set sizes automatically at runtime
if (!this.DesignMode)
{
if (!isResizing)
{
isResizing = true;
if ((this.Height - 1) % (buttonHeight + 1) > 0)
this.Height = ((this.Height - 1) / (buttonHeight + 1)) * (buttonHeight + 1) + 1;
this.Invalidate();
isResizing = false;
}
}
}
#endregion OutlookBar control event handlers
}
/// <summary>
/// OutlookbarButton represents a button on the Outlookbar
/// this is an internally used class (not a control!)
/// </summary>
#region OutlookBarButton
public class OutlookBarButton // : IComponent
{
private bool enabled = true;
private bool visible = true;
[Description("Indicates wether the button is enabled"), Category("Behavior")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool Enabled
{
get { return enabled; }
set { enabled = value; }
}
[Description("Indicates wether the button is enabled"), Category("Behavior")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public bool Visible
{
get { return visible; }
set { visible = value; }
}
protected Image image = null;
[Description("The image that will be displayed on the button"), Category("Data")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public Image Image
{
get { return image; }
set
{
image = value;
parent.Invalidate();
}
}
protected object tag = null;
[Description("User-defined data to be associated with the button"), Category("Appearance")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public object Tag
{
get { return tag; }
set { tag = value; }
}
public OutlookBarButton()
{
this.parent = new OutlookBar(); // set it to a dummy outlookbar control
text = "";
}
public OutlookBarButton(OutlookBar parent)
{
this.parent = parent;
text = "";
}
protected OutlookBar parent;
internal OutlookBar Parent
{
get { return parent; }
set { parent = value; }
}
protected string text;
[Description("The text that will be displayed on the button"), Category("Appearance")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string Text
{
get { return text; }
set
{
text = value;
parent.Invalidate();
}
}
protected int height;
public int Height
{
get { return parent == null ? 30 : parent.ButtonHeight; }
}
public int Width
{
get { return parent == null ? 60 : parent.Width - 2; }
}
/// <summary>
/// the outlook button will paint itself on its container (the OutlookBar)
/// </summary>
/// <param name="graphics"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="IsSelected"></param>
/// <param name="IsHovering"></param>
public void PaintButton(Graphics graphics, int x, int y, bool IsSelected, bool IsHovering)
{
Brush br;
Rectangle rect = new Rectangle(0, y, this.Width, this.Height);
if (!visible)
{
//return;
//rect = Rectangle.Empty;
}
if (enabled)
{
if (IsSelected)
if (IsHovering)
br = new LinearGradientBrush(rect, parent.GradientButtonSelectedDark, parent.GradientButtonSelectedLight, 90f);
else
br = new LinearGradientBrush(rect, parent.GradientButtonSelectedLight, parent.GradientButtonSelectedDark, 90f);
else
if (IsHovering)
br = new LinearGradientBrush(rect, parent.GradientButtonHoverLight, parent.GradientButtonHoverDark, 90f);
else
br = new LinearGradientBrush(rect, parent.GradientButtonNormalLight, parent.GradientButtonNormalDark, 90f);
}
else
br = new LinearGradientBrush(rect, parent.GradientButtonNormalLight, parent.GradientButtonNormalDark, 90f);
graphics.FillRectangle(br, x, y, this.Width, this.Height);
br.Dispose();
string text = visible ? this.Text : string.Empty;
if (text.Length > 0)
graphics.DrawString(this.Text, parent.Font, Brushes.Black, 36, y + this.Height / 2 - parent.Font.Height / 2);
if (image != null)
{
graphics.DrawImage(image, 36 / 2 - image.Width / 2, y + this.Height / 2 - image.Height / 2, image.Width, image.Height);
}
}
}
#endregion
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the LabAccesoResultado class.
/// </summary>
[Serializable]
public partial class LabAccesoResultadoCollection : ActiveList<LabAccesoResultado, LabAccesoResultadoCollection>
{
public LabAccesoResultadoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>LabAccesoResultadoCollection</returns>
public LabAccesoResultadoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
LabAccesoResultado o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the LAB_AccesoResultado table.
/// </summary>
[Serializable]
public partial class LabAccesoResultado : ActiveRecord<LabAccesoResultado>, IActiveRecord
{
#region .ctors and Default Settings
public LabAccesoResultado()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public LabAccesoResultado(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public LabAccesoResultado(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public LabAccesoResultado(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("LAB_AccesoResultado", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdAccesoResultado = new TableSchema.TableColumn(schema);
colvarIdAccesoResultado.ColumnName = "idAccesoResultado";
colvarIdAccesoResultado.DataType = DbType.Int32;
colvarIdAccesoResultado.MaxLength = 0;
colvarIdAccesoResultado.AutoIncrement = true;
colvarIdAccesoResultado.IsNullable = false;
colvarIdAccesoResultado.IsPrimaryKey = true;
colvarIdAccesoResultado.IsForeignKey = false;
colvarIdAccesoResultado.IsReadOnly = false;
colvarIdAccesoResultado.DefaultSetting = @"";
colvarIdAccesoResultado.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdAccesoResultado);
TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema);
colvarIdUsuario.ColumnName = "idUsuario";
colvarIdUsuario.DataType = DbType.Int32;
colvarIdUsuario.MaxLength = 0;
colvarIdUsuario.AutoIncrement = false;
colvarIdUsuario.IsNullable = false;
colvarIdUsuario.IsPrimaryKey = false;
colvarIdUsuario.IsForeignKey = false;
colvarIdUsuario.IsReadOnly = false;
colvarIdUsuario.DefaultSetting = @"";
colvarIdUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdUsuario);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = false;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarNumeroDocumento = new TableSchema.TableColumn(schema);
colvarNumeroDocumento.ColumnName = "numeroDocumento";
colvarNumeroDocumento.DataType = DbType.Int32;
colvarNumeroDocumento.MaxLength = 0;
colvarNumeroDocumento.AutoIncrement = false;
colvarNumeroDocumento.IsNullable = false;
colvarNumeroDocumento.IsPrimaryKey = false;
colvarNumeroDocumento.IsForeignKey = false;
colvarNumeroDocumento.IsReadOnly = false;
colvarNumeroDocumento.DefaultSetting = @"";
colvarNumeroDocumento.ForeignKeyTableName = "";
schema.Columns.Add(colvarNumeroDocumento);
TableSchema.TableColumn colvarNumeroProtocolo = new TableSchema.TableColumn(schema);
colvarNumeroProtocolo.ColumnName = "numeroProtocolo";
colvarNumeroProtocolo.DataType = DbType.AnsiString;
colvarNumeroProtocolo.MaxLength = 50;
colvarNumeroProtocolo.AutoIncrement = false;
colvarNumeroProtocolo.IsNullable = false;
colvarNumeroProtocolo.IsPrimaryKey = false;
colvarNumeroProtocolo.IsForeignKey = false;
colvarNumeroProtocolo.IsReadOnly = false;
colvarNumeroProtocolo.DefaultSetting = @"";
colvarNumeroProtocolo.ForeignKeyTableName = "";
schema.Columns.Add(colvarNumeroProtocolo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("LAB_AccesoResultado",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdAccesoResultado")]
[Bindable(true)]
public int IdAccesoResultado
{
get { return GetColumnValue<int>(Columns.IdAccesoResultado); }
set { SetColumnValue(Columns.IdAccesoResultado, value); }
}
[XmlAttribute("IdUsuario")]
[Bindable(true)]
public int IdUsuario
{
get { return GetColumnValue<int>(Columns.IdUsuario); }
set { SetColumnValue(Columns.IdUsuario, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime Fecha
{
get { return GetColumnValue<DateTime>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("NumeroDocumento")]
[Bindable(true)]
public int NumeroDocumento
{
get { return GetColumnValue<int>(Columns.NumeroDocumento); }
set { SetColumnValue(Columns.NumeroDocumento, value); }
}
[XmlAttribute("NumeroProtocolo")]
[Bindable(true)]
public string NumeroProtocolo
{
get { return GetColumnValue<string>(Columns.NumeroProtocolo); }
set { SetColumnValue(Columns.NumeroProtocolo, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdUsuario,DateTime varFecha,int varNumeroDocumento,string varNumeroProtocolo)
{
LabAccesoResultado item = new LabAccesoResultado();
item.IdUsuario = varIdUsuario;
item.Fecha = varFecha;
item.NumeroDocumento = varNumeroDocumento;
item.NumeroProtocolo = varNumeroProtocolo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdAccesoResultado,int varIdUsuario,DateTime varFecha,int varNumeroDocumento,string varNumeroProtocolo)
{
LabAccesoResultado item = new LabAccesoResultado();
item.IdAccesoResultado = varIdAccesoResultado;
item.IdUsuario = varIdUsuario;
item.Fecha = varFecha;
item.NumeroDocumento = varNumeroDocumento;
item.NumeroProtocolo = varNumeroProtocolo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdAccesoResultadoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdUsuarioColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn NumeroDocumentoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn NumeroProtocoloColumn
{
get { return Schema.Columns[4]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdAccesoResultado = @"idAccesoResultado";
public static string IdUsuario = @"idUsuario";
public static string Fecha = @"fecha";
public static string NumeroDocumento = @"numeroDocumento";
public static string NumeroProtocolo = @"numeroProtocolo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ModestTree
{
public static class TypeExtensions
{
public static bool DerivesFrom<T>(this Type a)
{
return DerivesFrom(a, typeof(T));
}
// This seems easier to think about than IsAssignableFrom
public static bool DerivesFrom(this Type a, Type b)
{
return b != a && b.IsAssignableFrom(a);
}
public static bool DerivesFromOrEqual<T>(this Type a)
{
return DerivesFromOrEqual(a, typeof(T));
}
public static bool DerivesFromOrEqual(this Type a, Type b)
{
return b == a || b.IsAssignableFrom(a);
}
public static object GetDefaultValue(this Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
// Returns name without generic arguments
public static string GetSimpleName(this Type type)
{
var name = type.Name;
var quoteIndex = name.IndexOf("`");
if (quoteIndex == -1)
{
return name;
}
// Remove the backtick
return name.Substring(0, quoteIndex);
}
public static IEnumerable<Type> GetParentTypes(this Type type)
{
if (type == null || type.BaseType == null || type == typeof(object) || type.BaseType == typeof(object))
{
yield break;
}
yield return type.BaseType;
foreach (var ancestor in type.BaseType.GetParentTypes())
{
yield return ancestor;
}
}
public static string NameWithParents(this Type type)
{
var typeList = type.GetParentTypes().Prepend(type).Select(x => x.Name()).ToArray();
return string.Join(":", typeList);
}
public static bool IsClosedGenericType(this Type type)
{
return type.IsGenericType && type != type.GetGenericTypeDefinition();
}
public static bool IsOpenGenericType(this Type type)
{
return type.IsGenericType && type == type.GetGenericTypeDefinition();
}
// This is the same as the standard GetFields except it also supports getting the private
// fields in base classes
public static IEnumerable<FieldInfo> GetAllFields(this Type type, BindingFlags flags)
{
if ((int)(flags & BindingFlags.DeclaredOnly) != 0)
{
// Can use normal method in this case
foreach (var fieldInfo in type.GetFields(flags))
{
yield return fieldInfo;
}
}
else
{
// Add DeclaredOnly because we will get the base classes below
foreach (var fieldInfo in type.GetFields(flags | BindingFlags.DeclaredOnly))
{
yield return fieldInfo;
}
if (type.BaseType != null && type.BaseType != typeof(object))
{
foreach (var fieldInfo in type.BaseType.GetAllFields(flags))
{
yield return fieldInfo;
}
}
}
}
// This is the same as the standard GetProperties except it also supports getting the private
// members in base classes
public static IEnumerable<PropertyInfo> GetAllProperties(this Type type, BindingFlags flags)
{
if ((int)(flags & BindingFlags.DeclaredOnly) != 0)
{
// Can use normal method in this case
foreach (var propertyInfo in type.GetProperties(flags))
{
yield return propertyInfo;
}
}
else
{
// Add DeclaredOnly because we will get the base classes below
foreach (var propertyInfo in type.GetProperties(flags | BindingFlags.DeclaredOnly))
{
yield return propertyInfo;
}
if (type.BaseType != null && type.BaseType != typeof(object))
{
foreach (var propertyInfo in type.BaseType.GetAllProperties(flags))
{
yield return propertyInfo;
}
}
}
}
// This is the same as the standard GetMethods except it also supports getting the private
// members in base classes
public static IEnumerable<MethodInfo> GetAllMethods(this Type type, BindingFlags flags)
{
if ((int)(flags & BindingFlags.DeclaredOnly) != 0)
{
// Can use normal method in this case
foreach (var methodInfo in type.GetMethods(flags))
{
yield return methodInfo;
}
}
else
{
// Add DeclaredOnly because we will get the base classes below
foreach (var methodInfo in type.GetMethods(flags | BindingFlags.DeclaredOnly))
{
yield return methodInfo;
}
if (type.BaseType != null && type.BaseType != typeof(object))
{
foreach (var methodInfo in type.BaseType.GetAllMethods(flags))
{
yield return methodInfo;
}
}
}
}
public static string Name(this Type type)
{
if (type.IsArray)
{
return string.Format("{0}[]", type.GetElementType().Name());
}
if (type.ContainsGenericParameters || type.IsGenericType)
{
if (type.BaseType == typeof(Nullable<>) || (type.BaseType == typeof(ValueType) && type.UnderlyingSystemType.Name.StartsWith("Nullable")))
{
return GetCSharpTypeName(type.GetGenericArguments().Single().Name) + "?";
}
int index = type.Name.IndexOf("`");
string genericTypeName = index > 0 ? type.Name.Substring(0, index) : type.Name;
string genericArgs = string.Join(",", type.GetGenericArguments().Select(t => t.Name()).ToArray());
return genericArgs.Length == 0 ? genericTypeName : genericTypeName + "<" + genericArgs + ">";
}
// If a nested class, include the parent classes as well
return (type.DeclaringType == null ? "" : type.DeclaringType.Name() + ".") + GetCSharpTypeName(type.Name);
}
static string GetCSharpTypeName(string typeName)
{
switch (typeName)
{
case "String":
case "Object":
case "Void":
case "Byte":
case "Double":
case "Decimal":
return typeName.ToLower();
case "Int16":
return "short";
case "Int32":
return "int";
case "Int64":
return "long";
case "Single":
return "float";
case "Boolean":
return "bool";
default:
return typeName;
}
}
public static bool HasAttribute(
this ICustomAttributeProvider provider, params Type[] attributeTypes)
{
return provider.AllAttributes(attributeTypes).Any();
}
public static bool HasAttribute<T>(this ICustomAttributeProvider provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Any();
}
public static IEnumerable<T> AllAttributes<T>(
this ICustomAttributeProvider provider)
where T : Attribute
{
return provider.AllAttributes(typeof(T)).Cast<T>();
}
public static IEnumerable<Attribute> AllAttributes(
this ICustomAttributeProvider provider, params Type[] attributeTypes)
{
var allAttributes = provider.GetCustomAttributes(true).Cast<Attribute>();
if (attributeTypes.Length == 0)
{
return allAttributes;
}
return allAttributes.Where(a => attributeTypes.Contains(a.GetType()));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
/// <summary>
/// Implementations of EnvDTE.FileCodeModel for both languages.
/// </summary>
public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring
{
internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create(
CodeModelState state,
object parent,
DocumentId documentId,
ITextManagerAdapter textManagerAdapter)
{
return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>();
}
private readonly ComHandle<object, object> _parentHandle;
/// <summary>
/// Don't use directly. Instead, call <see cref="GetDocumentId()"/>.
/// </summary>
private DocumentId _documentId;
// Note: these are only valid when the underlying file is being renamed. Do not use.
private ProjectId _incomingProjectId;
private string _incomingFilePath;
private Document _previousDocument;
private readonly ITextManagerAdapter _textManagerAdapter;
private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable;
// These are used during batching.
private bool _batchMode;
private List<AbstractKeyedCodeElement> _batchElements;
private Document _batchDocument;
// track state to make sure we open editor only once
private int _editCount;
private IInvisibleEditor _invisibleEditor;
private SyntaxTree _lastSyntaxTree;
private FileCodeModel(
CodeModelState state,
object parent,
DocumentId documentId,
ITextManagerAdapter textManagerAdapter)
: base(state)
{
Debug.Assert(documentId != null);
Debug.Assert(textManagerAdapter != null);
_parentHandle = new ComHandle<object, object>(parent);
_documentId = documentId;
_textManagerAdapter = textManagerAdapter;
_codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>();
_batchMode = false;
_batchDocument = null;
_lastSyntaxTree = GetSyntaxTree();
}
internal ITextManagerAdapter TextManagerAdapter
{
get { return _textManagerAdapter; }
}
/// <summary>
/// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file
/// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair.
/// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the
/// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file.
/// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace
/// using the <see cref="_incomingFilePath"/>.
/// </summary>
internal void OnRename(string newFilePath)
{
Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug.");
if (_documentId != null)
{
_previousDocument = Workspace.CurrentSolution.GetDocument(_documentId);
}
_incomingFilePath = newFilePath;
_incomingProjectId = _documentId.ProjectId;
_documentId = null;
}
internal override void Shutdown()
{
if (_invisibleEditor != null)
{
// we are shutting down, so do not worry about editCount. If the editor is still alive, dispose it.
CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
_invisibleEditor.Dispose();
_invisibleEditor = null;
}
base.Shutdown();
}
private bool TryGetDocumentId(out DocumentId documentId)
{
if (_documentId != null)
{
documentId = _documentId;
return true;
}
documentId = null;
// We don't have DocumentId, so try to retrieve it from the workspace.
if (_incomingProjectId == null || _incomingFilePath == null)
{
return false;
}
var project = ((VisualStudioWorkspaceImpl)this.State.Workspace).ProjectTracker.GetProject(_incomingProjectId);
if (project == null)
{
return false;
}
var hostDocument = project.GetCurrentDocumentFromPath(_incomingFilePath);
if (hostDocument == null)
{
return false;
}
_documentId = hostDocument.Id;
_incomingProjectId = null;
_incomingFilePath = null;
_previousDocument = null;
documentId = _documentId;
return true;
}
internal DocumentId GetDocumentId()
{
if (_documentId != null)
{
return _documentId;
}
DocumentId documentId;
if (TryGetDocumentId(out documentId))
{
return documentId;
}
throw Exceptions.ThrowEUnexpected();
}
internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey)
{
EnvDTE.CodeElement codeElement;
if (!_codeElementTable.TryGetValue(oldNodeKey, out codeElement))
{
throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table.");
}
_codeElementTable.Remove(oldNodeKey);
var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement);
if (!object.Equals(managedElement, keyedElement))
{
throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}");
}
_codeElementTable.Add(newNodeKey, codeElement);
}
internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element)
{
_codeElementTable.Add(nodeKey, element);
}
internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey)
{
_codeElementTable.Remove(nodeKey);
}
internal T GetOrCreateCodeElement<T>(SyntaxNode node)
{
var nodeKey = CodeModelService.TryGetNodeKey(node);
if (!nodeKey.IsEmpty)
{
// Since the node already has a key, check to see if a code element already
// exists for it. If so, return that element it it's still valid; otherwise,
// remove it from the table.
EnvDTE.CodeElement codeElement;
if (_codeElementTable.TryGetValue(nodeKey, out codeElement))
{
if (codeElement != null)
{
var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement);
if (element.IsValidNode())
{
if (codeElement is T)
{
return (T)codeElement;
}
throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}");
}
}
}
// Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one.
_codeElementTable.Remove(nodeKey);
}
return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node);
}
private void InitializeEditor()
{
_editCount++;
if (_editCount == 1)
{
Debug.Assert(_invisibleEditor == null);
_invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId());
CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
}
}
private void ReleaseEditor()
{
Debug.Assert(_editCount >= 1);
_editCount--;
if (_editCount == 0)
{
Debug.Assert(_invisibleEditor != null);
CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer);
_invisibleEditor.Dispose();
_invisibleEditor = null;
}
}
internal void EnsureEditor(Action action)
{
InitializeEditor();
try
{
action();
}
finally
{
ReleaseEditor();
}
}
internal T EnsureEditor<T>(Func<T> action)
{
InitializeEditor();
try
{
return action();
}
finally
{
ReleaseEditor();
}
}
internal void PerformEdit(Func<Document, Document> action)
{
EnsureEditor(() =>
{
Debug.Assert(_invisibleEditor != null);
var document = GetDocument();
var workspace = document.Project.Solution.Workspace;
var result = action(document);
var formatted = Formatter.FormatAsync(result, Formatter.Annotation).WaitAndGetResult(CancellationToken.None);
formatted = Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).WaitAndGetResult(CancellationToken.None);
ApplyChanges(workspace, formatted);
});
}
internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode
{
return EnsureEditor(() =>
{
Debug.Assert(_invisibleEditor != null);
var document = GetDocument();
var workspace = document.Project.Solution.Workspace;
var result = action(document);
ApplyChanges(workspace, result.Item2);
return result.Item1;
});
}
private void ApplyChanges(Workspace workspace, Document document)
{
if (IsBatchOpen)
{
_batchDocument = document;
}
else
{
workspace.TryApplyChanges(document.Project.Solution);
}
}
internal Document GetDocument()
{
Document document;
if (!TryGetDocument(out document))
{
throw Exceptions.ThrowEFail();
}
return document;
}
internal bool TryGetDocument(out Document document)
{
if (IsBatchOpen && _batchDocument != null)
{
document = _batchDocument;
return true;
}
DocumentId documentId;
if (!TryGetDocumentId(out documentId) && _previousDocument != null)
{
document = _previousDocument;
}
else
{
document = Workspace.CurrentSolution.GetDocument(GetDocumentId());
}
return document != null;
}
internal SyntaxTree GetSyntaxTree()
{
return GetDocument()
.GetSyntaxTreeAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
}
internal SyntaxNode GetSyntaxRoot()
{
return GetDocument()
.GetSyntaxRootAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
}
internal SemanticModel GetSemanticModel()
{
return GetDocument()
.GetSemanticModelAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
}
internal Compilation GetCompilation()
{
return GetDocument().Project
.GetCompilationAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
}
internal ProjectId GetProjectId()
{
return GetDocumentId().ProjectId;
}
internal AbstractProject GetAbstractProject()
{
return ((VisualStudioWorkspaceImpl)Workspace).ProjectTracker.GetProject(GetProjectId());
}
internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey)
{
return CodeModelService.LookupNode(nodeKey, GetSyntaxTree());
}
internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey)
where TSyntaxNode : SyntaxNode
{
return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode;
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
return EnsureEditor(() =>
{
return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString);
});
}
public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access);
});
}
public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddDelegate(GetSyntaxRoot(), name, type, position, access);
});
}
public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddEnum(GetSyntaxRoot(), name, position, bases, access);
});
}
public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access)
{
throw Exceptions.ThrowEFail();
}
public EnvDTE80.CodeImport AddImport(string name, object position, string alias)
{
return EnsureEditor(() =>
{
return AddImport(GetSyntaxRoot(), name, position, alias);
});
}
public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddInterface(GetSyntaxRoot(), name, position, bases, access);
});
}
public EnvDTE.CodeNamespace AddNamespace(string name, object position)
{
return EnsureEditor(() =>
{
return AddNamespace(GetSyntaxRoot(), name, position);
});
}
public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access)
{
return EnsureEditor(() =>
{
return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access);
});
}
public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access)
{
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope)
{
// Can't use point.AbsoluteCharOffset because it's calculated by the native
// implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp)
// to only count each newline as a single character. We need to ask for line and
// column and calculate the right offset ourselves. See DevDiv2 530496 for details.
var position = GetPositionFromTextPoint(point);
var result = CodeElementFromPosition(position, scope);
if (result == null)
{
throw Exceptions.ThrowEFail();
}
return result;
}
private int GetPositionFromTextPoint(EnvDTE.TextPoint point)
{
var lineNumber = point.Line - 1;
var column = point.LineCharOffset - 1;
var line = GetDocument().GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None).Lines[lineNumber];
var position = line.Start + column;
return position;
}
internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope)
{
var root = GetSyntaxRoot();
var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position);
var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position);
// We apply a set of heuristics to determine which member we pick to start searching.
var token = leftToken;
if (leftToken != rightToken)
{
if (leftToken.Span.End == position && rightToken.SpanStart == position)
{
// If both tokens are touching, we prefer identifiers and keywords to
// separators. Note that the language doesn't allow both tokens to be a
// keyword or identifier.
if (SyntaxFactsService.IsKeyword(rightToken) ||
SyntaxFactsService.IsIdentifier(rightToken))
{
token = rightToken;
}
}
else if (leftToken.Span.End < position && rightToken.SpanStart <= position)
{
// If only the right token is touching, we have to use it.
token = rightToken;
}
}
// If we ended up using the left token but the position is after that token,
// walk up to the first node who's last token is not the leftToken. By doing this, we
// ensure that we don't find members when the position is actually between them.
// In that case, we should find the enclosing type or namespace.
var parent = token.Parent;
if (token == leftToken && position > token.Span.End)
{
while (parent != null)
{
if (parent.GetLastToken() == token)
{
parent = parent.Parent;
}
else
{
break;
}
}
}
var node = parent != null
? parent.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope))
: null;
if (node == null)
{
return null;
}
if (scope == EnvDTE.vsCMElement.vsCMElementAttribute ||
scope == EnvDTE.vsCMElement.vsCMElementImportStmt ||
scope == EnvDTE.vsCMElement.vsCMElementParameter ||
scope == EnvDTE.vsCMElement.vsCMElementOptionStmt ||
scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt ||
scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt ||
(scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node)))
{
// Attributes, imports, parameters, Option, Inherits and Implements
// don't have node keys of their own and won't be included in our
// collection of elements. Delegate to the service to create these.
return CodeModelService.CreateInternalCodeElement(State, this, node);
}
return GetOrCreateCodeElement<EnvDTE.CodeElement>(node);
}
public EnvDTE.CodeElements CodeElements
{
get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); }
}
public EnvDTE.ProjectItem Parent
{
get { return _parentHandle.Object as EnvDTE.ProjectItem; }
}
public void Remove(object element)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element);
if (codeElement == null)
{
codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element));
}
if (codeElement == null)
{
throw new ArgumentException(ServicesVSResources.ElementIsNotValid, nameof(element));
}
codeElement.Delete();
}
int IVBFileCodeModelEvents.StartEdit()
{
try
{
InitializeEditor();
if (_editCount == 1)
{
_batchMode = true;
_batchElements = new List<AbstractKeyedCodeElement>();
}
return VSConstants.S_OK;
}
catch (Exception ex)
{
return Marshal.GetHRForException(ex);
}
}
int IVBFileCodeModelEvents.EndEdit()
{
try
{
if (_editCount == 1)
{
List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null;
if (_batchElements.Count > 0)
{
foreach (var element in _batchElements)
{
var node = element.LookupNode();
if (node != null)
{
elementAndPaths = elementAndPaths ?? new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>();
elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node)));
}
}
}
if (_batchDocument != null)
{
// perform expensive operations at once
var newDocument = Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None);
_batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution);
// done using batch document
_batchDocument = null;
}
// Ensure the file is prettylisted, even if we didn't make any edits
CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer);
if (elementAndPaths != null)
{
foreach (var elementAndPath in elementAndPaths)
{
// make sure the element is there.
EnvDTE.CodeElement existingElement;
if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out existingElement))
{
elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None);
}
// make sure existing element doesn't go away (weak reference) in the middle of
// updating the node key
GC.KeepAlive(existingElement);
}
}
_batchMode = false;
_batchElements = null;
}
return VSConstants.S_OK;
}
catch (Exception ex)
{
return Marshal.GetHRForException(ex);
}
finally
{
ReleaseEditor();
}
}
public void BeginBatch()
{
IVBFileCodeModelEvents temp = this;
ErrorHandler.ThrowOnFailure(temp.StartEdit());
}
public void EndBatch()
{
IVBFileCodeModelEvents temp = this;
ErrorHandler.ThrowOnFailure(temp.EndEdit());
}
public bool IsBatchOpen
{
get
{
return _batchMode && _editCount > 0;
}
}
public EnvDTE.CodeElement ElementFromID(string id)
{
throw new NotImplementedException();
}
public EnvDTE80.vsCMParseStatus ParseStatus
{
get
{
var syntaxTree = GetSyntaxTree();
return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)
? EnvDTE80.vsCMParseStatus.vsCMParseStatusError
: EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete;
}
}
public void Synchronize()
{
FireEvents();
}
EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection()
{
return CodeElements;
}
internal List<GlobalNodeKey> GetCurrentNodeKeys()
{
var currentNodeKeys = new List<GlobalNodeKey>();
foreach (var element in _codeElementTable.Values)
{
var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element);
if (keyedElement == null)
{
continue;
}
SyntaxNode node;
if (keyedElement.TryLookupNode(out node))
{
var nodeKey = keyedElement.NodeKey;
currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node)));
}
}
return currentNodeKeys;
}
internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys)
{
foreach (var globalNodeKey in globalNodeKeys)
{
ResetElementKey(globalNodeKey);
}
}
private void ResetElementKey(GlobalNodeKey globalNodeKey)
{
// Failure to find the element is not an error -- it just means the code
// element didn't exist...
EnvDTE.CodeElement element;
if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out element))
{
var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element);
if (keyedElement != null)
{
keyedElement.ReacquireNodeKey(globalNodeKey.Path, default(CancellationToken));
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Security {
using System;
using System.Security.Util;
using System.Security.Permissions;
using System.Reflection;
using System.Collections;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
[Flags]
internal enum PermissionTokenType
{
Normal = 0x1,
IUnrestricted = 0x2,
DontKnow = 0x4,
BuiltIn = 0x8
}
[Serializable]
internal sealed class PermissionTokenKeyComparer : IEqualityComparer
{
private Comparer _caseSensitiveComparer;
private TextInfo _info;
public PermissionTokenKeyComparer()
{
_caseSensitiveComparer = new Comparer(CultureInfo.InvariantCulture);
_info = CultureInfo.InvariantCulture.TextInfo;
}
[System.Security.SecuritySafeCritical] // auto-generated
public int Compare(Object a, Object b)
{
String strA = a as String;
String strB = b as String;
// if it's not a string then we just call the object comparer
if (strA == null || strB == null)
return _caseSensitiveComparer.Compare(a, b);
int i = _caseSensitiveComparer.Compare(a,b);
if (i == 0)
return 0;
if (SecurityManager.IsSameType(strA, strB))
return 0;
return i;
}
public new bool Equals( Object a, Object b )
{
if (a == b) return true;
if (a == null || b == null) return false;
return Compare( a, b ) == 0;
}
// The data structure consuming this will be responsible for dealing with null objects as keys.
public int GetHashCode(Object obj)
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
Contract.EndContractBlock();
String str = obj as String;
if (str == null)
return obj.GetHashCode();
int iComma = str.IndexOf( ',' );
if (iComma == -1)
iComma = str.Length;
int accumulator = 0;
for (int i = 0; i < iComma; ++i)
{
accumulator = (accumulator << 7) ^ str[i] ^ (accumulator >> 25);
}
return accumulator;
}
}
[Serializable]
internal sealed class PermissionToken : ISecurityEncodable
{
private static readonly PermissionTokenFactory s_theTokenFactory;
#if FEATURE_CAS_POLICY
private static volatile ReflectionPermission s_reflectPerm = null;
#endif // FEATURE_CAS_POLICY
private const string c_mscorlibName = System.CoreLib.Name;
internal int m_index;
internal volatile PermissionTokenType m_type;
#if FEATURE_CAS_POLICY
internal String m_strTypeName;
#endif // FEATURE_CAS_POLICY
static internal TokenBasedSet s_tokenSet = new TokenBasedSet();
internal static bool IsMscorlibClassName (string className) {
Contract.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
System.CoreLib.Name+" name mismatch" );
// If the class name does not look like a fully qualified name, we cannot simply determine if it's
// an mscorlib.dll type so we should return true so the type can be matched with the
// right index in the TokenBasedSet.
int index = className.IndexOf(',');
if (index == -1)
return true;
index = className.LastIndexOf(']');
if (index == -1)
index = 0;
// Search for the string 'mscorlib' in the classname. If we find it, we will conservatively assume it's an mscorlib.dll type and load it.
for (int i = index; i < className.Length; i++) {
#if FEATURE_CORECLR
if (className[i] == 's' || className[i] == 'S')
#else
if (className[i] == 'm' || className[i] == 'M')
#endif
{
if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
}
return false;
}
static PermissionToken()
{
s_theTokenFactory = new PermissionTokenFactory( 4 );
}
internal PermissionToken()
{
}
internal PermissionToken(int index, PermissionTokenType type, String strTypeName)
{
m_index = index;
m_type = type;
#if FEATURE_CAS_POLICY
m_strTypeName = strTypeName;
#endif // FEATURE_CAS_POLICY
}
[System.Security.SecurityCritical] // auto-generated
public static PermissionToken GetToken(Type cls)
{
if (cls == null)
return null;
#if FEATURE_CAS_POLICY
if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null)
{
if (s_reflectPerm == null)
s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted);
s_reflectPerm.Assert();
MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic );
Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" );
// GetTokenIndex needs to be invoked without any security checks, since doing a security check
// will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the
// token.
RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo;
Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo");
int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null);
return s_theTokenFactory.BuiltInGetToken(token, null, cls);
}
else
#endif // FEATURE_CAS_POLICY
{
return s_theTokenFactory.GetToken(cls, null);
}
}
public static PermissionToken GetToken(IPermission perm)
{
if (perm == null)
return null;
IBuiltInPermission ibPerm = perm as IBuiltInPermission;
if (ibPerm != null)
return s_theTokenFactory.BuiltInGetToken( ibPerm.GetTokenIndex(), perm, null );
else
return s_theTokenFactory.GetToken(perm.GetType(), perm);
}
#if FEATURE_CAS_POLICY
public static PermissionToken GetToken(String typeStr)
{
return GetToken( typeStr, false );
}
#if _DEBUG
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static void GetTokenHelper(String typeStr)
{
new PermissionSet(PermissionState.Unrestricted).Assert();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Type type = RuntimeTypeHandle.GetTypeByName( typeStr.Trim().Replace( '\'', '\"' ), ref stackMark);
Contract.Assert( (type == null) || (type.Module.Assembly != System.Reflection.Assembly.GetExecutingAssembly()) || (typeStr.IndexOf("mscorlib", StringComparison.Ordinal) < 0),
"We should not go through this path for mscorlib based permissions" );
}
#endif
public static PermissionToken GetToken(String typeStr, bool bCreateMscorlib)
{
if (typeStr == null)
return null;
if (IsMscorlibClassName( typeStr ))
{
if (!bCreateMscorlib)
{
return null;
}
else
{
return FindToken( Type.GetType( typeStr ) );
}
}
else
{
PermissionToken token = s_theTokenFactory.GetToken(typeStr);
#if _DEBUG
GetTokenHelper(typeStr);
#endif
return token;
}
}
[SecuritySafeCritical]
public static PermissionToken FindToken( Type cls )
{
if (cls == null)
return null;
#if FEATURE_CAS_POLICY
if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null)
{
if (s_reflectPerm == null)
s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted);
s_reflectPerm.Assert();
MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic );
Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" );
// GetTokenIndex needs to be invoked without any security checks, since doing a security check
// will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the
// token.
RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo;
Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo");
int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null);
return s_theTokenFactory.BuiltInGetToken(token, null, cls);
}
else
#endif // FEATURE_CAS_POLICY
{
return s_theTokenFactory.FindToken( cls );
}
}
#endif // FEATURE_CAS_POLICY
public static PermissionToken FindTokenByIndex( int i )
{
return s_theTokenFactory.FindTokenByIndex( i );
}
public static bool IsTokenProperlyAssigned( IPermission perm, PermissionToken token )
{
PermissionToken heldToken = GetToken( perm );
if (heldToken.m_index != token.m_index)
return false;
if (token.m_type != heldToken.m_type)
return false;
if (perm.GetType().Module.Assembly == Assembly.GetExecutingAssembly() &&
heldToken.m_index >= BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED)
return false;
return true;
}
#if FEATURE_CAS_POLICY
public SecurityElement ToXml()
{
Contract.Assert( (m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when ToXml is called" );
SecurityElement elRoot = new SecurityElement( "PermissionToken" );
if ((m_type & PermissionTokenType.BuiltIn) != 0)
elRoot.AddAttribute( "Index", "" + this.m_index );
else
elRoot.AddAttribute( "Name", SecurityElement.Escape( m_strTypeName ) );
elRoot.AddAttribute("Type", m_type.ToString("F"));
return elRoot;
}
public void FromXml(SecurityElement elRoot)
{
// For the most part there is no parameter checking here since this is an
// internal class and the serialization/deserialization path is controlled.
if (!elRoot.Tag.Equals( "PermissionToken" ))
Contract.Assert( false, "Tried to deserialize non-PermissionToken element here" );
String strName = elRoot.Attribute( "Name" );
PermissionToken realToken;
if (strName != null)
realToken = GetToken( strName, true );
else
realToken = FindTokenByIndex( Int32.Parse( elRoot.Attribute( "Index" ), CultureInfo.InvariantCulture ) );
this.m_index = realToken.m_index;
this.m_type = (PermissionTokenType) Enum.Parse(typeof(PermissionTokenType), elRoot.Attribute("Type"));
Contract.Assert((this.m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when FromXml is called.");
this.m_strTypeName = realToken.m_strTypeName;
}
#endif // FEATURE_CAS_POLICY
}
// Package access only
internal class PermissionTokenFactory
{
private volatile int m_size;
private volatile int m_index;
private volatile Hashtable m_tokenTable; // Cache of tokens by class string name
private volatile Hashtable m_handleTable; // Cache of tokens by type handle (IntPtr)
private volatile Hashtable m_indexTable; // Cache of tokens by index
// We keep an array of tokens for our built-in permissions.
// This is ordered in terms of unrestricted perms first, normals
// second. Of course, all the ordering is based on the individual
// permissions sticking to the deal, so we do some simple boundary
// checking but mainly leave it to faith.
private volatile PermissionToken[] m_builtIn;
private const String s_unrestrictedPermissionInferfaceName = "System.Security.Permissions.IUnrestrictedPermission";
internal PermissionTokenFactory( int size )
{
m_builtIn = new PermissionToken[BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED];
m_size = size;
m_index = BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED;
m_tokenTable = null;
m_handleTable = new Hashtable(size);
m_indexTable = new Hashtable(size);
}
#if FEATURE_CAS_POLICY
[SecuritySafeCritical]
internal PermissionToken FindToken( Type cls )
{
IntPtr typePtr = cls.TypeHandle.Value;
PermissionToken tok = (PermissionToken)m_handleTable[typePtr];
if (tok != null)
return tok;
if (m_tokenTable == null)
return null;
tok = (PermissionToken)m_tokenTable[cls.AssemblyQualifiedName];
if (tok != null)
{
lock (this)
{
m_handleTable.Add(typePtr, tok);
}
}
return tok;
}
#endif // FEATURE_CAS_POLICY
internal PermissionToken FindTokenByIndex( int i )
{
PermissionToken token;
if (i < BuiltInPermissionIndex.NUM_BUILTIN_NORMAL + BuiltInPermissionIndex.NUM_BUILTIN_UNRESTRICTED)
{
token = BuiltInGetToken( i, null, null );
}
else
{
token = (PermissionToken)m_indexTable[i];
}
return token;
}
[SecuritySafeCritical]
internal PermissionToken GetToken(Type cls, IPermission perm)
{
Contract.Assert( cls != null, "Must pass in valid type" );
IntPtr typePtr = cls.TypeHandle.Value;
object tok = m_handleTable[typePtr];
if (tok == null)
{
String typeStr = cls.AssemblyQualifiedName;
tok = m_tokenTable != null ? m_tokenTable[typeStr] : null; // Assumes asynchronous lookups are safe
if (tok == null)
{
lock (this)
{
if (m_tokenTable != null)
{
tok = m_tokenTable[typeStr]; // Make sure it wasn't just added
}
else
m_tokenTable = new Hashtable(m_size, 1.0f, new PermissionTokenKeyComparer());
if (tok == null)
{
if (perm != null)
{
tok = new PermissionToken( m_index++, PermissionTokenType.IUnrestricted, typeStr );
}
else
{
if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null)
tok = new PermissionToken( m_index++, PermissionTokenType.IUnrestricted, typeStr );
else
tok = new PermissionToken( m_index++, PermissionTokenType.Normal, typeStr );
}
m_tokenTable.Add(typeStr, tok);
m_indexTable.Add(m_index - 1, tok);
PermissionToken.s_tokenSet.SetItem( ((PermissionToken)tok).m_index, tok );
}
if (!m_handleTable.Contains(typePtr))
m_handleTable.Add( typePtr, tok );
}
}
else
{
lock (this)
{
if (!m_handleTable.Contains(typePtr))
m_handleTable.Add( typePtr, tok );
}
}
}
if ((((PermissionToken)tok).m_type & PermissionTokenType.DontKnow) != 0)
{
if (perm != null)
{
Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
#if FEATURE_CAS_POLICY
((PermissionToken)tok).m_strTypeName = perm.GetType().AssemblyQualifiedName;
#endif // FEATURE_CAS_POLICY
}
else
{
Contract.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null)
((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
else
((PermissionToken)tok).m_type = PermissionTokenType.Normal;
#if FEATURE_CAS_POLICY
((PermissionToken)tok).m_strTypeName = cls.AssemblyQualifiedName;
#endif // FEATURE_CAS_POLICY
}
}
return (PermissionToken)tok;
}
internal PermissionToken GetToken(String typeStr)
{
Object tok = null;
tok = m_tokenTable != null ? m_tokenTable[typeStr] : null; // Assumes asynchronous lookups are safe
if (tok == null)
{
lock (this)
{
if (m_tokenTable != null)
{
tok = m_tokenTable[typeStr]; // Make sure it wasn't just added
}
else
m_tokenTable = new Hashtable(m_size, 1.0f, new PermissionTokenKeyComparer());
if (tok == null)
{
tok = new PermissionToken( m_index++, PermissionTokenType.DontKnow, typeStr );
m_tokenTable.Add(typeStr, tok);
m_indexTable.Add(m_index - 1, tok);
PermissionToken.s_tokenSet.SetItem(((PermissionToken)tok).m_index, tok);
}
}
}
return (PermissionToken)tok;
}
internal PermissionToken BuiltInGetToken( int index, IPermission perm, Type cls )
{
PermissionToken token = Volatile.Read(ref m_builtIn[index]);
if (token == null)
{
lock (this)
{
token = m_builtIn[index];
if (token == null)
{
PermissionTokenType permType = PermissionTokenType.DontKnow;
if (perm != null)
{
permType = PermissionTokenType.IUnrestricted;
}
else if (cls != null)
{
permType = PermissionTokenType.IUnrestricted;
}
token = new PermissionToken( index, permType | PermissionTokenType.BuiltIn, null );
Volatile.Write(ref m_builtIn[index], token);
PermissionToken.s_tokenSet.SetItem( token.m_index, token );
}
}
}
if ((token.m_type & PermissionTokenType.DontKnow) != 0)
{
token.m_type = PermissionTokenType.BuiltIn;
if (perm != null)
{
token.m_type |= PermissionTokenType.IUnrestricted;
}
else if (cls != null)
{
token.m_type |= PermissionTokenType.IUnrestricted;
}
else
{
token.m_type |= PermissionTokenType.DontKnow;
}
}
return token;
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections.Generic;
namespace OpenADK.Library
{
/// <summary> Encapsulates a SIF version number.
///
/// The Adk uses instances of SifVersion rather than strings to identify
/// versions of SIF. Typically you do not need to obtain a SifVersion instance
/// directly except for when initializing the class framework with the
/// <c>Adk.initialize</c> method. Rather, classes for which SIF version is
/// a property, such as SifDataObject and Query, provide a <c>getSIFVersion</c>
/// method to obtain the version associated with an object.
/// </summary>
/// <author> Eric Petersen
/// </author>
/// <version> 1.0
/// </version>
[Serializable]
public class SifVersion : IComparable
{
/// <summary> Gets the major version number</summary>
public virtual int Major
{
get { return fVersion.Major; }
}
/// <summary> Gets the minor version number</summary>
public virtual int Minor
{
get { return fVersion.Minor; }
}
/// <summary> Gets the revision number</summary>
public virtual int Revision
{
get { return fVersion.Revision; }
}
/// <summary> Get the SIF namespace for this version of the specification.
///
/// </summary>
/// <returns> If the SifVersion is less than SIF 1.1, a namespace in the form
/// "http://www.sifinfo.org/v1.0r2/messages" is returned, where the full
/// SIF Version number is included in the namespace. For SIF 1.x and
/// later, a namespace in the form "http://www.sifinfo.org/infrastructure/1.x"
/// is returned, where only the major version number is included in the
/// namespace.
/// </returns>
public virtual string Xmlns
{
get
{
if (CompareTo(SIF11) < 0)
{
return "http://www.sifinfo.org/v" + this.ToString() + "/messages";
}
// return SifDtd.XMLNS_BASE + "/" + fVersion.Major + ".x";
return Adk.Dtd.BaseNamespace + "/" + fVersion.Major + ".x";
}
}
/// <summary>Identifies the SIF 1.1 Specification </summary>
public static readonly SifVersion SIF11 = new SifVersion(1, 1, 0);
/// <summary>Identifies the SIF 1.5r1 Specification</summary>
public static readonly SifVersion SIF15r1 = new SifVersion(1, 5, 1);
/// <summary>Identifies the SIF 2.0 Specification</summary>
public static readonly SifVersion SIF20 = new SifVersion(2, 0, 0);
/// <summary>Identifies the SIF 2.0r1 Specification</summary>
public static readonly SifVersion SIF20r1 = new SifVersion(2, 0, 1);
/// <summary>Identifies the SIF 2.1 Specification</summary>
public static readonly SifVersion SIF21 = new SifVersion(2, 1, 0);
/// <summary>Identifies the SIF 2.2 Specification</summary>
public static readonly SifVersion SIF22 = new SifVersion(2, 2, 0);
/// <summary>Identifies the SIF 2.3 Specification</summary>
public static readonly SifVersion SIF23 = new SifVersion(2, 3, 0);
/// <summary>Identifies the SIF 2.4 Specification</summary>
public static readonly SifVersion SIF24 = new SifVersion(2, 4, 0);
/// <summary>Identifies the SIF 2.5 Specification</summary>
public static readonly SifVersion SIF25 = new SifVersion(2, 5, 0);
/// <summary>Identifies the SIF 2.5 Specification</summary>
public static readonly SifVersion SIF26 = new SifVersion(2, 6, 0);
//// WARNING: MAKE SURE TO UPDATE THE GETINSTANCE METHOD WHEN ADDING NEW VERSIONS ////
/// <summary>Identifies the latest SIF Specification supported by the Library Adk </summary>
public static readonly SifVersion LATEST = SIF26;
/// <summary>
/// Returns the earliest SIFVersion supported by the ADK for the major version
/// number of SIF specified. For example, passing the value 1 returns <c>SifVersion.SIF11</c>
/// </summary>
/// <param name="major"></param>
/// <returns>The latest version of SIF that the ADK supports for the specified
/// major version</returns>
public static SifVersion GetEarliest(int major)
{
switch (major)
{
case 1:
return SifVersion.SIF11;
case 2:
return SifVersion.SIF20r1;
}
return null;
}
/// <summary> Constructs a version object
///
/// </summary>
/// <param name="major">The major version number
/// </param>
/// <param name="minor">The minor version number
/// </param>
/// <param name="revision">The revision number
/// </param>
private SifVersion(int major,
int minor,
int revision)
{
fVersion = new Version(major, minor, 0, revision);
}
/// <summary> Gets a SifVersion instance</summary>
/// <remarks>
/// <para>
/// This method always returns the same version instance for the given version
/// numbers. If the version number match on official version supported by the ADK,
/// that version instance is returned. Otherwise, a new SIFVersion instance is
/// created and returned. The sam SifVersion instance will always be returned for
/// the same paramters
/// </para>
/// </remarks>
/// <returns> A SifVersion instance to encapsulate the version information
/// provided to this method. If the <i>major</i>, <i>minor</i>, and
/// <i>revision</i> numbers match one of the versions supported by the
/// Adk (e.g. SifVersion.SIF10r1, SifVersion.SIF10r2, etc.), that object
/// is returned. Otherwise, a new instance is created. Thus, you are
/// guaranteed to always receive the same SifVersion instance or a given
/// version number supported by the Adk.
/// </returns>
private static SifVersion GetInstance(int major,
int minor,
int revision)
{
// Check for versions explicitly supported by the ADK first
if (major == 2)
{
if ( minor == 0 )
{
if ( revision == 0 )
{
return SIF20;
}
else if ( revision == 1 )
{
return SIF20r1;
}
}
if ( revision == 0 )
{
if ( minor == 1 )
{
return SIF21;
}
else if ( minor == 2 )
{
return SIF22;
}
else if ( minor == 3 )
{
return SIF23;
}
else if (minor == 4)
{
return SIF24;
}
else if (minor == 5)
{
return SIF25;
}
else if (minor == 6)
{
return SIF26;
}
}
}
else if (major == 1)
{
if (minor == 5 && revision == 1)
{
return SIF15r1;
}
else if (minor == 1 && revision == 0)
{
return SIF11;
}
}
// No explicit support found. Return a newly-fabricated instance
// to support this version of SIF
String tag = ToString(major, minor, revision, '.');
SifVersion ver;
if (sVersions == null)
{
sVersions = new Dictionary<string, SifVersion>();
}
if (!sVersions.TryGetValue(tag, out ver))
{
ver = new SifVersion(major, minor, revision);
sVersions[tag] = ver;
}
return ver;
}
/// <summary> Parse a <c>SifVersion</c> from a string</summary>
/// <param name="versionStr">A version string in the format "1.0r1"</param>
/// <returns> A SifVersion instance encapsulating the version string</returns>
/// <exception cref="ArgumentException">is thrown if the version string is invalid</exception>
public static SifVersion Parse(string versionStr)
{
if (versionStr == null)
{
throw new ArgumentNullException("Version to parse cannot be null", "versionStr");
}
try
{
string v = versionStr.ToLower();
int i = v.IndexOf('.');
int major = Int32.Parse(v.Substring(0, i));
int minor;
int revision = 0;
int r = v.IndexOf('r');
if (r == -1)
{
String minorStr = v.Substring(i + 1);
if (minorStr.Equals("*"))
{
// NOTE: This may change to getLatest(major). However, the Test harness does not
// support that at the moment.
// For now, return 1.5r1 for 1.*, 2.0r1 or higher (based on ADK.getSIFVersion) for 2.*
if (major == 1)
{
return SifVersion.SIF15r1;
}
else if (major == 2)
{
if (Adk.SifVersion.CompareTo(SifVersion.SIF20r1) > 0)
{
return Adk.SifVersion;
}
else
{
return SifVersion.SIF20r1;
}
}
else
{
throw new ArgumentException("SIFVersion " + versionStr + " is not supported.");
}
}
else
{
minor = Int32.Parse(minorStr);
}
}
else
{
minor = Int32.Parse(v.Substring(i + 1, r - i - 1));
revision = Int32.Parse(v.Substring(r + 1));
}
return GetInstance(major, minor, revision);
}
catch (Exception thr)
{
throw new ArgumentException(versionStr + " is an invalid version string", thr);
}
}
/// <summary>
/// Returns the latest SIFVersion supported by the ADK for the major version
/// number of SIF specified. For example, passing the value 1 returns
/// <c>SifVersion.15r1</c>
/// </summary>
/// <param name="major"></param>
/// <returns></returns>
public static SifVersion GetLatest(int major)
{
switch (major)
{
case 1:
return SIF15r1;
case 2:
return LATEST;
}
return null;
}
/// <summary> Parse a <c>SifVersion</c> from a <i>xmlns</i> attribute value
///
/// If the xmlns attribute is in the form "http://www.sifinfo.org/v1.0r1/messages",
/// the version identified by the namespace is returned (e.g. "1.0r1"). If the
/// xmlns attribute is in the form "http://www.sifinfo.org/infrastructure/1.x",
/// the latest version of SIF identified by the major version number is
/// returned.
///
/// </summary>
/// <param name="xmlns">A SIF xmlns attribute value (e.g. "http://www.sifinfo.org/v1.0r1/messages",
/// "http://www.sifinfo.org/infrastructure/1x.", etc)
///
/// </param>
/// <returns> A SifVersion object encapsulating the version of SIF identified
/// by the xmlns value, or null if the xmlns is invalid
/// </returns>
public static SifVersion ParseXmlns(string xmlns)
{
//
// Determine the SIFVersion:
//
if (xmlns != null)
{
if (xmlns.EndsWith(".x"))
{
// http://www.sifinfo.org/infrastructure/1.x
// NOTE: This works until SIF 10.x
int location = xmlns.LastIndexOf('/');
char majorCh = xmlns[location + 1];
if (char.IsDigit(majorCh))
{
int major = majorCh - 48;
return GetLatest(major);
}
}
}
return null;
}
/// <summary> Gets the string representation of the version</summary>
/// <returns> The tag passed to the constructor. If null, a version in the
/// form <i>major</i>.<i>minor</i>r<i>revision</i> is returned with no
/// padding.
/// </returns>
public override string ToString()
{
return ToString(this.Major, this.Minor, this.Revision, '.');
}
/// <summary>
/// Formats a SIF Version String for the ToString() and ToSymbol() methods
/// </summary>
/// <param name="major"></param>
/// <param name="minor"></param>
/// <param name="revision"></param>
/// <returns></returns>
/// <param name="seperator"></param>
private static String ToString(int major,
int minor,
int revision,
char seperator)
{
if (revision < 1)
{
return String.Format("{1}{0}{2}", seperator, major, minor);
}
else
{
return String.Format("{1}{0}{2}r{3}", seperator, major, minor, revision);
}
}
/// <summary> Gets the string representation of the version using an underscore instead
/// of a period as the delimiter
/// </summary>
public virtual string ToSymbol()
{
return ToString(this.Major, this.Minor, this.Revision, '_');
}
#region Private Members
/// <summary>
/// The dictionary of current active versions
/// </summary>
private static IDictionary<String, SifVersion> sVersions = null;
/// <summary>
/// The current version
/// </summary>
protected readonly Version fVersion;
#endregion
#region Comparison
public override bool Equals(object obj)
{
// Test reference comparison first ( fastest )
if (ReferenceEquals(this, obj))
{
return true;
}
if ((!ReferenceEquals(obj, null)) &&
(obj.GetType().Equals(this.GetType())))
{
return fVersion.Equals(((SifVersion)obj).fVersion);
}
return false;
}
public override int GetHashCode()
{
return fVersion.GetHashCode();
}
/// <summary> Compare this version to another</summary>
/// <param name="version">The version to compare</param>
/// <returns> -1 if this version is earlier than <c>version</c>, 0 if
/// the versions are equal, or 1 if this version is greater than <c>
/// version</c> or <c>version</c> is null
/// </returns>
public int CompareTo(object version)
{
if (version == null)
{
return 1;
}
if (!(version is SifVersion))
{
throw new ArgumentException
(string.Format
("{0} cannot be compared to a SifVersion object", version.GetType().FullName));
}
return fVersion.CompareTo(((SifVersion)version).fVersion);
}
public static bool operator >(SifVersion version1,
SifVersion version2)
{
return version1.fVersion > version2.fVersion;
}
public static bool operator <(SifVersion version1,
SifVersion version2)
{
return version1.fVersion < version2.fVersion;
}
public static bool operator >=(SifVersion version1,
SifVersion version2)
{
return version1.fVersion >= version2.fVersion;
}
public static bool operator <=(SifVersion version1,
SifVersion version2)
{
return version1.fVersion <= version2.fVersion;
}
public static bool operator ==(SifVersion version1,
SifVersion version2)
{
if( object.ReferenceEquals( version1, null ) )
{
return object.ReferenceEquals( version2, null );
}
else if (object.ReferenceEquals(version2, null))
{
return object.ReferenceEquals(version1, null);
}
return version1.fVersion == version2.fVersion;
}
public static bool operator !=(SifVersion version1,
SifVersion version2)
{
// use the opposite result of the
// == operator
return !(version1 == version2);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.ServiceModel;
namespace Petite
{
/// <summary>
/// Interface implemented by the Context class to provide an Object Set
/// </summary>
public interface IObjectSetProvider
{
/// <summary>
/// Create an Object Set for a specific entity
/// </summary>
/// <typeparam name="TEntity">Type of the entity to provide a set for</typeparam>
/// <returns>An object set for <typeparamref name="TEntity"/> objects</returns>
IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class;
}
/// <summary>
/// Interface for creating an object context
/// </summary>
public interface IObjectContextFactory
{
/// <summary>
/// Create an Entity Framework object context
/// </summary>
/// <returns>A new ObjectContext</returns>
ObjectContext Create();
/// <summary>
/// Identifies this Object Context
/// </summary>
string ContextTypeName { get; }
}
/// <summary>
/// Factory for creating an Entity Framework ObjectContext
/// </summary>
/// <typeparam name="TContext">Type of ObjectContext to create</typeparam>
public class ObjectContextFactory<TContext> : IObjectContextFactory
where TContext : ObjectContext, new()
{
public ObjectContext Create()
{
return new TContext();
}
public string ContextTypeName
{
get { return typeof(TContext).Name; }
}
}
/// <summary>
/// This will act as an IObjectSetProvider and IObjectContext using a per WCF-operation ObjectContext that is
/// automatically disposed of when completed.
/// </summary>
public class WcfObjectContextAdapter : IObjectSetProvider, IObjectContext
{
private readonly IObjectContextFactory _contextFactory;
/// <summary>
/// Create a new instance of the adapter
/// </summary>
/// <param name="contextFactory">Factory to use to construct the DbContext</param>
public WcfObjectContextAdapter(IObjectContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
protected virtual string KeyName { get { return _contextFactory.ContextTypeName; } }
public IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class
{
var context = GetCurrentContext();
return context.CreateObjectSet<TEntity>();
}
public int SaveChanges()
{
var context = GetCurrentContext();
return context.SaveChanges();
}
public void Detach(object obj)
{
var context = GetCurrentContext();
context.Detach(obj);
}
protected ObjectContext GetCurrentContext()
{
var storageExtension = OperationContextStorageExtension.Current;
var objContext = storageExtension.Get<ObjectContext>(KeyName);
if(objContext == null)
{
// No DbContext has been created for this operation yet. Create a new one...
objContext = _contextFactory.Create();
// ... store it and make sure it will be Disposed when the operation is completed.
storageExtension.Store(objContext, KeyName, () => objContext.Dispose());
}
return objContext;
}
}
/// <summary>
/// A simple implementation of IObjectContext and IObjectSetProvider that creates a single object context
/// and uses it
/// </summary>
public class SingleUsageObjectContextAdapter : IObjectSetProvider, IObjectContext
{
private readonly IObjectContextFactory _contextFactory;
protected ObjectContext ObjContext { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="contextFactory"></param>
public SingleUsageObjectContextAdapter(IObjectContextFactory contextFactory)
{
_contextFactory = contextFactory;
ObjContext = _contextFactory.Create();
}
public IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class
{
return ObjContext.CreateObjectSet<TEntity>();
}
public int SaveChanges()
{
return ObjContext.SaveChanges();
}
}
/// <summary>
/// Extension class for keeping instances of object stored in the current OperationContext.
/// </summary>
public class OperationContextStorageExtension : IExtension<OperationContext>
{
class ValueAndAction
{
public ValueAndAction(object value, Action action)
{
Value = value;
Action = action;
}
public object Value { get; private set; }
public Action Action { get; private set; }
}
private readonly IDictionary<object, ValueAndAction> _instances;
private OperationContextStorageExtension()
{
_instances = new Dictionary<object, ValueAndAction>();
}
/// <summary>
/// Store an object
/// </summary>
/// <param name="value">Object to store</param>
/// <param name="completedAction">Optional Action to invoke when the current operation has completed.</param>
public void Store<T>(T value, Action completedAction = null)
{
_instances[typeof(T)] = new ValueAndAction(value, completedAction);
}
/// <summary>
/// Store an object
/// </summary>
/// <param name="value">Object to store</param>
/// <param name="key">Key to use</param>
/// <param name="completedAction">Optional Action to invoke when the current operation has completed.</param>
public void Store<T>(T value, object key, Action completedAction = null)
{
_instances[key] = new ValueAndAction(value, completedAction);
}
/// <summary>
/// Get a stored object
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <returns>The stored object or null if no object of type <typeparamref name="T"/> has been stored</returns>
public T Get<T>()
{
ValueAndAction obj;
if(!_instances.TryGetValue(typeof(T), out obj))
return default(T);
return (T)obj.Value;
}
/// <summary>
/// Get a stored object
/// </summary>
/// <typeparam name="T">Type of the object to get</typeparam>
/// <param name="key">Key of the object</param>
/// <returns>The stored object or null if no object with that key has been stored</returns>
public T Get<T>(object key)
{
ValueAndAction obj;
if(!_instances.TryGetValue(key, out obj))
return default(T);
return (T)obj.Value;
}
public void Attach(OperationContext owner)
{
// Make sure we are notified when the operation is complete
owner.OperationCompleted += OnOperationCompleted;
}
public void Detach(OperationContext owner)
{
owner.OperationCompleted -= OnOperationCompleted;
}
void OnOperationCompleted(object sender, EventArgs e)
{
// Invoke any actions
foreach(var obj in _instances.Values)
{
if(obj.Action != null)
obj.Action.Invoke();
}
}
/// <summary>
/// Get or create the one and only StorageExtension
/// </summary>
public static OperationContextStorageExtension Current
{
get
{
var opContext = OperationContext.Current;
if(opContext == null)
throw new InvalidOperationException("No OperationContext");
var currentContext = opContext.Extensions.Find<OperationContextStorageExtension>();
if(currentContext == null)
{
currentContext = new OperationContextStorageExtension();
opContext.Extensions.Add(currentContext);
}
return currentContext;
}
}
}
/// <summary>
/// Base class for implementing the Repository pattern over an Entity Framework entity
/// </summary>
/// <remarks>Usually you will derive from this class to create an entity-specific repository</remarks>
/// <typeparam name="TEntity">Entity to expose via the Repository</typeparam>
public class RepositoryBase<TEntity> : IRepository<TEntity>
where TEntity : class
{
private readonly IObjectSet<TEntity> _objectSet;
public RepositoryBase(IObjectSetProvider objectSetProvider)
{
_objectSet = objectSetProvider.CreateObjectSet<TEntity>();
if(_objectSet == null)
throw new InvalidOperationException("Unable to create object set");
}
/// <summary>
/// This property can be used by derived classes in order to get access to the underlying DbSet
/// </summary>
protected virtual IObjectSet<TEntity> Query
{
get { return _objectSet; }
}
/// <summary>
/// Return all entities
/// </summary>
public virtual IEnumerable<TEntity> List()
{
return Query.ToArray();
}
/// <summary>
/// Return all entities that match the <c cref="whereClause">whereClause</c>
/// </summary>
public virtual IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> whereClause)
{
return Query.Where(whereClause).ToArray();
}
/// <summary>
/// Return the first entity that matches the <c cref="whereClause">whereClause</c>
/// </summary>
public virtual TEntity Get(Expression<Func<TEntity, bool>> whereClause)
{
return Query.Where(whereClause).FirstOrDefault();
}
/// <summary>
/// Add a new entity to the repository
/// </summary>
public virtual void Add(TEntity entity)
{
_objectSet.AddObject(entity);
}
/// <summary>
/// Delete an existing entity from the repository
/// </summary>
public virtual void Delete(TEntity entity)
{
_objectSet.DeleteObject(entity);
}
}
public static class RepositoryExtensions
{
public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path)
{
var objectQuery = source as ObjectQuery<TSource>;
if(objectQuery != null)
{
return objectQuery.Include(path);
}
return source;
}
}
}
| |
using System.Diagnostics;
using System.Text;
using HANDLE = System.IntPtr;
using i64 = System.Int64;
using u32 = System.UInt32;
using sqlite3_int64 = System.Int64;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2005 November 29
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains OS interface code that is common to all
** architectures.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45
**
*************************************************************************
*/
//#define _SQLITE_OS_C_ 1
//#include "sqliteInt.h"
//#undef _SQLITE_OS_C_
/*
** The default SQLite sqlite3_vfs implementations do not allocate
** memory (actually, os_unix.c allocates a small amount of memory
** from within OsOpen()), but some third-party implementations may.
** So we test the effects of a malloc() failing and the sqlite3OsXXX()
** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
**
** The following functions are instrumented for malloc() failure
** testing:
**
** sqlite3OsOpen()
** sqlite3OsRead()
** sqlite3OsWrite()
** sqlite3OsSync()
** sqlite3OsLock()
**
*/
#if (SQLITE_TEST)
static int sqlite3_memdebug_vfs_oom_test = 1;
//#define DO_OS_MALLOC_TEST(x) \
//if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
// void *pTstAlloc = sqlite3Malloc(10); \
// if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
// sqlite3_free(pTstAlloc); \
//}
static void DO_OS_MALLOC_TEST( sqlite3_file x )
{
}
#else
//#define DO_OS_MALLOC_TEST(x)
static void DO_OS_MALLOC_TEST( sqlite3_file x ) { }
#endif
/*
** The following routines are convenience wrappers around methods
** of the sqlite3_file object. This is mostly just syntactic sugar. All
** of this would be completely automatic if SQLite were coded using
** C++ instead of plain old C.
*/
static int sqlite3OsClose( sqlite3_file pId )
{
int rc = SQLITE_OK;
if ( pId.pMethods != null )
{
rc = pId.pMethods.xClose( pId );
pId.pMethods = null;
}
return rc;
}
static int sqlite3OsRead( sqlite3_file id, byte[] pBuf, int amt, i64 offset )
{
DO_OS_MALLOC_TEST( id );
if ( pBuf == null )
pBuf = sqlite3Malloc( amt );
return id.pMethods.xRead( id, pBuf, amt, offset );
}
static int sqlite3OsWrite( sqlite3_file id, byte[] pBuf, int amt, i64 offset )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xWrite( id, pBuf, amt, offset );
}
static int sqlite3OsTruncate( sqlite3_file id, i64 size )
{
return id.pMethods.xTruncate( id, size );
}
static int sqlite3OsSync( sqlite3_file id, int flags )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xSync( id, flags );
}
static int sqlite3OsFileSize( sqlite3_file id, ref long pSize )
{
return id.pMethods.xFileSize( id, ref pSize );
}
static int sqlite3OsLock( sqlite3_file id, int lockType )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xLock( id, lockType );
}
static int sqlite3OsUnlock( sqlite3_file id, int lockType )
{
return id.pMethods.xUnlock( id, lockType );
}
static int sqlite3OsCheckReservedLock( sqlite3_file id, ref int pResOut )
{
DO_OS_MALLOC_TEST( id );
return id.pMethods.xCheckReservedLock( id, ref pResOut );
}
static int sqlite3OsFileControl( sqlite3_file id, u32 op, ref sqlite3_int64 pArg )
{
return id.pMethods.xFileControl( id, (int)op, ref pArg );
}
static int sqlite3OsSectorSize( sqlite3_file id )
{
dxSectorSize xSectorSize = id.pMethods.xSectorSize;
return ( xSectorSize != null ? xSectorSize( id ) : SQLITE_DEFAULT_SECTOR_SIZE );
}
static int sqlite3OsDeviceCharacteristics( sqlite3_file id )
{
return id.pMethods.xDeviceCharacteristics( id );
}
static int sqlite3OsShmLock( sqlite3_file id, int offset, int n, int flags )
{
return id.pMethods.xShmLock( id, offset, n, flags );
}
static void sqlite3OsShmBarrier( sqlite3_file id )
{
id.pMethods.xShmBarrier( id );
}
static int sqlite3OsShmUnmap( sqlite3_file id, int deleteFlag )
{
return id.pMethods.xShmUnmap( id, deleteFlag );
}
static int sqlite3OsShmMap(
sqlite3_file id, /* Database file handle */
int iPage,
int pgsz,
int bExtend, /* True to extend file if necessary */
out object pp /* OUT: Pointer to mapping */
)
{
return id.pMethods.xShmMap( id, iPage, pgsz, bExtend, out pp );
}
/*
** The next group of routines are convenience wrappers around the
** VFS methods.
*/
static int sqlite3OsOpen(
sqlite3_vfs pVfs,
string zPath,
sqlite3_file pFile,
int flags,
ref int pFlagsOut
)
{
int rc;
DO_OS_MALLOC_TEST( null );
/* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
** reaching the VFS. */
rc = pVfs.xOpen( pVfs, zPath, pFile, flags & 0x87f3f, out pFlagsOut );
Debug.Assert( rc == SQLITE_OK || pFile.pMethods == null );
return rc;
}
static int sqlite3OsDelete( sqlite3_vfs pVfs, string zPath, int dirSync )
{
return pVfs.xDelete( pVfs, zPath, dirSync );
}
static int sqlite3OsAccess( sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut )
{
DO_OS_MALLOC_TEST( null );
return pVfs.xAccess( pVfs, zPath, flags, out pResOut );
}
static int sqlite3OsFullPathname(
sqlite3_vfs pVfs,
string zPath,
int nPathOut,
StringBuilder zPathOut
)
{
zPathOut.Length = 0;//zPathOut[0] = 0;
return pVfs.xFullPathname( pVfs, zPath, nPathOut, zPathOut );
}
#if !SQLITE_OMIT_LOAD_EXTENSION
static HANDLE sqlite3OsDlOpen( sqlite3_vfs pVfs, string zPath )
{
return pVfs.xDlOpen( pVfs, zPath );
}
static void sqlite3OsDlError( sqlite3_vfs pVfs, int nByte, string zBufOut )
{
pVfs.xDlError( pVfs, nByte, zBufOut );
}
static object sqlite3OsDlSym( sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym )
{
return pVfs.xDlSym( pVfs, pHdle, zSym );
}
static void sqlite3OsDlClose( sqlite3_vfs pVfs, HANDLE pHandle )
{
pVfs.xDlClose( pVfs, pHandle );
}
#endif
static int sqlite3OsRandomness( sqlite3_vfs pVfs, int nByte, byte[] zBufOut )
{
return pVfs.xRandomness( pVfs, nByte, zBufOut );
}
static int sqlite3OsSleep( sqlite3_vfs pVfs, int nMicro )
{
return pVfs.xSleep( pVfs, nMicro );
}
static int sqlite3OsCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTimeOut )
{
int rc;
/* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
** method to get the current date and time if that method is available
** (if iVersion is 2 or greater and the function pointer is not NULL) and
** will fall back to xCurrentTime() if xCurrentTimeInt64() is
** unavailable.
*/
if ( pVfs.iVersion >= 2 && pVfs.xCurrentTimeInt64 != null )
{
rc = pVfs.xCurrentTimeInt64( pVfs, ref pTimeOut );
}
else
{
double r = 0;
rc = pVfs.xCurrentTime( pVfs, ref r );
pTimeOut = (sqlite3_int64)( r * 86400000.0 );
}
return rc;
}
static int sqlite3OsOpenMalloc(
ref sqlite3_vfs pVfs,
string zFile,
ref sqlite3_file ppFile,
int flags,
ref int pOutFlags
)
{
int rc = SQLITE_NOMEM;
sqlite3_file pFile;
pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile);
if ( pFile != null )
{
rc = sqlite3OsOpen( pVfs, zFile, pFile, flags, ref pOutFlags );
if ( rc != SQLITE_OK )
{
pFile = null; // was sqlite3DbFree(db,ref pFile);
}
else
{
ppFile = pFile;
}
}
return rc;
}
static int sqlite3OsCloseFree( sqlite3_file pFile )
{
int rc = SQLITE_OK;
Debug.Assert( pFile != null );
rc = sqlite3OsClose( pFile );
//sqlite3_free( ref pFile );
return rc;
}
/*
** This function is a wrapper around the OS specific implementation of
** sqlite3_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite3_os_init() by the upper layers can be tested.
*/
static int sqlite3OsInit()
{
//void *p = sqlite3_malloc(10);
//if( p==null ) return SQLITE_NOMEM;
//sqlite3_free(ref p);
return sqlite3_os_init();
}
/*
** The list of all registered VFS implementations.
*/
static sqlite3_vfs vfsList;
//#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
/*
** Locate a VFS by name. If no name is given, simply return the
** first VFS on the list.
*/
static bool isInit = false;
static sqlite3_vfs sqlite3_vfs_find( string zVfs )
{
sqlite3_vfs pVfs = null;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex;
#endif
#if !SQLITE_OMIT_AUTOINIT
int rc = sqlite3_initialize();
if ( rc != 0 )
return null;
#endif
#if SQLITE_THREADSAFE
mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter( mutex );
for ( pVfs = vfsList; pVfs != null; pVfs = pVfs.pNext )
{
if ( zVfs == null || zVfs == "" )
break;
if ( zVfs == pVfs.zName )
break; //strcmp(zVfs, pVfs.zName) == null) break;
}
sqlite3_mutex_leave( mutex );
return pVfs;
}
/*
** Unlink a VFS from the linked list
*/
static void vfsUnlink( sqlite3_vfs pVfs )
{
Debug.Assert( sqlite3_mutex_held( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ) );
if ( pVfs == null )
{
/* No-op */
}
else if ( vfsList == pVfs )
{
vfsList = pVfs.pNext;
}
else if ( vfsList != null )
{
sqlite3_vfs p = vfsList;
while ( p.pNext != null && p.pNext != pVfs )
{
p = p.pNext;
}
if ( p.pNext == pVfs )
{
p.pNext = pVfs.pNext;
}
}
}
/*
** Register a VFS with the system. It is harmless to register the same
** VFS multiple times. The new VFS becomes the default if makeDflt is
** true.
*/
static int sqlite3_vfs_register( sqlite3_vfs pVfs, int makeDflt )
{
sqlite3_mutex mutex;
#if !SQLITE_OMIT_AUTOINIT
int rc = sqlite3_initialize();
if ( rc != 0 )
return rc;
#endif
mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
sqlite3_mutex_enter( mutex );
vfsUnlink( pVfs );
if ( makeDflt != 0 || vfsList == null )
{
pVfs.pNext = vfsList;
vfsList = pVfs;
}
else
{
pVfs.pNext = vfsList.pNext;
vfsList.pNext = pVfs;
}
Debug.Assert( vfsList != null );
sqlite3_mutex_leave( mutex );
return SQLITE_OK;
}
/*
** Unregister a VFS so that it is no longer accessible.
*/
static int sqlite3_vfs_unregister( sqlite3_vfs pVfs )
{
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter( mutex );
vfsUnlink( pVfs );
sqlite3_mutex_leave( mutex );
return SQLITE_OK;
}
}
}
| |
using System;
using System.Drawing;
using System.Text;
using System.Runtime.InteropServices;
namespace GhostscriptSharp
{
/// <summary>
/// Wraps the Ghostscript API with a C# interface
/// </summary>
public class GhostscriptWrapper
{
#region Globals
private static readonly string[] ARGS = new string[] {
// Keep gs from writing information to standard output
"-q",
"-dQUIET",
"-dPARANOIDSAFER", // Run this command in safe mode
"-dBATCH", // Keep gs from going into interactive mode
"-dNOPAUSE", // Do not prompt and pause for each page
"-dNOPROMPT", // Disable prompts for user interaction
"-dMaxBitmap=500000000", // Set high for better performance
"-dNumRenderingThreads=4", // Multi-core, come-on!
// Configure the output anti-aliasing, resolution, etc
"-dAlignToPixels=0",
"-dGridFitTT=0",
"-dTextAlphaBits=4",
"-dGraphicsAlphaBits=4"
};
#endregion
/// <summary>
/// Generates a thumbnail jpg for the pdf at the input path and saves it
/// at the output path
/// </summary>
public static void GeneratePageThumb(string inputPath, string outputPath, int page, int dpix, int dpiy, int width = 0, int height = 0)
{
GeneratePageThumbs(inputPath, outputPath, page, page, dpix, dpiy, width, height);
}
/// <summary>
/// Generates a collection of thumbnail jpgs for the pdf at the input path
/// starting with firstPage and ending with lastPage.
/// Put "%d" somewhere in the output path to have each of the pages numbered
/// </summary>
public static void GeneratePageThumbs(string inputPath, string outputPath, int firstPage, int lastPage, int dpix, int dpiy, int width = 0, int height = 0)
{
if (IntPtr.Size == 4)
API.GhostScript32.CallAPI(GetArgs(inputPath, outputPath, firstPage, lastPage, dpix, dpiy, width, height));
else
API.GhostScript64.CallAPI(GetArgs(inputPath, outputPath, firstPage, lastPage, dpix, dpiy, width, height));
}
/// <summary>
/// Rasterises a PDF into selected format
/// </summary>
/// <param name="inputPath">PDF file to convert</param>
/// <param name="outputPath">Destination file</param>
/// <param name="settings">Conversion settings</param>
public static void GenerateOutput(string inputPath, string outputPath, GhostscriptSettings settings)
{
if (IntPtr.Size == 4)
API.GhostScript32.CallAPI(GetArgs(inputPath, outputPath, settings));
else
API.GhostScript64.CallAPI(GetArgs(inputPath, outputPath, settings));
}
/// <summary>
/// Returns an array of arguments to be sent to the Ghostscript API
/// </summary>
/// <param name="inputPath">Path to the source file</param>
/// <param name="outputPath">Path to the output file</param>
/// <param name="firstPage">The page of the file to start on</param>
/// <param name="lastPage">The page of the file to end on</param>
private static string[] GetArgs(string inputPath,
string outputPath,
int firstPage,
int lastPage,
int dpix,
int dpiy,
int width,
int height)
{
// To maintain backwards compatibility, this method uses previous hardcoded values.
GhostscriptSettings s = new GhostscriptSettings();
s.Device = Settings.GhostscriptDevices.jpeg;
s.Page.Start = firstPage;
s.Page.End = lastPage;
s.Resolution = new System.Drawing.Size(dpix, dpiy);
Settings.GhostscriptPageSize pageSize = new Settings.GhostscriptPageSize();
if (width == 0 && height == 0)
{
pageSize.Native = GhostscriptSharp.Settings.GhostscriptPageSizes.a7;
}
else
{
pageSize.Manual = new Size(width, height);
}
s.Size = pageSize;
return GetArgs(inputPath, outputPath, s);
}
/// <summary>
/// Returns an array of arguments to be sent to the Ghostscript API
/// </summary>
/// <param name="inputPath">Path to the source file</param>
/// <param name="outputPath">Path to the output file</param>
/// <param name="settings">API parameters</param>
/// <returns>API arguments</returns>
private static string[] GetArgs(string inputPath,
string outputPath,
GhostscriptSettings settings)
{
System.Collections.ArrayList args = new System.Collections.ArrayList(ARGS);
if (settings.Device == Settings.GhostscriptDevices.UNDEFINED)
{
throw new ArgumentException("An output device must be defined for Ghostscript", "GhostscriptSettings.Device");
}
if (settings.Page.AllPages == false && (settings.Page.Start <= 0 && settings.Page.End < settings.Page.Start))
{
throw new ArgumentException("Pages to be printed must be defined.", "GhostscriptSettings.Pages");
}
if (settings.Resolution.IsEmpty)
{
throw new ArgumentException("An output resolution must be defined", "GhostscriptSettings.Resolution");
}
if (settings.Size.Native == Settings.GhostscriptPageSizes.UNDEFINED && settings.Size.Manual.IsEmpty)
{
throw new ArgumentException("Page size must be defined", "GhostscriptSettings.Size");
}
// Output device
args.Add(String.Format("-sDEVICE={0}", settings.Device));
// Pages to output
if (settings.Page.AllPages)
{
args.Add("-dFirstPage=1");
}
else
{
args.Add(String.Format("-dFirstPage={0}", settings.Page.Start));
if (settings.Page.End >= settings.Page.Start)
{
args.Add(String.Format("-dLastPage={0}", settings.Page.End));
}
}
// Page size
if (settings.Size.Native == Settings.GhostscriptPageSizes.UNDEFINED)
{
args.Add(String.Format("-dDEVICEWIDTHPOINTS={0}", settings.Size.Manual.Width));
args.Add(String.Format("-dDEVICEHEIGHTPOINTS={0}", settings.Size.Manual.Height));
args.Add("-dFIXEDMEDIA");
args.Add("-dPDFFitPage");
}
else
{
args.Add(String.Format("-sPAPERSIZE={0}", settings.Size.Native.ToString()));
}
// Page resolution
args.Add(String.Format("-dDEVICEXRESOLUTION={0}", settings.Resolution.Width));
args.Add(String.Format("-dDEVICEYRESOLUTION={0}", settings.Resolution.Height));
// Files
args.Add(String.Format("-sOutputFile={0}", outputPath));
args.Add(inputPath);
return (string[])args.ToArray(typeof(string));
}
}
/// <summary>
/// Ghostscript settings
/// </summary>
public class GhostscriptSettings
{
private Settings.GhostscriptDevices _device;
private Settings.GhostscriptPages _pages = new Settings.GhostscriptPages();
private System.Drawing.Size _resolution;
private Settings.GhostscriptPageSize _size = new Settings.GhostscriptPageSize();
public Settings.GhostscriptDevices Device
{
get { return this._device; }
set { this._device = value; }
}
public Settings.GhostscriptPages Page
{
get { return this._pages; }
set { this._pages = value; }
}
public System.Drawing.Size Resolution
{
get { return this._resolution; }
set { this._resolution = value; }
}
public Settings.GhostscriptPageSize Size
{
get { return this._size; }
set { this._size = value; }
}
}
}
namespace GhostscriptSharp.Settings
{
/// <summary>
/// Which pages to output
/// </summary>
public class GhostscriptPages
{
private bool _allPages = true;
private int _start;
private int _end;
/// <summary>
/// Output all pages avaialble in document
/// </summary>
public bool AllPages
{
set
{
this._start = -1;
this._end = -1;
this._allPages = true;
}
get
{
return this._allPages;
}
}
/// <summary>
/// Start output at this page (1 for page 1)
/// </summary>
public int Start
{
set
{
this._allPages = false;
this._start = value;
}
get
{
return this._start;
}
}
/// <summary>
/// Page to stop output at
/// </summary>
public int End
{
set
{
this._allPages = false;
this._end = value;
}
get
{
return this._end;
}
}
}
/// <summary>
/// Output devices for GhostScript
/// </summary>
public enum GhostscriptDevices
{
UNDEFINED,
png16m,
pnggray,
png256,
png16,
pngmono,
pngalpha,
jpeg,
jpeggray,
tiffgray,
tiff12nc,
tiff24nc,
tiff32nc,
tiffsep,
tiffcrle,
tiffg3,
tiffg32d,
tiffg4,
tifflzw,
tiffpack,
faxg3,
faxg32d,
faxg4,
bmpmono,
bmpgray,
bmpsep1,
bmpsep8,
bmp16,
bmp256,
bmp16m,
bmp32b,
pcxmono,
pcxgray,
pcx16,
pcx256,
pcx24b,
pcxcmyk,
psdcmyk,
psdrgb,
pdfwrite,
pswrite,
epswrite,
pxlmono,
pxlcolor
}
/// <summary>
/// Output document physical dimensions
/// </summary>
public class GhostscriptPageSize
{
private GhostscriptPageSizes _fixed;
private System.Drawing.Size _manual;
/// <summary>
/// Custom document size
/// </summary>
public System.Drawing.Size Manual
{
set
{
this._fixed = GhostscriptPageSizes.UNDEFINED;
this._manual = value;
}
get
{
return this._manual;
}
}
/// <summary>
/// Standard paper size
/// </summary>
public GhostscriptPageSizes Native
{
set
{
this._fixed = value;
this._manual = new System.Drawing.Size(0, 0);
}
get
{
return this._fixed;
}
}
}
/// <summary>
/// Native page sizes
/// </summary>
/// <remarks>
/// Missing 11x17 as enums can't start with a number, and I can't be bothered
/// to add in logic to handle it - if you need it, do it yourself.
/// </remarks>
public enum GhostscriptPageSizes
{
UNDEFINED,
ledger,
legal,
letter,
lettersmall,
archE,
archD,
archC,
archB,
archA,
a0,
a1,
a2,
a3,
a4,
a4small,
a5,
a6,
a7,
a8,
a9,
a10,
isob0,
isob1,
isob2,
isob3,
isob4,
isob5,
isob6,
c0,
c1,
c2,
c3,
c4,
c5,
c6,
jisb0,
jisb1,
jisb2,
jisb3,
jisb4,
jisb5,
jisb6,
b0,
b1,
b2,
b3,
b4,
b5,
flsa,
flse,
halfletter
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Text.Tests
{
public class ValueStringBuilderTests
{
[Fact]
public void Ctor_Default_CanAppend()
{
var vsb = default(ValueStringBuilder);
Assert.Equal(0, vsb.Length);
vsb.Append('a');
Assert.Equal(1, vsb.Length);
Assert.Equal("a", vsb.ToString());
}
[Fact]
public void Ctor_Span_CanAppend()
{
var vsb = new ValueStringBuilder(new char[1]);
Assert.Equal(0, vsb.Length);
vsb.Append('a');
Assert.Equal(1, vsb.Length);
Assert.Equal("a", vsb.ToString());
}
[Fact]
public void Ctor_InitialCapacity_CanAppend()
{
var vsb = new ValueStringBuilder(1);
Assert.Equal(0, vsb.Length);
vsb.Append('a');
Assert.Equal(1, vsb.Length);
Assert.Equal("a", vsb.ToString());
}
[Fact]
public void Append_Char_MatchesStringBuilder()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
for (int i = 1; i <= 100; i++)
{
sb.Append((char)i);
vsb.Append((char)i);
}
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
public void Append_String_MatchesStringBuilder()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
for (int i = 1; i <= 100; i++)
{
string s = i.ToString();
sb.Append(s);
vsb.Append(s);
}
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Theory]
[InlineData(0, 4*1024*1024)]
[InlineData(1025, 4*1024*1024)]
[InlineData(3*1024*1024, 6*1024*1024)]
public void Append_String_Large_MatchesStringBuilder(int initialLength, int stringLength)
{
var sb = new StringBuilder(initialLength);
var vsb = new ValueStringBuilder(new char[initialLength]);
string s = new string('a', stringLength);
sb.Append(s);
vsb.Append(s);
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
public void Append_CharInt_MatchesStringBuilder()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
for (int i = 1; i <= 100; i++)
{
sb.Append((char)i, i);
vsb.Append((char)i, i);
}
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
public unsafe void Append_PtrInt_MatchesStringBuilder()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
for (int i = 1; i <= 100; i++)
{
string s = i.ToString();
fixed (char* p = s)
{
sb.Append(p, s.Length);
vsb.Append(p, s.Length);
}
}
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
public void AppendSpan_DataAppendedCorrectly()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
for (int i = 1; i <= 1000; i++)
{
string s = i.ToString();
sb.Append(s);
Span<char> span = vsb.AppendSpan(s.Length);
Assert.Equal(sb.Length, vsb.Length);
s.AsSpan().CopyTo(span);
}
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
public void Insert_IntCharInt_MatchesStringBuilder()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
var rand = new Random(42);
for (int i = 1; i <= 100; i++)
{
int index = rand.Next(sb.Length);
sb.Insert(index, new string((char)i, 1), i);
vsb.Insert(index, (char)i, i);
}
Assert.Equal(sb.Length, vsb.Length);
Assert.Equal(sb.ToString(), vsb.ToString());
}
[Fact]
public void AsSpan_ReturnsCorrectValue_DoesntClearBuilder()
{
var sb = new StringBuilder();
var vsb = new ValueStringBuilder();
for (int i = 1; i <= 100; i++)
{
string s = i.ToString();
sb.Append(s);
vsb.Append(s);
}
var resultString = new string(vsb.AsSpan());
Assert.Equal(sb.ToString(), resultString);
Assert.NotEqual(0, sb.Length);
Assert.Equal(sb.Length, vsb.Length);
}
[Fact]
public void ToString_ClearsBuilder_ThenReusable()
{
const string Text1 = "test";
var vsb = new ValueStringBuilder();
vsb.Append(Text1);
Assert.Equal(Text1.Length, vsb.Length);
string s = vsb.ToString();
Assert.Equal(Text1, s);
Assert.Equal(0, vsb.Length);
Assert.Equal(string.Empty, vsb.ToString());
Assert.True(vsb.TryCopyTo(Span<char>.Empty, out _));
const string Text2 = "another test";
vsb.Append(Text2);
Assert.Equal(Text2.Length, vsb.Length);
Assert.Equal(Text2, vsb.ToString());
}
[Fact]
public void TryCopyTo_FailsWhenDestinationIsTooSmall_SucceedsWhenItsLargeEnough()
{
var vsb = new ValueStringBuilder();
const string Text = "expected text";
vsb.Append(Text);
Assert.Equal(Text.Length, vsb.Length);
Span<char> dst = new char[Text.Length - 1];
Assert.False(vsb.TryCopyTo(dst, out int charsWritten));
Assert.Equal(0, charsWritten);
Assert.Equal(0, vsb.Length);
}
[Fact]
public void TryCopyTo_ClearsBuilder_ThenReusable()
{
const string Text1 = "test";
var vsb = new ValueStringBuilder();
vsb.Append(Text1);
Assert.Equal(Text1.Length, vsb.Length);
Span<char> dst = new char[Text1.Length];
Assert.True(vsb.TryCopyTo(dst, out int charsWritten));
Assert.Equal(Text1.Length, charsWritten);
Assert.Equal(Text1, new string(dst));
Assert.Equal(0, vsb.Length);
Assert.Equal(string.Empty, vsb.ToString());
Assert.True(vsb.TryCopyTo(Span<char>.Empty, out _));
const string Text2 = "another test";
vsb.Append(Text2);
Assert.Equal(Text2.Length, vsb.Length);
Assert.Equal(Text2, vsb.ToString());
}
[Fact]
public void Dispose_ClearsBuilder_ThenReusable()
{
const string Text1 = "test";
var vsb = new ValueStringBuilder();
vsb.Append(Text1);
Assert.Equal(Text1.Length, vsb.Length);
vsb.Dispose();
Assert.Equal(0, vsb.Length);
Assert.Equal(string.Empty, vsb.ToString());
Assert.True(vsb.TryCopyTo(Span<char>.Empty, out _));
const string Text2 = "another test";
vsb.Append(Text2);
Assert.Equal(Text2.Length, vsb.Length);
Assert.Equal(Text2, vsb.ToString());
}
[Fact]
public unsafe void Indexer()
{
const string Text1 = "foobar";
var vsb = new ValueStringBuilder();
vsb.Append(Text1);
Assert.Equal('b', vsb[3]);
vsb[3] = 'c';
Assert.Equal('c', vsb[3]);
}
[Fact]
public void EnsureCapacity_IfRequestedCapacityWins()
{
// Note: constants used here may be dependent on minimal buffer size
// the ArrayPool is able to return.
Span<char> initialBuffer = stackalloc char[32];
var builder = new ValueStringBuilder(initialBuffer);
builder.EnsureCapacity(65);
Assert.Equal(128, builder.Capacity);
}
[Fact]
public void EnsureCapacity_IfBufferTimesTwoWins()
{
Span<char> initialBuffer = stackalloc char[32];
var builder = new ValueStringBuilder(initialBuffer);
builder.EnsureCapacity(33);
Assert.Equal(64, builder.Capacity);
}
[Fact]
public void EnsureCapacity_NoAllocIfNotNeeded()
{
// Note: constants used here may be dependent on minimal buffer size
// the ArrayPool is able to return.
Span<char> initialBuffer = stackalloc char[64];
var builder = new ValueStringBuilder(initialBuffer);
builder.EnsureCapacity(16);
Assert.Equal(64, builder.Capacity);
}
}
}
| |
//
// ContextBackendHandler.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Alex Corrado <corrado@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using AppKit;
using CoreGraphics;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
class CGContextBackend {
public CGContext Context;
public CGSize Size;
public CGAffineTransform? InverseViewTransform;
public ContextStatus CurrentStatus = new ContextStatus ();
public double ScaleFactor = 1;
public StyleSet Styles;
}
class ContextStatus
{
public object Pattern;
public double GlobalAlpha = 1;
public ContextStatus Previous;
}
public class MacContextBackendHandler: ContextBackendHandler
{
const double degrees = System.Math.PI / 180d;
public override double GetScaleFactor (object backend)
{
var ct = (CGContextBackend) backend;
return ct.ScaleFactor;
}
public override void Save (object backend)
{
var ct = (CGContextBackend) backend;
ct.Context.SaveState ();
ct.CurrentStatus = new ContextStatus {
Pattern = ct.CurrentStatus.Pattern,
GlobalAlpha = ct.CurrentStatus.GlobalAlpha,
Previous = ct.CurrentStatus,
};
}
public override void Restore (object backend)
{
var ct = (CGContextBackend) backend;
ct.Context.RestoreState ();
if (ct.CurrentStatus.Previous != null) {
ct.CurrentStatus = ct.CurrentStatus.Previous;
}
}
public override void SetGlobalAlpha (object backend, double alpha)
{
var ct = (CGContextBackend) backend;
ct.CurrentStatus.GlobalAlpha = alpha;
ct.Context.SetAlpha ((float)alpha);
}
public override void SetStyles (object backend, StyleSet styles)
{
((CGContextBackend)backend).Styles = styles;
}
public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2)
{
CGContext ctx = ((CGContextBackend)backend).Context;
ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), false);
}
public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2)
{
CGContext ctx = ((CGContextBackend)backend).Context;
ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), true);
}
public override void Clip (object backend)
{
((CGContextBackend)backend).Context.Clip ();
}
public override void ClipPreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
using (CGPath oldPath = ctx.CopyPath ()) {
ctx.Clip ();
ctx.AddPath (oldPath);
}
}
public override void ClosePath (object backend)
{
((CGContextBackend)backend).Context.ClosePath ();
}
public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3)
{
((CGContextBackend)backend).Context.AddCurveToPoint ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3);
}
public override void Fill (object backend)
{
CGContextBackend gc = (CGContextBackend)backend;
CGContext ctx = gc.Context;
SetupContextForDrawing (ctx);
if (gc.CurrentStatus.Pattern is GradientInfo) {
MacGradientBackendHandler.Draw (ctx, ((GradientInfo)gc.CurrentStatus.Pattern));
}
else if (gc.CurrentStatus.Pattern is ImagePatternInfo) {
SetupPattern (gc);
ctx.DrawPath (CGPathDrawingMode.Fill);
}
else {
ctx.DrawPath (CGPathDrawingMode.Fill);
}
}
public override void FillPreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
using (CGPath oldPath = ctx.CopyPath ()) {
Fill (backend);
ctx.AddPath (oldPath);
}
}
public override void LineTo (object backend, double x, double y)
{
((CGContextBackend)backend).Context.AddLineToPoint ((float)x, (float)y);
}
public override void MoveTo (object backend, double x, double y)
{
((CGContextBackend)backend).Context.MoveTo ((float)x, (float)y);
}
public override void NewPath (object backend)
{
((CGContextBackend)backend).Context.BeginPath ();
}
public override void Rectangle (object backend, double x, double y, double width, double height)
{
((CGContextBackend)backend).Context.AddRect (new CGRect ((nfloat)x, (nfloat)y, (nfloat)width, (nfloat)height));
}
public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3)
{
CGContext ctx = ((CGContextBackend)backend).Context;
CGPoint p = ctx.GetPathCurrentPoint ();
ctx.AddCurveToPoint ((float)(p.X + dx1), (float)(p.Y + dy1), (float)(p.X + dx2), (float)(p.Y + dy2), (float)(p.X + dx3), (float)(p.Y + dy3));
}
public override void RelLineTo (object backend, double dx, double dy)
{
CGContext ctx = ((CGContextBackend)backend).Context;
CGPoint p = ctx.GetPathCurrentPoint ();
ctx.AddLineToPoint ((float)(p.X + dx), (float)(p.Y + dy));
}
public override void RelMoveTo (object backend, double dx, double dy)
{
CGContext ctx = ((CGContextBackend)backend).Context;
CGPoint p = ctx.GetPathCurrentPoint ();
ctx.MoveTo ((float)(p.X + dx), (float)(p.Y + dy));
}
public override void Stroke (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
ctx.DrawPath (CGPathDrawingMode.Stroke);
}
public override void StrokePreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
using (CGPath oldPath = ctx.CopyPath ()) {
ctx.DrawPath (CGPathDrawingMode.Stroke);
ctx.AddPath (oldPath);
}
}
public override void SetColor (object backend, Xwt.Drawing.Color color)
{
CGContextBackend gc = (CGContextBackend)backend;
gc.CurrentStatus.Pattern = null;
CGContext ctx = gc.Context;
ctx.SetFillColorSpace (Util.DeviceRGBColorSpace);
ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace);
ctx.SetFillColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
ctx.SetStrokeColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
}
public override void SetLineWidth (object backend, double width)
{
((CGContextBackend)backend).Context.SetLineWidth ((float)width);
}
public override void SetLineDash (object backend, double offset, params double[] pattern)
{
var array = new nfloat[pattern.Length];
for (int n=0; n<pattern.Length; n++)
array [n] = (float) pattern[n];
((CGContextBackend)backend).Context.SetLineDash ((nfloat)offset, array);
}
public override void SetPattern (object backend, object p)
{
CGContextBackend gc = (CGContextBackend)backend;
var toolkit = ApplicationContext.Toolkit;
gc.CurrentStatus.Pattern = toolkit.GetSafeBackend (p);
}
void SetupPattern (CGContextBackend gc)
{
gc.Context.SetPatternPhase (new CGSize (0, 0));
if (gc.CurrentStatus.Pattern is GradientInfo)
return;
if (gc.CurrentStatus.Pattern is ImagePatternInfo) {
var pi = (ImagePatternInfo) gc.CurrentStatus.Pattern;
var bounds = new CGRect (CGPoint.Empty, new CGSize (pi.Image.Size.Width, pi.Image.Size.Height));
var t = CGAffineTransform.Multiply (CGAffineTransform.MakeScale (1f, -1f), gc.Context.GetCTM ());
CGPattern pattern;
if (pi.Image is CustomImage) {
pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => {
c.TranslateCTM (0, bounds.Height);
c.ScaleCTM (1f, -1f);
((CustomImage)pi.Image).DrawInContext (c);
});
} else {
var empty = CGRect.Empty;
CGImage cgimg = pi.Image.AsCGImage (ref empty, null, null);
pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height,
CGPatternTiling.ConstantSpacing, true, c => c.DrawImage (bounds, cgimg));
}
CGContext ctx = gc.Context;
var alpha = new[] { (nfloat)pi.Alpha };
ctx.SetFillColorSpace (Util.PatternColorSpace);
ctx.SetStrokeColorSpace (Util.PatternColorSpace);
ctx.SetFillPattern (pattern, alpha);
ctx.SetStrokePattern (pattern, alpha);
}
}
public override void DrawTextLayout (object backend, TextLayout layout, double x, double y)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
var li = ApplicationContext.Toolkit.GetSafeBackend (layout);
MacTextLayoutBackendHandler.Draw (ctx, li, x, y);
}
public override void DrawImage (object backend, ImageDescription img, double x, double y)
{
var srcRect = new Rectangle (Point.Zero, img.Size);
var destRect = new Rectangle (x, y, img.Size.Width, img.Size.Height);
DrawImage (backend, img, srcRect, destRect);
}
public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect)
{
var cb = (CGContextBackend)backend;
CGContext ctx = cb.Context;
// Add the styles that have been globaly set to the context
img.Styles = img.Styles.AddRange (cb.Styles);
img.Alpha *= cb.CurrentStatus.GlobalAlpha;
ctx.SaveState ();
ctx.SetAlpha ((float)img.Alpha);
double rx = destRect.Width / srcRect.Width;
double ry = destRect.Height / srcRect.Height;
ctx.AddRect (new CGRect ((nfloat)destRect.X, (nfloat)destRect.Y, (nfloat)destRect.Width, (nfloat)destRect.Height));
ctx.Clip ();
ctx.TranslateCTM ((float)(destRect.X - (srcRect.X * rx)), (float)(destRect.Y - (srcRect.Y * ry)));
ctx.ScaleCTM ((float)rx, (float)ry);
NSImage image = (NSImage)img.Backend;
if (image is CustomImage) {
((CustomImage)image).DrawInContext ((CGContextBackend)backend, img);
} else {
var size = new CGSize ((nfloat)img.Size.Width, (nfloat)img.Size.Height);
var rr = new CGRect (0, 0, size.Width, size.Height);
ctx.ScaleCTM (1f, -1f);
ctx.DrawImage (new CGRect (0, -size.Height, size.Width, size.Height), image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null));
}
ctx.RestoreState ();
}
public override void Rotate (object backend, double angle)
{
((CGContextBackend)backend).Context.RotateCTM ((float)(angle * degrees));
}
public override void Scale (object backend, double scaleX, double scaleY)
{
((CGContextBackend)backend).Context.ScaleCTM ((float)scaleX, (float)scaleY);
}
public override void Translate (object backend, double tx, double ty)
{
((CGContextBackend)backend).Context.TranslateCTM ((float)tx, (float)ty);
}
public override void ModifyCTM (object backend, Matrix m)
{
CGAffineTransform t = new CGAffineTransform ((float)m.M11, (float)m.M12,
(float)m.M21, (float)m.M22,
(float)m.OffsetX, (float)m.OffsetY);
((CGContextBackend)backend).Context.ConcatCTM (t);
}
public override Matrix GetCTM (object backend)
{
CGAffineTransform t = GetContextTransform ((CGContextBackend)backend);
Matrix ctm = new Matrix (t.xx, t.yx, t.xy, t.yy, t.x0, t.y0);
return ctm;
}
public override object CreatePath ()
{
return new CGPath ();
}
public override object CopyPath (object backend)
{
return ((CGContextBackend)backend).Context.CopyPath ();
}
public override void AppendPath (object backend, object otherBackend)
{
CGContext dest = ((CGContextBackend)backend).Context;
CGContextBackend src = otherBackend as CGContextBackend;
if (src != null) {
using (var path = src.Context.CopyPath ())
dest.AddPath (path);
} else {
dest.AddPath ((CGPath)otherBackend);
}
}
public override bool IsPointInFill (object backend, double x, double y)
{
return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Fill);
}
public override bool IsPointInStroke (object backend, double x, double y)
{
return ((CGContextBackend)backend).Context.PathContainsPoint (new CGPoint ((nfloat)x, (nfloat)y), CGPathDrawingMode.Stroke);
}
public override void Dispose (object backend)
{
((CGContextBackend)backend).Context.Dispose ();
}
static CGAffineTransform GetContextTransform (CGContextBackend gc)
{
CGAffineTransform t = gc.Context.GetCTM ();
// The CTM returned above actually includes the full view transform.
// We only want the transform that is applied to the context, so concat
// the inverse of the view transform to nullify that part.
if (gc.InverseViewTransform.HasValue)
t.Multiply (gc.InverseViewTransform.Value);
return t;
}
static void SetupContextForDrawing (CGContext ctx)
{
if (ctx.IsPathEmpty ())
return;
// setup pattern drawing to better match the behavior of Cairo
var drawPoint = ctx.GetCTM ().TransformPoint (ctx.GetPathBoundingBox ().Location);
var patternPhase = new CGSize (drawPoint.X, drawPoint.Y);
if (patternPhase != CGSize.Empty)
ctx.SetPatternPhase (patternPhase);
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: ApplicationGesture.cs
//
// Description:
// The definition of ApplicationGesture enum type
//
// Features:
//
// History:
// 01/14/2005 waynezen: Created
//
// Copyright (C) 2001 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
namespace System.Windows.Ink
{
/// <summary>
/// ApplicationGesture
/// </summary>
public enum ApplicationGesture
{
/// <summary>
/// AllGestures
/// </summary>
AllGestures = 0,
/// <summary>
/// ArrowDown
/// </summary>
ArrowDown = 61497,
/// <summary>
/// ArrowLeft
/// </summary>
ArrowLeft = 61498,
/// <summary>
/// ArrowRight
/// </summary>
ArrowRight = 61499,
/// <summary>
/// ArrowUp
/// </summary>
ArrowUp = 61496,
/// <summary>
/// Check
/// </summary>
Check = 61445,
/// <summary>
/// ChevronDown
/// </summary>
ChevronDown = 61489,
/// <summary>
/// ChevronLeft
/// </summary>
ChevronLeft = 61490,
/// <summary>
/// ChevronRight
/// </summary>
ChevronRight = 61491,
/// <summary>
/// ChevronUp
/// </summary>
ChevronUp = 61488,
/// <summary>
/// Circle
/// </summary>
Circle = 61472,
/// <summary>
/// Curlicue
/// </summary>
Curlicue = 61456,
/// <summary>
/// DoubleCircle
/// </summary>
DoubleCircle = 61473,
/// <summary>
/// DoubleCurlicue
/// </summary>
DoubleCurlicue = 61457,
/// <summary>
/// DoubleTap
/// </summary>
DoubleTap = 61681,
/// <summary>
/// Down
/// </summary>
Down = 61529,
/// <summary>
/// DownLeft
/// </summary>
DownLeft = 61546,
/// <summary>
/// DownLeftLong
/// </summary>
DownLeftLong = 61542,
/// <summary>
/// DownRight
/// </summary>
DownRight = 61547,
/// <summary>
/// DownRightLong
/// </summary>
DownRightLong = 61543,
/// <summary>
/// DownUp
/// </summary>
DownUp = 61537,
/// <summary>
/// Exclamation
/// </summary>
Exclamation = 61604,
/// <summary>
/// Left
/// </summary>
Left = 61530,
/// <summary>
/// LeftDown
/// </summary>
LeftDown = 61549,
/// <summary>
/// LeftRight
/// </summary>
LeftRight = 61538,
/// <summary>
/// LeftUp
/// </summary>
LeftUp = 61548,
/// <summary>
/// NoGesture
/// </summary>
NoGesture = 61440,
/// <summary>
/// Right
/// </summary>
Right = 61531,
/// <summary>
/// RightDown
/// </summary>
RightDown = 61551,
/// <summary>
/// RightLeft
/// </summary>
RightLeft = 61539,
/// <summary>
/// RightUp
/// </summary>
RightUp = 61550,
/// <summary>
/// ScratchOut
/// </summary>
ScratchOut = 61441,
/// <summary>
/// SemicircleLeft
/// </summary>
SemicircleLeft = 61480,
/// <summary>
/// SemicircleRight
/// </summary>
SemicircleRight = 61481,
/// <summary>
/// Square
/// </summary>
Square = 61443,
/// <summary>
/// Star
/// </summary>
Star = 61444,
/// <summary>
/// Tap
/// </summary>
Tap = 61680,
/// <summary>
/// Triangle
/// </summary>
Triangle = 61442,
/// <summary>
/// Up
/// </summary>
Up = 61528,
/// <summary>
/// UpDown
/// </summary>
UpDown = 61536,
/// <summary>
/// UpLeft
/// </summary>
UpLeft = 61544,
/// <summary>
/// UpLeftLong
/// </summary>
UpLeftLong = 61540,
/// <summary>
/// UpRight
/// </summary>
UpRight = 61545,
/// <summary>
/// UpRightLong
/// </summary>
UpRightLong = 61541
}
// Whenever the ApplicationGesture is modified, please update this ApplicationGestureHelper.IsDefined.
internal static class ApplicationGestureHelper
{
// the number of enums defined, used by NativeRecognizer
// to limit input
internal static readonly int CountOfValues = 44;
// Helper like Enum.IsDefined, for ApplicationGesture. It is an fxcop violation
// to use Enum.IsDefined (for perf reasons)
internal static bool IsDefined(ApplicationGesture applicationGesture)
{
//note that we can't just check the upper and lower bounds since the app gesture
//values are not contiguous
switch(applicationGesture)
{
case ApplicationGesture.AllGestures:
case ApplicationGesture.ArrowDown:
case ApplicationGesture.ArrowLeft:
case ApplicationGesture.ArrowRight:
case ApplicationGesture.ArrowUp:
case ApplicationGesture.Check:
case ApplicationGesture.ChevronDown:
case ApplicationGesture.ChevronLeft:
case ApplicationGesture.ChevronRight:
case ApplicationGesture.ChevronUp:
case ApplicationGesture.Circle:
case ApplicationGesture.Curlicue:
case ApplicationGesture.DoubleCircle:
case ApplicationGesture.DoubleCurlicue:
case ApplicationGesture.DoubleTap:
case ApplicationGesture.Down:
case ApplicationGesture.DownLeft:
case ApplicationGesture.DownLeftLong:
case ApplicationGesture.DownRight:
case ApplicationGesture.DownRightLong:
case ApplicationGesture.DownUp:
case ApplicationGesture.Exclamation:
case ApplicationGesture.Left:
case ApplicationGesture.LeftDown:
case ApplicationGesture.LeftRight:
case ApplicationGesture.LeftUp:
case ApplicationGesture.NoGesture:
case ApplicationGesture.Right:
case ApplicationGesture.RightDown:
case ApplicationGesture.RightLeft:
case ApplicationGesture.RightUp:
case ApplicationGesture.ScratchOut:
case ApplicationGesture.SemicircleLeft:
case ApplicationGesture.SemicircleRight:
case ApplicationGesture.Square:
case ApplicationGesture.Star:
case ApplicationGesture.Tap:
case ApplicationGesture.Triangle:
case ApplicationGesture.Up:
case ApplicationGesture.UpDown:
case ApplicationGesture.UpLeft:
case ApplicationGesture.UpLeftLong:
case ApplicationGesture.UpRight:
case ApplicationGesture.UpRightLong:
{
return true;
}
default:
{
return false;
}
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace Craft.Net.Common
{
/// <summary>
/// Represents the location of an object in 3D space.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Vector3 : IEquatable<Vector3>
{
[FieldOffset(0)]
public double X;
[FieldOffset(8)]
public double Y;
[FieldOffset(16)]
public double Z;
public Vector3(double value)
{
X = Y = Z = value;
}
public Vector3(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public Vector3(Vector3 v)
{
X = v.X;
Y = v.Y;
Z = v.Z;
}
/// <summary>
/// Converts this Vector3 to a string in the format <x, y, z>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("<{0},{1},{2}>", X, Y, Z);
}
#region Math
/// <summary>
/// Truncates the decimal component of each part of this Vector3.
/// </summary>
public Vector3 Floor()
{
return new Vector3(Math.Floor(X), Math.Floor(Y), Math.Floor(Z));
}
/// <summary>
/// Calculates the distance between two Vector3 objects.
/// </summary>
public double DistanceTo(Vector3 other)
{
return Math.Sqrt(Square(other.X - X) +
Square(other.Y - Y) +
Square(other.Z - Z));
}
/// <summary>
/// Calculates the square of a num.
/// </summary>
private double Square(double num)
{
return num * num;
}
/// <summary>
/// Finds the distance of this vector from Vector3.Zero
/// </summary>
public double Distance
{
get
{
return DistanceTo(Zero);
}
}
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z)
);
}
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z)
);
}
#endregion
#region Operators
public static bool operator !=(Vector3 a, Vector3 b)
{
return !a.Equals(b);
}
public static bool operator ==(Vector3 a, Vector3 b)
{
return a.Equals(b);
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(
a.X + b.X,
a.Y + b.Y,
a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(
a.X - b.X,
a.Y - b.Y,
a.Z - b.Z);
}
public static Vector3 operator +(Vector3 a, Size b)
{
return new Vector3(
a.X + b.Width,
a.Y + b.Height,
a.Z + b.Depth);
}
public static Vector3 operator -(Vector3 a, Size b)
{
return new Vector3(
a.X - b.Width,
a.Y - b.Height,
a.Z - b.Depth);
}
public static Vector3 operator -(Vector3 a)
{
return new Vector3(
-a.X,
-a.Y,
-a.Z);
}
public static Vector3 operator *(Vector3 a, Vector3 b)
{
return new Vector3(
a.X * b.X,
a.Y * b.Y,
a.Z * b.Z);
}
public static Vector3 operator /(Vector3 a, Vector3 b)
{
return new Vector3(
a.X / b.X,
a.Y / b.Y,
a.Z / b.Z);
}
public static Vector3 operator %(Vector3 a, Vector3 b)
{
return new Vector3(a.X % b.X, a.Y % b.Y, a.Z % b.Z);
}
public static Vector3 operator +(Vector3 a, double b)
{
return new Vector3(
a.X + b,
a.Y + b,
a.Z + b);
}
public static Vector3 operator -(Vector3 a, double b)
{
return new Vector3(
a.X - b,
a.Y - b,
a.Z - b);
}
public static Vector3 operator *(Vector3 a, double b)
{
return new Vector3(
a.X * b,
a.Y * b,
a.Z * b);
}
public static Vector3 operator /(Vector3 a, double b)
{
return new Vector3(
a.X / b,
a.Y / b,
a.Z / b);
}
public static Vector3 operator %(Vector3 a, double b)
{
return new Vector3(a.X % b, a.Y % b, a.Y % b);
}
public static Vector3 operator +(double a, Vector3 b)
{
return new Vector3(
a + b.X,
a + b.Y,
a + b.Z);
}
public static Vector3 operator -(double a, Vector3 b)
{
return new Vector3(
a - b.X,
a - b.Y,
a - b.Z);
}
public static Vector3 operator *(double a, Vector3 b)
{
return new Vector3(
a * b.X,
a * b.Y,
a * b.Z);
}
public static Vector3 operator /(double a, Vector3 b)
{
return new Vector3(
a / b.X,
a / b.Y,
a / b.Z);
}
public static Vector3 operator %(double a, Vector3 b)
{
return new Vector3(a % b.X, a % b.Y, a % b.Y);
}
#endregion
#region Constants
public static readonly Vector3 Zero = new Vector3(0);
public static readonly Vector3 One = new Vector3(1);
public static readonly Vector3 Up = new Vector3(0, 1, 0);
public static readonly Vector3 Down = new Vector3(0, -1, 0);
public static readonly Vector3 Left = new Vector3(-1, 0, 0);
public static readonly Vector3 Right = new Vector3(1, 0, 0);
public static readonly Vector3 Backwards = new Vector3(0, 0, -1);
public static readonly Vector3 Forwards = new Vector3(0, 0, 1);
public static readonly Vector3 East = new Vector3(1, 0, 0);
public static readonly Vector3 West = new Vector3(-1, 0, 0);
public static readonly Vector3 North = new Vector3(0, 0, -1);
public static readonly Vector3 South = new Vector3(0, 0, 1);
#endregion
public bool Equals(Vector3 other)
{
return other.X.Equals(X) && other.Y.Equals(Y) && other.Z.Equals(Z);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(Vector3)) return false;
return Equals((Vector3)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = X.GetHashCode();
result = (result * 397) ^ Y.GetHashCode();
result = (result * 397) ^ Z.GetHashCode();
return result;
}
}
}
}
| |
//
// Derived from
// Mono.Data.Sqlite.SQLiteFunction.cs
//
// Author(s):
// Robert Simpson (robert@blackcastlesoft.com)
//
// Adapted and modified for the Mono Project by
// Marek Habersack (grendello@gmail.com)
//
// Adapted and modified for the Hyena by
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2006,2010 Novell, Inc (http://www.novell.com)
// Copyright (C) 2007 Marek Habersack
//
// 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.
//
/********************************************************
* ADO.NET 2.0 Data Provider for Sqlite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Hyena.Data.Sqlite
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
/// <summary>
/// The type of user-defined function to declare
/// </summary>
public enum FunctionType
{
/// <summary>
/// Scalar functions are designed to be called and return a result immediately. Examples include ABS(), Upper(), Lower(), etc.
/// </summary>
Scalar = 0,
/// <summary>
/// Aggregate functions are designed to accumulate data until the end of a call and then return a result gleaned from the accumulated data.
/// Examples include SUM(), COUNT(), AVG(), etc.
/// </summary>
Aggregate = 1,
/// <summary>
/// Collation sequences are used to sort textual data in a custom manner, and appear in an ORDER BY clause. Typically text in an ORDER BY is
/// sorted using a straight case-insensitive comparison function. Custom collating sequences can be used to alter the behavior of text sorting
/// in a user-defined manner.
/// </summary>
Collation = 2,
}
/// <summary>
/// An internal callback delegate declaration.
/// </summary>
/// <param name="context">Raw context pointer for the user function</param>
/// <param name="nArgs">Count of arguments to the function</param>
/// <param name="argsptr">A pointer to the array of argument pointers</param>
internal delegate void SqliteCallback(IntPtr context, int nArgs, IntPtr argsptr);
/// <summary>
/// An internal callback delegate declaration.
/// </summary>
/// <param name="context">Raw context pointer for the user function</param>
internal delegate void SqliteFinalCallback(IntPtr context);
/// <summary>
/// Internal callback delegate for implementing collation sequences
/// </summary>
/// <param name="len1">Length of the string pv1</param>
/// <param name="pv1">Pointer to the first string to compare</param>
/// <param name="len2">Length of the string pv2</param>
/// <param name="pv2">Pointer to the second string to compare</param>
/// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater
/// than the second.</returns>
internal delegate int SqliteCollation(int len1, IntPtr pv1, int len2, IntPtr pv2);
/// <summary>
/// This abstract class is designed to handle user-defined functions easily. An instance of the derived class is made for each
/// connection to the database.
/// </summary>
/// <remarks>
/// Although there is one instance of a class derived from SqliteFunction per database connection, the derived class has no access
/// to the underlying connection. This is necessary to deter implementers from thinking it would be a good idea to make database
/// calls during processing.
///
/// It is important to distinguish between a per-connection instance, and a per-SQL statement context. One instance of this class
/// services all SQL statements being stepped through on that connection, and there can be many. One should never store per-statement
/// information in member variables of user-defined function classes.
///
/// For aggregate functions, always create and store your per-statement data in the contextData object on the 1st step. This data will
/// be automatically freed for you (and Dispose() called if the item supports IDisposable) when the statement completes.
/// </remarks>
public abstract class SqliteFunction : IDisposable
{
/// <summary>
/// The base connection this function is attached to
/// </summary>
/// <summary>
/// Internal array used to keep track of aggregate function context data
/// </summary>
private Dictionary<long, object> _contextDataList;
/// <summary>
/// Holds a reference to the callback function for user functions
/// </summary>
internal SqliteCallback _InvokeFunc;
/// <summary>
/// Holds a reference to the callbakc function for stepping in an aggregate function
/// </summary>
internal SqliteCallback _StepFunc;
/// <summary>
/// Holds a reference to the callback function for finalizing an aggregate function
/// </summary>
internal SqliteFinalCallback _FinalFunc;
/// <summary>
/// Holds a reference to the callback function for collation sequences
/// </summary>
internal SqliteCollation _CompareFunc;
/// <summary>
/// Internal constructor, initializes the function's internal variables.
/// </summary>
protected SqliteFunction()
{
_contextDataList = new Dictionary<long, object>();
}
/// <summary>
/// Scalar functions override this method to do their magic.
/// </summary>
/// <remarks>
/// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available
/// to force them into a certain type. Therefore the only types you will ever see as parameters are
/// DBNull.Value, Int64, Double, String or byte[] array.
/// </remarks>
/// <param name="args">The arguments for the command to process</param>
/// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or
/// you may return an Exception-derived class if you wish to return an error to Sqlite. Do not actually throw the error,
/// just return it!</returns>
public virtual object Invoke(object[] args)
{
return null;
}
/// <summary>
/// Aggregate functions override this method to do their magic.
/// </summary>
/// <remarks>
/// Typically you'll be updating whatever you've placed in the contextData field and returning as quickly as possible.
/// </remarks>
/// <param name="args">The arguments for the command to process</param>
/// <param name="stepNumber">The 1-based step number. This is incrememted each time the step method is called.</param>
/// <param name="contextData">A placeholder for implementers to store contextual data pertaining to the current context.</param>
public virtual void Step(object[] args, int stepNumber, ref object contextData)
{
}
/// <summary>
/// Aggregate functions override this method to finish their aggregate processing.
/// </summary>
/// <remarks>
/// If you implemented your aggregate function properly,
/// you've been recording and keeping track of your data in the contextData object provided, and now at this stage you should have
/// all the information you need in there to figure out what to return.
/// NOTE: It is possible to arrive here without receiving a previous call to Step(), in which case the contextData will
/// be null. This can happen when no rows were returned. You can either return null, or 0 or some other custom return value
/// if that is the case.
/// </remarks>
/// <param name="contextData">Your own assigned contextData, provided for you so you can return your final results.</param>
/// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or
/// you may return an Exception-derived class if you wish to return an error to Sqlite. Do not actually throw the error,
/// just return it!
/// </returns>
public virtual object Final(object contextData)
{
return null;
}
/// <summary>
/// User-defined collation sequences override this method to provide a custom string sorting algorithm.
/// </summary>
/// <param name="param1">The first string to compare</param>
/// <param name="param2">The second strnig to compare</param>
/// <returns>1 if param1 is greater than param2, 0 if they are equal, or -1 if param1 is less than param2</returns>
public virtual int Compare(string param1, string param2)
{
return 0;
}
/// <summary>
/// Converts an IntPtr array of context arguments to an object array containing the resolved parameters the pointers point to.
/// </summary>
/// <remarks>
/// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available
/// to force them into a certain type. Therefore the only types you will ever see as parameters are
/// DBNull.Value, Int64, Double, String or byte[] array.
/// </remarks>
/// <param name="nArgs">The number of arguments</param>
/// <param name="argsptr">A pointer to the array of arguments</param>
/// <returns>An object array of the arguments once they've been converted to .NET values</returns>
internal object[] ConvertParams(int nArgs, IntPtr argsptr)
{
object[] parms = new object[nArgs];
IntPtr[] argint = new IntPtr[nArgs];
Marshal.Copy(argsptr, argint, 0, nArgs);
for (int n = 0; n < nArgs; n++) {
IntPtr valPtr = (IntPtr)argint[n];
int type = Native.sqlite3_value_type (valPtr);
switch (type) {
case SQLITE_INTEGER:
parms[n] = Native.sqlite3_value_int64 (valPtr);
break;
case SQLITE_FLOAT:
parms[n] = Native.sqlite3_value_double (valPtr);
break;
case SQLITE3_TEXT:
parms[n] = Native.sqlite3_value_text16 (valPtr).PtrToString ();
break;
case SQLITE_BLOB:
parms[n] = Native.sqlite3_value_blob (valPtr);
break;
case SQLITE_NULL:
parms[n] = null;
break;
default:
throw new Exception (String.Format ("Value is of unknown type {0}", type));
}
}
return parms;
}
/// <summary>
/// Takes the return value from Invoke() and Final() and figures out how to return it to Sqlite's context.
/// </summary>
/// <param name="context">The context the return value applies to</param>
/// <param name="returnValue">The parameter to return to Sqlite</param>
void SetReturnValue(IntPtr context, object r)
{
if (r is Exception) {
Native.sqlite3_result_error16 (context, ((Exception)r).Message, -1);
} else {
var o = SqliteUtils.ToDbFormat (r);
if (o == null)
Native.sqlite3_result_null (context);
else if (r is int || r is uint)
Native.sqlite3_result_int (context, (int)r);
else if (r is long || r is ulong)
Native.sqlite3_result_int64 (context, (long)r);
else if (r is double || r is float)
Native.sqlite3_result_double (context, (double)r);
else if (r is string) {
string str = (string)r;
// -1 for the last arg is the TRANSIENT destructor type so that sqlite will make its own copy of the string
Native.sqlite3_result_text16 (context, str, str.Length*2, (IntPtr)(-1));
} else if (r is byte[]) {
var bytes = (byte[])r;
Native.sqlite3_result_blob (context, bytes, bytes.Length, (IntPtr)(-1));
}
}
}
/// <summary>
/// Internal scalar callback function, which wraps the raw context pointer and calls the virtual Invoke() method.
/// </summary>
/// <param name="context">A raw context pointer</param>
/// <param name="nArgs">Number of arguments passed in</param>
/// <param name="argsptr">A pointer to the array of arguments</param>
internal void ScalarCallback(IntPtr context, int nArgs, IntPtr argsptr)
{
SetReturnValue(context, Invoke(ConvertParams(nArgs, argsptr)));
}
/// <summary>
/// Internal collation sequence function, which wraps up the raw string pointers and executes the Compare() virtual function.
/// </summary>
/// <param name="len1">Length of the string pv1</param>
/// <param name="ptr1">Pointer to the first string to compare</param>
/// <param name="len2">Length of the string pv2</param>
/// <param name="ptr2">Pointer to the second string to compare</param>
/// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater
/// than the second.</returns>
internal int CompareCallback(int len1, IntPtr ptr1, int len2, IntPtr ptr2)
{
return Compare(ptr1.PtrToString (), ptr2.PtrToString ());
}
/// <summary>
/// The internal aggregate Step function callback, which wraps the raw context pointer and calls the virtual Step() method.
/// </summary>
/// <remarks>
/// This function takes care of doing the lookups and getting the important information put together to call the Step() function.
/// That includes pulling out the user's contextData and updating it after the call is made. We use a sorted list for this so
/// binary searches can be done to find the data.
/// </remarks>
/// <param name="context">A raw context pointer</param>
/// <param name="nArgs">Number of arguments passed in</param>
/// <param name="argsptr">A pointer to the array of arguments</param>
internal void StepCallback(IntPtr context, int nArgs, IntPtr argsptr)
{
int n = Native.sqlite3_aggregate_count (context);
long nAux;
object obj = null;
nAux = (long)Native.sqlite3_aggregate_context (context, 1);
if (n > 1) obj = _contextDataList[nAux];
Step(ConvertParams(nArgs, argsptr), n, ref obj);
_contextDataList[nAux] = obj;
}
/// <summary>
/// An internal aggregate Final function callback, which wraps the context pointer and calls the virtual Final() method.
/// </summary>
/// <param name="context">A raw context pointer</param>
internal void FinalCallback(IntPtr context)
{
long n = (long)Native.sqlite3_aggregate_context (context, 1);
object obj = null;
if (_contextDataList.ContainsKey(n))
{
obj = _contextDataList[n];
_contextDataList.Remove(n);
}
SetReturnValue(context, Final(obj));
IDisposable disp = obj as IDisposable;
if (disp != null) disp.Dispose();
}
/// <summary>
/// Placeholder for a user-defined disposal routine
/// </summary>
/// <param name="disposing">True if the object is being disposed explicitly</param>
protected virtual void Dispose(bool disposing)
{
}
/// <summary>
/// Disposes of any active contextData variables that were not automatically cleaned up. Sometimes this can happen if
/// someone closes the connection while a DataReader is open.
/// </summary>
public void Dispose()
{
Dispose(true);
IDisposable disp;
foreach (KeyValuePair<long, object> kv in _contextDataList)
{
disp = kv.Value as IDisposable;
if (disp != null)
disp.Dispose();
}
_contextDataList.Clear();
_InvokeFunc = null;
_StepFunc = null;
_FinalFunc = null;
_CompareFunc = null;
_contextDataList = null;
GC.SuppressFinalize(this);
}
const int SQLITE_INTEGER = 1;
const int SQLITE_FLOAT = 2;
const int SQLITE3_TEXT = 3;
const int SQLITE_BLOB = 4;
const int SQLITE_NULL = 5;
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="LegacyAspNetSynchronizationContext.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Runtime.ExceptionServices;
using System.Security.Permissions;
using System.Threading;
using System.Web;
using System.Web.Util;
namespace System.Web {
// Represents a SynchronizationContext that has legacy behavior (<= FX 4.0) when it comes to asynchronous operations.
// Characterized by locking on the HttpApplication to synchronize work, dispatching Posts as Sends.
internal sealed class LegacyAspNetSynchronizationContext : AspNetSynchronizationContextBase {
private HttpApplication _application;
private Action<bool> _appVerifierCallback;
private bool _disabled;
private bool _syncCaller;
private bool _invalidOperationEncountered;
private int _pendingCount;
private ExceptionDispatchInfo _error;
private WaitCallback _lastCompletionCallback;
private object _lastCompletionCallbackLock;
internal LegacyAspNetSynchronizationContext(HttpApplication app) {
_application = app;
_appVerifierCallback = AppVerifier.GetSyncContextCheckDelegate(app);
_lastCompletionCallbackLock = new object();
}
private void CheckForRequestStateIfRequired() {
if (_appVerifierCallback != null) {
_appVerifierCallback(false);
}
}
private void CallCallback(SendOrPostCallback callback, Object state) {
CheckForRequestStateIfRequired();
// don't take app lock for [....] caller to avoid deadlocks in case they poll for result
if (_syncCaller) {
CallCallbackPossiblyUnderLock(callback, state);
}
else {
lock (_application) {
CallCallbackPossiblyUnderLock(callback, state);
}
}
}
private void CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state) {
ThreadContext threadContext = null;
try {
threadContext = _application.OnThreadEnter();
try {
callback(state);
}
catch (Exception e) {
_error = ExceptionDispatchInfo.Capture(e);
}
}
finally {
if (threadContext != null) {
threadContext.DisassociateFromCurrentThread();
}
}
}
// this property no-ops using the legacy [....] context
internal override bool AllowAsyncDuringSyncStages {
get;
set;
}
internal override int PendingOperationsCount {
get { return _pendingCount; }
}
internal override ExceptionDispatchInfo ExceptionDispatchInfo {
get { return _error; }
}
internal override void ClearError() {
_error = null;
}
// Dev11 Bug 70908: Race condition involving SynchronizationContext allows ASP.NET requests to be abandoned in the pipeline
//
// When the last completion occurs, the _pendingCount is decremented and then the _lastCompletionCallbackLock is acquired to get
// the _lastCompletionCallback. If the _lastCompletionCallback is non-null, then the last completion will invoke the callback;
// otherwise, the caller of PendingCompletion will handle the completion.
internal override bool PendingCompletion(WaitCallback callback) {
Debug.Assert(_lastCompletionCallback == null); // only one at a time
bool pending = false;
if (_pendingCount != 0) {
lock (_lastCompletionCallbackLock) {
if (_pendingCount != 0) {
pending = true;
_lastCompletionCallback = callback;
}
}
}
return pending;
}
public override void Send(SendOrPostCallback callback, Object state) {
#if DBG
Debug.Trace("Async", "Send");
Debug.Trace("AsyncStack", "Send from:\r\n" + GetDebugStackTrace());
#endif
CallCallback(callback, state);
}
public override void Post(SendOrPostCallback callback, Object state) {
#if DBG
Debug.Trace("Async", "Post");
Debug.Trace("AsyncStack", "Post from:\r\n" + GetDebugStackTrace());
#endif
CallCallback(callback, state);
}
#if DBG
[EnvironmentPermission(SecurityAction.Assert, Unrestricted=true)]
private void CreateCopyDumpStack() {
Debug.Trace("Async", "CreateCopy");
Debug.Trace("AsyncStack", "CreateCopy from:\r\n" + GetDebugStackTrace());
}
#endif
public override SynchronizationContext CreateCopy() {
#if DBG
CreateCopyDumpStack();
#endif
LegacyAspNetSynchronizationContext context = new LegacyAspNetSynchronizationContext(_application);
context._disabled = _disabled;
context._syncCaller = _syncCaller;
context.AllowAsyncDuringSyncStages = AllowAsyncDuringSyncStages;
return context;
}
public override void OperationStarted() {
if (_invalidOperationEncountered || (_disabled && _pendingCount == 0)) {
_invalidOperationEncountered = true;
throw new InvalidOperationException(SR.GetString(SR.Async_operation_disabled));
}
Interlocked.Increment(ref _pendingCount);
#if DBG
Debug.Trace("Async", "OperationStarted(count=" + _pendingCount + ")");
Debug.Trace("AsyncStack", "OperationStarted(count=" + _pendingCount + ") from:\r\n" + GetDebugStackTrace());
#endif
}
public override void OperationCompleted() {
if (_invalidOperationEncountered || (_disabled && _pendingCount == 0)) {
// throw from operation started could cause extra operation completed
return;
}
int pendingCount = Interlocked.Decrement(ref _pendingCount);
#if DBG
Debug.Trace("Async", "OperationCompleted(pendingCount=" + pendingCount + ")");
Debug.Trace("AsyncStack", "OperationCompleted(pendingCount=" + pendingCount + ") from:\r\n" + GetDebugStackTrace());
#endif
// notify (once) about the last completion to resume the async work
if (pendingCount == 0) {
WaitCallback callback = null;
lock (_lastCompletionCallbackLock) {
callback = _lastCompletionCallback;
_lastCompletionCallback = null;
}
if (callback != null) {
Debug.Trace("Async", "Queueing LastCompletionWorkItemCallback");
ThreadPool.QueueUserWorkItem(callback);
}
}
}
internal override bool Enabled {
get { return !_disabled; }
}
internal override void Enable() {
_disabled = false;
}
internal override void Disable() {
_disabled = true;
}
internal override void SetSyncCaller() {
_syncCaller = true;
}
internal override void ResetSyncCaller() {
_syncCaller = false;
}
internal override void AssociateWithCurrentThread() {
Monitor.Enter(_application);
}
internal override void DisassociateFromCurrentThread() {
Monitor.Exit(_application);
}
#if DBG
[EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
private static string GetDebugStackTrace() {
return Environment.StackTrace;
}
#endif
}
}
| |
// 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.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
// TODO: Once we upgrade to C# 6, remove all of these and simply import the Http class.
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
using CURLMcode = Interop.Http.CURLMcode;
using CURLMSG = Interop.Http.CURLMSG;
using CURLoption = Interop.Http.CURLoption;
using SafeCurlMultiHandle = Interop.Http.SafeCurlMultiHandle;
using CurlSeekResult = Interop.Http.CurlSeekResult;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides a multi handle and the associated processing for all requests on the handle.</summary>
private sealed class MultiAgent
{
private static readonly Interop.Http.ReadWriteCallback s_receiveHeadersCallback = CurlReceiveHeadersCallback;
private static readonly Interop.Http.ReadWriteCallback s_sendCallback = CurlSendCallback;
private static readonly Interop.Http.SeekCallback s_seekCallback = CurlSeekCallback;
private static readonly Interop.Http.ReadWriteCallback s_receiveBodyCallback = CurlReceiveBodyCallback;
private static readonly Interop.Http.DebugCallback s_debugCallback = CurlDebugFunction;
/// <summary>
/// A collection of not-yet-processed incoming requests for work to be done
/// by this multi agent. This can include making new requests, canceling
/// active requests, or unpausing active requests.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private readonly Queue<IncomingRequest> _incomingRequests = new Queue<IncomingRequest>();
/// <summary>Map of activeOperations, indexed by a GCHandle ptr.</summary>
private readonly Dictionary<IntPtr, ActiveRequest> _activeOperations = new Dictionary<IntPtr, ActiveRequest>();
/// <summary>
/// Special file descriptor used to wake-up curl_multi_wait calls. This is the read
/// end of a pipe, with the write end written to when work is queued or when cancellation
/// is requested. This is only valid while the worker is executing.
/// </summary>
private SafeFileHandle _wakeupRequestedPipeFd;
/// <summary>
/// Write end of the pipe connected to <see cref="_wakeupRequestedPipeFd"/>.
/// This is only valid while the worker is executing.
/// </summary>
private SafeFileHandle _requestWakeupPipeFd;
/// <summary>
/// Task for the currently running worker, or null if there is no current worker.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private Task _runningWorker;
/// <summary>Queues a request for the multi handle to process.</summary>
public void Queue(IncomingRequest request)
{
lock (_incomingRequests)
{
// Add the request, then initiate processing.
_incomingRequests.Enqueue(request);
EnsureWorkerIsRunning();
}
}
/// <summary>Gets the ID of the currently running worker, or null if there isn't one.</summary>
internal int? RunningWorkerId { get { return _runningWorker != null ? (int?)_runningWorker.Id : null; } }
/// <summary>Schedules the processing worker if one hasn't already been scheduled.</summary>
private void EnsureWorkerIsRunning()
{
Debug.Assert(Monitor.IsEntered(_incomingRequests), "Needs to be called under _incomingRequests lock");
if (_runningWorker == null)
{
EventSourceTrace("MultiAgent worker queueing");
// Create pipe used to forcefully wake up curl_multi_wait calls when something important changes.
// This is created here rather than in Process so that the pipe is available immediately
// for subsequent queue calls to use.
Debug.Assert(_wakeupRequestedPipeFd == null, "Read pipe should have been cleared");
Debug.Assert(_requestWakeupPipeFd == null, "Write pipe should have been cleared");
unsafe
{
int* fds = stackalloc int[2];
Interop.CheckIo(Interop.Sys.Pipe(fds));
_wakeupRequestedPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.ReadEndOfPipe], true);
_requestWakeupPipeFd = new SafeFileHandle((IntPtr)fds[Interop.Sys.WriteEndOfPipe], true);
}
// Kick off the processing task. It's "DenyChildAttach" to avoid any surprises if
// code happens to create attached tasks, and it's LongRunning because this thread
// is likely going to sit around for a while in a wait loop (and the more requests
// are concurrently issued to the same agent, the longer the thread will be around).
const TaskCreationOptions Options = TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning;
_runningWorker = new Task(s =>
{
var thisRef = (MultiAgent)s;
try
{
// Do the actual processing
thisRef.EventSourceTrace("MultiAgent worker running");
thisRef.WorkerLoop();
}
catch (Exception exc)
{
thisRef.EventSourceTrace("Unexpected worker failure: {0}", exc);
Debug.Fail("Unexpected exception from processing loop: " + exc.ToString());
}
finally
{
thisRef.EventSourceTrace("MultiAgent worker shutting down");
lock (thisRef._incomingRequests)
{
// Close our wakeup pipe (ignore close errors).
// This is done while holding the lock to prevent
// subsequent Queue calls to see an improperly configured
// set of descriptors.
thisRef._wakeupRequestedPipeFd.Dispose();
thisRef._wakeupRequestedPipeFd = null;
thisRef._requestWakeupPipeFd.Dispose();
thisRef._requestWakeupPipeFd = null;
// In the time between we stopped processing and now,
// more requests could have been added. If they were
// kick off another processing loop.
thisRef._runningWorker = null;
if (thisRef._incomingRequests.Count > 0)
{
thisRef.EnsureWorkerIsRunning();
}
}
}
}, this, CancellationToken.None, Options);
_runningWorker.Start(TaskScheduler.Default); // started after _runningWorker field set to avoid race conditions
}
else // _workerRunning == true
{
// The worker is already running. If there are already queued requests, we're done.
// However, if there aren't any queued requests, Process could be blocked inside of
// curl_multi_wait, and we want to make sure it wakes up to see that there additional
// requests waiting to be handled. So we write to the wakeup pipe.
Debug.Assert(_incomingRequests.Count >= 1, "We just queued a request, so the count should be at least 1");
if (_incomingRequests.Count == 1)
{
RequestWakeup();
}
}
}
/// <summary>Write a byte to the wakeup pipe.</summary>
private void RequestWakeup()
{
unsafe
{
EventSourceTrace(null);
byte b = 1;
Interop.CheckIo(Interop.Sys.Write(_requestWakeupPipeFd, &b, 1));
}
}
/// <summary>Clears data from the wakeup pipe.</summary>
/// <remarks>
/// This must only be called when we know there's data to be read.
/// The MultiAgent could easily deadlock if it's called when there's no data in the pipe.
/// </remarks>
private unsafe void ReadFromWakeupPipeWhenKnownToContainData()
{
// It's possible but unlikely that there will be tons of extra data in the pipe,
// more than we end up reading out here (it's unlikely because we only write a byte to the pipe when
// transitioning from 0 to 1 incoming request). In that unlikely event, the worst
// case will be that the next one or more waits will wake up immediately, with each one
// subsequently clearing out more of the pipe.
const int ClearBufferSize = 64; // sufficiently large to clear the pipe in any normal case
byte* clearBuf = stackalloc byte[ClearBufferSize];
Interop.CheckIo(Interop.Sys.Read(_wakeupRequestedPipeFd, clearBuf, ClearBufferSize));
}
/// <summary>Requests that libcurl unpause the connection associated with this request.</summary>
internal void RequestUnpause(EasyRequest easy)
{
EventSourceTrace(null, easy: easy);
Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause });
}
/// <summary>Creates and configures a new multi handle.</summary>
private SafeCurlMultiHandle CreateAndConfigureMultiHandle()
{
// Create the new handle
SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate();
if (multiHandle.IsInvalid)
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_FAILED_INIT, isMulti: false));
}
// In support of HTTP/2, enable HTTP/2 connections to be multiplexed if possible.
// We must only do this if the version of libcurl being used supports HTTP/2 multiplexing.
// Due to a change in a libcurl signature, if we try to make this call on an older libcurl,
// we'll end up accidentally and unconditionally enabling HTTP 1.1 pipelining.
if (s_supportsHttp2Multiplexing)
{
ThrowIfCURLMError(Interop.Http.MultiSetOptionLong(multiHandle,
Interop.Http.CURLMoption.CURLMOPT_PIPELINING,
(long)Interop.Http.CurlPipe.CURLPIPE_MULTIPLEX));
}
return multiHandle;
}
private void WorkerLoop()
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "No locks should be held while invoking Process");
Debug.Assert(_runningWorker != null && _runningWorker.Id == Task.CurrentId, "This is the worker, so it must be running");
Debug.Assert(_wakeupRequestedPipeFd != null && !_wakeupRequestedPipeFd.IsInvalid, "Should have a valid pipe for wake ups");
// Create the multi handle to use for this round of processing. This one handle will be used
// to service all easy requests currently available and all those that come in while
// we're processing other requests. Once the work quiesces and there are no more requests
// to process, this multi handle will be released as the worker goes away. The next
// time a request arrives and a new worker is spun up, a new multi handle will be created.
SafeCurlMultiHandle multiHandle = CreateAndConfigureMultiHandle();
// Clear our active operations table. This should already be clear, either because
// all previous operations completed without unexpected exception, or in the case of an
// unexpected exception we should have cleaned up gracefully anyway. But just in case...
Debug.Assert(_activeOperations.Count == 0, "We shouldn't have any active operations when starting processing.");
_activeOperations.Clear();
Exception eventLoopError = null;
try
{
// Continue processing as long as there are any active operations
while (true)
{
// First handle any requests in the incoming requests queue.
while (true)
{
IncomingRequest request;
lock (_incomingRequests)
{
if (_incomingRequests.Count == 0) break;
request = _incomingRequests.Dequeue();
}
HandleIncomingRequest(multiHandle, request);
}
// If we have no active operations, we're done.
if (_activeOperations.Count == 0)
{
return;
}
// We have one or more active operations. Run any work that needs to be run.
CURLMcode performResult;
while ((performResult = Interop.Http.MultiPerform(multiHandle)) == CURLMcode.CURLM_CALL_MULTI_PERFORM);
ThrowIfCURLMError(performResult);
// Complete and remove any requests that have finished being processed.
CURLMSG message;
IntPtr easyHandle;
CURLcode result;
while (Interop.Http.MultiInfoRead(multiHandle, out message, out easyHandle, out result))
{
Debug.Assert(message == CURLMSG.CURLMSG_DONE, "CURLMSG_DONE is supposed to be the only message type");
if (message == CURLMSG.CURLMSG_DONE)
{
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(easyHandle, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
if (getInfoResult == CURLcode.CURLE_OK)
{
ActiveRequest completedOperation;
bool gotActiveOp = _activeOperations.TryGetValue(gcHandlePtr, out completedOperation);
Debug.Assert(gotActiveOp, "Expected to find GCHandle ptr in active operations table");
if (gotActiveOp)
{
DeactivateActiveRequest(multiHandle, completedOperation.Easy, gcHandlePtr, completedOperation.CancellationRegistration);
FinishRequest(completedOperation.Easy, result);
}
}
}
}
// Wait for more things to do.
bool isWakeupRequestedPipeActive;
bool isTimeout;
ThrowIfCURLMError(Interop.Http.MultiWait(multiHandle, _wakeupRequestedPipeFd, out isWakeupRequestedPipeActive, out isTimeout));
if (isWakeupRequestedPipeActive)
{
// We woke up (at least in part) because a wake-up was requested.
// Read the data out of the pipe to clear it.
Debug.Assert(!isTimeout, "should not have timed out if isExtraFileDescriptorActive");
EventSourceTrace("Wait wake-up");
ReadFromWakeupPipeWhenKnownToContainData();
}
if (isTimeout)
{
EventSourceTrace("Wait timeout");
}
// PERF NOTE: curl_multi_wait uses poll (assuming it's available), which is O(N) in terms of the number of fds
// being waited on. If this ends up being a scalability bottleneck, we can look into using the curl_multi_socket_*
// APIs, which would let us switch to using epoll by being notified when sockets file descriptors are added or
// removed and configuring the epoll context with EPOLL_CTL_ADD/DEL, which at the expense of a lot of additional
// complexity would let us turn the O(N) operation into an O(1) operation. The additional complexity would come
// not only in the form of additional callbacks and managing the socket collection, but also in the form of timer
// management, which is necessary when using the curl_multi_socket_* APIs and which we avoid by using just
// curl_multi_wait/perform.
}
}
catch (Exception exc)
{
eventLoopError = exc;
throw;
}
finally
{
// If we got an unexpected exception, something very bad happened. We may have some
// operations that we initiated but that weren't completed. Make sure to clean up any
// such operations, failing them and releasing their resources.
if (_activeOperations.Count > 0)
{
Debug.Assert(eventLoopError != null, "We should only have remaining operations if we got an unexpected exception");
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
ActiveRequest failingOperation = pair.Value;
IntPtr failingOperationGcHandle = pair.Key;
DeactivateActiveRequest(multiHandle, failingOperation.Easy, failingOperationGcHandle, failingOperation.CancellationRegistration);
// Complete the operation's task and clean up any of its resources
failingOperation.Easy.FailRequest(CreateHttpRequestException(eventLoopError));
failingOperation.Easy.Cleanup(); // no active processing remains, so cleanup
}
// Clear the table.
_activeOperations.Clear();
}
// Finally, dispose of the multi handle.
multiHandle.Dispose();
}
}
private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
EventSourceTrace("Type: {0}", request.Type, easy: request.Easy);
EasyRequest easy = request.Easy;
switch (request.Type)
{
case IncomingRequestType.New:
ActivateNewRequest(multiHandle, easy);
break;
case IncomingRequestType.Cancel:
Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
break;
case IncomingRequestType.Unpause:
Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
if (!easy._easyHandle.IsClosed)
{
IntPtr gcHandlePtr;
ActiveRequest ar;
Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");
CURLcode unpauseResult = Interop.Http.EasyUnpause(easy._easyHandle);
try
{
ThrowIfCURLEError(unpauseResult);
}
catch (Exception exc)
{
FindAndFailActiveRequest(multiHandle, easy, exc);
}
}
break;
default:
Debug.Fail("Invalid request type: " + request.Type);
break;
}
}
private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy)
{
Debug.Assert(easy != null, "We should never get a null request");
Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet");
// If cancellation has been requested, complete the request proactively
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// Otherwise, configure it. Most of the configuration was already done when the EasyRequest
// was created, but there's additional configuration we need to do specific to this
// multi agent, specifically telling the easy request about its own GCHandle and setting
// up callbacks for data processing. Once it's configured, add it to the multi handle.
GCHandle gcHandle = GCHandle.Alloc(easy);
IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle);
try
{
easy._associatedMultiAgent = this;
easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr);
easy.SetCurlCallbacks(gcHandlePtr, s_receiveHeadersCallback, s_sendCallback, s_seekCallback, s_receiveBodyCallback, s_debugCallback);
ThrowIfCURLMError(Interop.Http.MultiAddHandle(multiHandle, easy._easyHandle));
}
catch (Exception exc)
{
gcHandle.Free();
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// And if cancellation can be requested, hook up a cancellation callback.
// This callback will put the easy request back into the queue, which will
// ensure that a wake-up request has been issued. When we pull
// the easy request out of the request queue, we'll see that it's already
// associated with this agent, meaning that it's a cancellation request,
// and we'll deal with it appropriately.
var cancellationReg = default(CancellationTokenRegistration);
if (easy._cancellationToken.CanBeCanceled)
{
cancellationReg = easy._cancellationToken.Register(s =>
{
var state = (Tuple<MultiAgent, EasyRequest>)s;
state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel });
}, Tuple.Create<MultiAgent, EasyRequest>(this, easy));
}
// Finally, add it to our map.
_activeOperations.Add(
gcHandlePtr,
new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg });
}
private void DeactivateActiveRequest(
SafeCurlMultiHandle multiHandle, EasyRequest easy,
IntPtr gcHandlePtr, CancellationTokenRegistration cancellationRegistration)
{
// Remove the operation from the multi handle so we can shut down the multi handle cleanly
CURLMcode removeResult = Interop.Http.MultiRemoveHandle(multiHandle, easy._easyHandle);
Debug.Assert(removeResult == CURLMcode.CURLM_OK, "Failed to remove easy handle"); // ignore cleanup errors in release
// Release the associated GCHandle so that it's not kept alive forever
if (gcHandlePtr != IntPtr.Zero)
{
try
{
GCHandle.FromIntPtr(gcHandlePtr).Free();
_activeOperations.Remove(gcHandlePtr);
}
catch (InvalidOperationException)
{
Debug.Fail("Couldn't get/free the GCHandle for an active operation while shutting down due to failure");
}
}
// Undo cancellation registration
cancellationRegistration.Dispose();
}
private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest)
{
// We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but
// expensive to look up by EasyRequest. If we find this becoming a bottleneck, we can add a reverse
// map that stores the other direction as well.
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
if (pair.Value.Easy == easy)
{
gcHandlePtr = pair.Key;
activeRequest = pair.Value;
return true;
}
}
gcHandlePtr = IntPtr.Zero;
activeRequest = default(ActiveRequest);
return false;
}
private void FindAndFailActiveRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy, Exception error)
{
EventSourceTrace("Error: {0}", error, easy: easy);
IntPtr gcHandlePtr;
ActiveRequest activeRequest;
if (FindActiveRequest(easy, out gcHandlePtr, out activeRequest))
{
DeactivateActiveRequest(multiHandle, easy, gcHandlePtr, activeRequest.CancellationRegistration);
easy.FailRequest(error);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
Debug.Assert(easy.Task.IsCompleted, "We should only not be able to find the request if it failed or we started to send back the response.");
}
}
private void FinishRequest(EasyRequest completedOperation, CURLcode messageResult)
{
EventSourceTrace("Curl result: {0}", messageResult, easy: completedOperation);
if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized)
{
// If preauthentication is enabled, then we want to transfer credentials to the handler's credential cache.
// That entails asking the easy operation which auth types are supported, and then giving that info to the
// handler, which along with the request URI and its server credentials will populate the cache appropriately.
if (completedOperation._handler.PreAuthenticate)
{
long authAvailable;
if (Interop.Http.EasyGetInfoLong(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out authAvailable) == CURLcode.CURLE_OK)
{
completedOperation._handler.TransferCredentialsToCache(
completedOperation._requestMessage.RequestUri, (CURLAUTH)authAvailable);
}
// Ignore errors: no need to fail for the sake of putting the credentials into the cache
}
}
// Complete or fail the request
try
{
bool unsupportedProtocolRedirect = messageResult == CURLcode.CURLE_UNSUPPORTED_PROTOCOL && completedOperation._isRedirect;
if (!unsupportedProtocolRedirect)
{
ThrowIfCURLEError(messageResult);
}
completedOperation.EnsureResponseMessagePublished();
}
catch (Exception exc)
{
completedOperation.FailRequest(exc);
}
// At this point, we've completed processing the entire request, either due to error
// or due to completing the entire response.
completedOperation.Cleanup();
}
private static void CurlDebugFunction(IntPtr curl, Interop.Http.CurlInfoType type, IntPtr data, ulong size, IntPtr context)
{
EasyRequest easy;
TryGetEasyRequestFromContext(context, out easy);
try
{
switch (type)
{
case Interop.Http.CurlInfoType.CURLINFO_TEXT:
case Interop.Http.CurlInfoType.CURLINFO_HEADER_IN:
case Interop.Http.CurlInfoType.CURLINFO_HEADER_OUT:
string text = Marshal.PtrToStringAnsi(data, (int)size).Trim();
if (text.Length > 0)
{
CurlHandler.EventSourceTrace("{0}: {1}", type, text, 0, easy: easy);
}
break;
default:
CurlHandler.EventSourceTrace("{0}: {1} bytes", type, size, 0, easy: easy);
break;
}
}
catch (Exception exc)
{
CurlHandler.EventSourceTrace("Error: {0}", exc, easy: easy);
}
}
private static ulong CurlReceiveHeadersCallback(IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
// The callback is invoked once per header; multi-line headers get merged into a single line.
size *= nitems;
if (size == 0)
{
return 0;
}
Debug.Assert(size <= Interop.Http.CURL_MAX_HTTP_HEADER);
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
CurlHandler.EventSourceTrace("Size: {0}", size, easy: easy);
try
{
HttpResponseMessage response = easy._responseMessage;
CurlResponseHeaderReader reader = new CurlResponseHeaderReader(buffer, size);
if (reader.ReadStatusLine(response))
{
// Clear the header if status line is received again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
easy._isRedirect = easy._handler.AutomaticRedirection &&
(response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.RedirectKeepVerb ||
response.StatusCode == HttpStatusCode.RedirectMethod);
}
else
{
string headerName;
string headerValue;
if (reader.ReadHeader(out headerName, out headerValue))
{
if (!response.Headers.TryAddWithoutValidation(headerName, headerValue))
{
response.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
else if (easy._isRedirect && string.Equals(headerName, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase))
{
HandleRedirectLocationHeader(easy, headerValue);
}
else if (string.Equals(headerName, HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase))
{
easy._handler.AddResponseCookies(easy, headerValue);
}
}
}
return size;
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returing a value other than size fails the callback and forces
// request completion with an error
CurlHandler.EventSourceTrace("Aborting request", easy: easy);
return size - 1;
}
private static ulong CurlReceiveBodyCallback(
IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
size *= nitems;
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
CurlHandler.EventSourceTrace("Size: {0}", size, easy: easy);
try
{
if (!(easy.Task.IsCanceled || easy.Task.IsFaulted))
{
// Complete the task if it hasn't already been. This will make the
// stream available to consumers. A previous write callback
// may have already completed the task to publish the response.
easy.EnsureResponseMessagePublished();
// Try to transfer the data to a reader. This will return either the
// amount of data transferred (equal to the amount requested
// to be transferred), or it will return a pause request.
return easy._responseMessage.ResponseStream.TransferDataToStream(buffer, (long)size);
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returing a value other than size fails the callback and forces
// request completion with an error.
CurlHandler.EventSourceTrace("Aborting request", easy: easy);
return (size > 0) ? size - 1 : 1;
}
private static ulong CurlSendCallback(IntPtr buffer, ulong size, ulong nitems, IntPtr context)
{
int length = checked((int)(size * nitems));
Debug.Assert(length <= RequestBufferSize, "length " + length + " should not be larger than RequestBufferSize " + RequestBufferSize);
if (length == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
CurlHandler.EventSourceTrace("Size: {0}", length, easy: easy);
Debug.Assert(easy._requestContentStream != null, "We should only be in the send callback if we have a request content stream");
Debug.Assert(easy._associatedMultiAgent != null, "The request should be associated with a multi agent.");
try
{
// Transfer data from the request's content stream to libcurl
return TransferDataFromRequestStream(buffer, length, easy);
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong.
CurlHandler.EventSourceTrace("Aborting request", easy: easy);
return Interop.Http.CURL_READFUNC_ABORT;
}
/// <summary>
/// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
/// request content (non-memory) stream to the buffer.
/// </summary>
/// <returns>The number of bytes transferred.</returns>
private static ulong TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy)
{
CurlHandler.EventSourceTrace("Length: {0}", length, easy: easy);
MultiAgent multi = easy._associatedMultiAgent;
// First check to see whether there's any data available from a previous asynchronous read request.
// If there is, the transfer state's Task field will be non-null, with its Result representing
// the number of bytes read. The Buffer will then contain all of that read data. If the Count
// is 0, then this is the first time we're checking that Task, and so we populate the Count
// from that read result. After that, we can transfer as much data remains between Offset and
// Count. Multiple callbacks may pull from that one read.
EasyRequest.SendTransferState sts = easy._sendTransferState;
if (sts != null)
{
// Is there a previous read that may still have data to be consumed?
if (sts._task != null)
{
if (!sts._task.IsCompleted)
{
// We have a previous read that's not yet completed. This should be quite rare, but it can
// happen when we're unpaused prematurely, potentially due to the request still finishing
// being sent as the server starts to send a response. Since we still have the outstanding
// read, we simply re-pause. When the task completes (which could have happened immediately
// after the check). the continuation we previously created will fire and queue an unpause.
// Since all of this processing is single-threaded on the current thread, that unpause request
// is guaranteed to happen after this re-pause.
multi.EventSourceTrace("Re-pausing reading after a spurious un-pause", easy: easy);
return Interop.Http.CURL_READFUNC_PAUSE;
}
// Determine how many bytes were read on the last asynchronous read.
// If nothing was read, then we're done and can simply return 0 to indicate
// the end of the stream.
int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed
Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead);
if (bytesRead == 0)
{
sts.SetTaskOffsetCount(null, 0, 0);
return 0;
}
// If Count is still 0, then this is the first time after the task completed
// that we're examining the data: transfer the bytesRead to the Count.
if (sts._count == 0)
{
multi.EventSourceTrace("ReadAsync completed with bytes: {0}", bytesRead, easy: easy);
sts._count = bytesRead;
}
// Now Offset and Count are both accurate. Determine how much data we can copy to libcurl...
int availableData = sts._count - sts._offset;
Debug.Assert(availableData > 0, "There must be some data still available.");
// ... and copy as much of that as libcurl will allow.
int bytesToCopy = Math.Min(availableData, length);
Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy);
multi.EventSourceTrace("Copied {0} bytes from request stream", bytesToCopy, easy: easy);
// Update the offset. If we've gone through all of the data, reset the state
// so that the next time we're called back we'll do a new read.
sts._offset += bytesToCopy;
Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count");
if (sts._offset == sts._count)
{
sts.SetTaskOffsetCount(null, 0, 0);
}
// Return the amount of data copied
Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here.");
return (ulong)bytesToCopy;
}
// sts was non-null but sts.Task was null, meaning there was no previous task/data
// from which to satisfy any of this request.
}
else // sts == null
{
// Allocate a transfer state object to use for the remainder of this request.
easy._sendTransferState = sts = new EasyRequest.SendTransferState();
}
Debug.Assert(sts != null, "By this point we should have a transfer object");
Debug.Assert(sts._task == null, "There shouldn't be a task now.");
Debug.Assert(sts._count == 0, "Count should be zero.");
Debug.Assert(sts._offset == 0, "Offset should be zero.");
// If we get here, there was no previously read data available to copy.
// Initiate a new asynchronous read.
Task<int> asyncRead = easy._requestContentStream.ReadAsyncInternal(
sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken);
Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync");
// Even though it's "Async", it's possible this read could complete synchronously or extremely quickly.
// Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback.
if (asyncRead.IsCompleted)
{
// Get the amount of data read.
int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed
if (bytesRead == 0)
{
return 0;
}
// Copy as much as we can.
int bytesToCopy = Math.Min(bytesRead, length);
Debug.Assert(bytesToCopy > 0 && bytesToCopy <= sts._buffer.Length, "ReadAsync quickly returned an invalid result length: " + bytesToCopy);
Marshal.Copy(sts._buffer, 0, buffer, bytesToCopy);
// If we read more than we were able to copy, stash it away for the next read.
if (bytesToCopy < bytesRead)
{
sts.SetTaskOffsetCount(asyncRead, bytesToCopy, bytesRead);
}
// Return the number of bytes read.
return (ulong)bytesToCopy;
}
// Otherwise, the read completed asynchronously. Store the task, and hook up a continuation
// such that the connection will be unpaused once the task completes.
sts.SetTaskOffsetCount(asyncRead, 0, 0);
asyncRead.ContinueWith((t, s) =>
{
EasyRequest easyRef = (EasyRequest)s;
easyRef._associatedMultiAgent.RequestUnpause(easyRef);
}, easy, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
// Then pause the connection.
multi.EventSourceTrace("Pausing the connection.", easy: easy);
return Interop.Http.CURL_READFUNC_PAUSE;
}
private static CurlSeekResult CurlSeekCallback(IntPtr context, long offset, int origin)
{
CurlHandler.EventSourceTrace("Offset: {0}, Origin: {1}", offset, origin, 0);
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
// If libcul is requesting we seek back to the beginning and if the request
// content stream is in a position to reset itself, reset and let libcurl
// know we did the seek; otherwise, let it know we can't seek.
if (offset == 0 && origin == (int)SeekOrigin.Begin &&
easy._requestContentStream != null && easy._requestContentStream.TryReset())
{
// Dump any state associated with the old stream's position
if (easy._sendTransferState != null)
{
easy._sendTransferState.SetTaskOffsetCount(null, 0, 0);
}
// Restart the transfer
easy._requestContentStream.Run();
return CurlSeekResult.CURL_SEEKFUNC_OK;
}
else
{
return CurlSeekResult.CURL_SEEKFUNC_CANTSEEK;
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong
return CurlSeekResult.CURL_SEEKFUNC_FAIL;
}
private static bool TryGetEasyRequestFromContext(IntPtr context, out EasyRequest easy)
{
// Get the EasyRequest from the context
try
{
GCHandle handle = GCHandle.FromIntPtr(context);
easy = (EasyRequest)handle.Target;
Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
return easy != null;
}
catch (InvalidCastException)
{
Debug.Fail("EasyRequest wasn't the GCHandle's Target");
}
catch (InvalidOperationException)
{
Debug.Fail("Invalid GCHandle");
}
easy = null;
return false;
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, this, easy, memberName);
}
private void EventSourceTrace(string message, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, this, easy, memberName);
}
/// <summary>Represents an active request currently being processed by the agent.</summary>
private struct ActiveRequest
{
public EasyRequest Easy;
public CancellationTokenRegistration CancellationRegistration;
}
/// <summary>Represents an incoming request to be processed by the agent.</summary>
internal struct IncomingRequest
{
public IncomingRequestType Type;
public EasyRequest Easy;
}
/// <summary>The type of an incoming request to be processed by the agent.</summary>
internal enum IncomingRequestType : byte
{
/// <summary>A new request that's never been submitted to an agent.</summary>
New,
/// <summary>A request to cancel a request previously submitted to the agent.</summary>
Cancel,
/// <summary>A request to unpause the connection associated with a request previously submitted to the agent.</summary>
Unpause
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkInterfacesOperations operations.
/// </summary>
public partial interface INetworkInterfacesOperations
{
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> GetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all network interfaces in a virtual machine
/// in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> BeginGetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all network interfaces in a virtual machine
/// in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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 Bas Geertsema or Xih Solutions 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.
*/
#endregion
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace MSNPSharp.P2P
{
public delegate void AckHandler(P2PMessage ack);
#region P2PMessage EventArgs
[Serializable]
public class P2PMessageEventArgs : EventArgs
{
private P2PMessage p2pMessage;
public P2PMessage P2PMessage
{
get
{
return p2pMessage;
}
}
public P2PMessageEventArgs(P2PMessage p2pMessage)
{
this.p2pMessage = p2pMessage;
}
}
[Serializable]
public class P2PAckMessageEventArgs : P2PMessageEventArgs
{
private int deleteTick = 0;
private AckHandler ackHandler;
public AckHandler AckHandler
{
get
{
return ackHandler;
}
}
public int DeleteTick
{
get
{
return deleteTick;
}
set
{
deleteTick = value;
}
}
public P2PAckMessageEventArgs(P2PMessage p2pMessage, AckHandler ackHandler, int timeoutSec)
: base(p2pMessage)
{
this.ackHandler = ackHandler;
this.deleteTick = timeoutSec;
if (timeoutSec != 0)
{
AddSeconds(timeoutSec);
}
}
public void AddSeconds(int secs)
{
DeleteTick = unchecked(Environment.TickCount + (secs * 1000));
}
}
[Serializable]
public class P2PMessageSessionEventArgs : P2PMessageEventArgs
{
private P2PSession p2pSession;
public P2PSession P2PSession
{
get
{
return p2pSession;
}
}
public P2PMessageSessionEventArgs(P2PMessage p2pMessage, P2PSession p2pSession)
: base(p2pMessage)
{
this.p2pSession = p2pSession;
}
}
#endregion
/// <summary>
/// The base class for P2P Transport Layer.
/// </summary>
public abstract class P2PBridge : IDisposable
{
public const int DefaultTimeout = 10;
/// <summary>
/// The maximum time for a bridge to waiting for coneection.
/// </summary>
public const int MaxTimeout = 180;
#region Events & Fields
/// <summary>
/// Fired after this bridge was opened.
/// </summary>
public event EventHandler<EventArgs> BridgeOpened;
/// <summary>
/// Fired after the connect negotiation has been completed.
/// </summary>
public event EventHandler<EventArgs> BridgeSynced;
/// <summary>
/// Fired after the bridge ends its lifecycle.
/// </summary>
public event EventHandler<EventArgs> BridgeClosed;
public event EventHandler<P2PMessageSessionEventArgs> BridgeSent;
private static uint bridgeCount = 0;
private uint sequenceId = 0;
private uint syncId = 0;
private ushort packageNo = 0;
protected uint bridgeID = ++bridgeCount;
protected int queueSize = 0;
private NSMessageHandler nsMessageHandler = null;
protected Dictionary<P2PSession, P2PSendQueue> sendQueues = new Dictionary<P2PSession, P2PSendQueue>();
protected Dictionary<P2PSession, P2PSendList> sendingQueues = new Dictionary<P2PSession, P2PSendList>();
protected List<P2PSession> stoppedSessions = new List<P2PSession>();
private Dictionary<uint, P2PAckMessageEventArgs> ackHandlersV1 = new Dictionary<uint, P2PAckMessageEventArgs>();
private Dictionary<uint, P2PAckMessageEventArgs> ackHandlersV2 = new Dictionary<uint, P2PAckMessageEventArgs>();
private DateTime nextCleanup = DateTime.MinValue;
private volatile int inCleanup = 0;
private object syncObject;
const int CleanupIntervalSecs = 5;
#endregion
#region Properties
/// <summary>
/// Check wether the bridge has been opened.
/// </summary>
public abstract bool IsOpen
{
get;
}
/// <summary>
/// The maximum data package szie for the bridge.
/// </summary>
public abstract int MaxDataSize
{
get;
}
public abstract Contact Remote
{
get;
}
/// <summary>
/// Check whether the connect negotiation has been completed.
/// You can transfer data only after a bridge after synced.
/// </summary>
public virtual bool Synced
{
get
{
return (0 != SyncId);
}
}
public virtual uint SyncId
{
get
{
return syncId;
}
protected internal set
{
syncId = value;
if (0 != value)
{
OnBridgeSynced(EventArgs.Empty);
}
}
}
/// <summary>
/// The current sequence ID for this bridge (Transport Layer).
/// </summary>
public virtual uint SequenceId
{
get
{
return sequenceId;
}
internal protected set
{
sequenceId = value;
}
}
public ushort PackageNo
{
get
{
return packageNo;
}
internal protected set
{
packageNo = value;
}
}
/// <summary>
/// The holding data queues to be sent in this bridge.
/// </summary>
public virtual Dictionary<P2PSession, P2PSendQueue> SendQueues
{
get
{
return sendQueues;
}
}
public NSMessageHandler NSMessageHandler
{
get
{
return nsMessageHandler;
}
}
public object SyncObject
{
get
{
if (syncObject == null)
{
Interlocked.CompareExchange(ref syncObject, new object(), null);
}
return syncObject;
}
}
#endregion
/// <summary>
/// P2PBridge constructor.
/// </summary>
protected P2PBridge(int queueSize, NSMessageHandler nsHandler)
{
this.queueSize = queueSize;
this.sequenceId = (uint)new Random().Next(5000, int.MaxValue);
this.nextCleanup = NextCleanupTime();
this.nsMessageHandler = nsHandler;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} created", this.ToString()), GetType().Name);
}
/// <summary>
/// Release the resources used by <see cref="P2PBridge"/>
/// </summary>
public virtual void Dispose()
{
lock (sendQueues)
sendQueues.Clear();
lock (sendingQueues)
sendingQueues.Clear();
lock (stoppedSessions)
stoppedSessions.Clear();
lock (ackHandlersV1)
ackHandlersV1.Clear();
lock (ackHandlersV2)
ackHandlersV2.Clear();
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} disposed", this.ToString()), GetType().Name);
}
private DateTime NextCleanupTime()
{
return DateTime.Now.AddMinutes(CleanupIntervalSecs);
}
private void RunRakCleanupIfNecessary()
{
if (nextCleanup < DateTime.Now)
{
List<P2PMessage> raks = new List<P2PMessage>();
if (nextCleanup < DateTime.Now)
{
inCleanup++;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("Running RAK cleanup for {0}...", this.ToString()));
nextCleanup = NextCleanupTime();
int tickcount = Environment.TickCount + 2000; // Give +2 secs change...
List<uint> ackstodelete = new List<uint>();
lock (ackHandlersV1)
{
// P2Pv1
foreach (KeyValuePair<uint, P2PAckMessageEventArgs> pair in ackHandlersV1)
{
if (pair.Value.DeleteTick != 0 && pair.Value.DeleteTick < tickcount)
{
ackstodelete.Add(pair.Key);
raks.Add(pair.Value.P2PMessage);
}
}
foreach (uint i in ackstodelete)
{
ackHandlersV1.Remove(i);
}
}
ackstodelete.Clear();
lock (ackHandlersV2)
{
// P2Pv2
foreach (KeyValuePair<uint, P2PAckMessageEventArgs> pair in ackHandlersV2)
{
if (pair.Value.DeleteTick != 0 && pair.Value.DeleteTick < tickcount)
{
ackstodelete.Add(pair.Key);
raks.Add(pair.Value.P2PMessage);
}
}
foreach (uint i in ackstodelete)
{
ackHandlersV2.Remove(i);
}
}
GC.Collect();
inCleanup = 0;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("End RAK cleanup for {0}...", this.ToString()));
}
if (raks.Count > 0)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("Unacked RAK packets for {0}...", this.ToString()));
foreach (P2PMessage rak in raks)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, rak.ToDebugString());
}
}
}
}
/// <summary>
/// Check whether the P2P session can be transfer on the bridge.
/// </summary>
/// <param name="session">
/// The <see cref="P2PSession"/> needs to check.
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public virtual bool SuitableFor(P2PSession session)
{
Contact remote = Remote;
return (session != null) && (remote != null) && (session.Remote.IsSibling(remote));
}
/// <summary>
/// Check if the session is ready to begin sending packets.
/// </summary>
/// <param name="session"></param>
/// <returns></returns>
public virtual bool Ready(P2PSession session)
{
lock (stoppedSessions)
{
if (queueSize == 0)
return IsOpen && (!stoppedSessions.Contains(session));
lock (sendingQueues)
{
if (!sendingQueues.ContainsKey(session))
return IsOpen && SuitableFor(session) && (!stoppedSessions.Contains(session));
return IsOpen && (sendingQueues[session].Count < queueSize) && (!stoppedSessions.Contains(session));
}
}
}
/// <summary>
/// Send a P2P Message to the specified P2PSession.
/// </summary>
/// <param name="session">
/// The application layer, which is a <see cref="P2PSession"/>.
/// </param>
/// <param name="remote">
/// The receiver <see cref="Contact"/>.
/// </param>
/// <param name="remoteGuid">
/// A <see cref="Guid"/>
/// </param>
/// <param name="msg">
/// The <see cref="P2PMessage"/> to be sent.
/// </param>
public virtual void Send(P2PSession session, Contact remote, Guid remoteGuid, P2PMessage msg)
{
Send(session, remote, remoteGuid, msg, 0, null);
}
/// <summary>
/// Send a P2P Message to the specified P2PSession.
/// </summary>
/// <param name="session">
/// The application layer, which is a <see cref="P2PSession"/>
/// </param>
/// <param name="remote">
/// he receiver <see cref="Contact"/>
/// </param>
/// <param name="remoteGuid">
/// A <see cref="Guid"/>
/// </param>
/// <param name="msg">
/// he <see cref="P2PMessage"/> to be sent.
/// </param>
/// <param name="ackTimeout">
/// The maximum time to wait for an ACK. <see cref="System.Int32"/>
/// </param>
/// <param name="ackHandler">
/// The <see cref="AckHandler"/> to handle the ACK.
/// </param>
public virtual void Send(P2PSession session, Contact remote, Guid remoteGuid, P2PMessage msg, int ackTimeout, AckHandler ackHandler)
{
if (remote == null)
throw new ArgumentNullException("remote");
P2PMessage[] msgs = SetSequenceNumberAndRegisterAck(session, remote, msg, ackHandler, ackTimeout);
if (session == null)
{
if (!IsOpen)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceError,
"Send called with no session on a closed bridge", GetType().Name);
return;
}
// Bypass queueing
foreach (P2PMessage m in msgs)
{
SendOnePacket(null, remote, remoteGuid, m);
}
return;
}
if (!SuitableFor(session))
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceError,
"Send called with a session this bridge is not suitable for", GetType().Name);
return;
}
lock (sendQueues)
{
if (!sendQueues.ContainsKey(session))
sendQueues[session] = new P2PSendQueue();
}
lock (sendQueues[session])
{
foreach (P2PMessage m in msgs)
sendQueues[session].Enqueue(remote, remoteGuid, m);
}
ProcessSendQueues();
}
private P2PMessage[] SetSequenceNumberAndRegisterAck(P2PSession session, Contact remote, P2PMessage p2pMessage, AckHandler ackHandler, int timeout)
{
if (p2pMessage.Header.Identifier == 0)
{
if (p2pMessage.Version == P2PVersion.P2PV1)
{
p2pMessage.Header.Identifier = ++sequenceId;
}
else if (p2pMessage.Version == P2PVersion.P2PV2)
{
p2pMessage.V2Header.Identifier = sequenceId;
}
}
if (p2pMessage.Version == P2PVersion.P2PV1 && p2pMessage.V1Header.AckSessionId == 0)
{
p2pMessage.V1Header.AckSessionId = (uint)new Random().Next(50000, int.MaxValue);
}
if (p2pMessage.Version == P2PVersion.P2PV2 && p2pMessage.V2Header.PackageNumber == 0)
{
p2pMessage.V2Header.PackageNumber = packageNo;
}
P2PMessage[] msgs = p2pMessage.SplitMessage(MaxDataSize);
if (p2pMessage.Version == P2PVersion.P2PV2)
{
// Correct local sequence no
P2PMessage lastMsg = msgs[msgs.Length - 1];
SequenceId = lastMsg.V2Header.Identifier + lastMsg.V2Header.MessageSize;
}
if (ackHandler != null)
{
P2PMessage firstMessage = msgs[0];
RegisterAckHandler(new P2PAckMessageEventArgs(firstMessage, ackHandler, timeout));
}
if (session != null)
{
session.LocalIdentifier = SequenceId;
}
return msgs;
}
protected virtual void RegisterAckHandler(P2PAckMessageEventArgs e)
{
if (e.P2PMessage.Version == P2PVersion.P2PV2)
{
lock (ackHandlersV2)
{
e.P2PMessage.V2Header.OperationCode |= (byte)OperationCode.RAK;
ackHandlersV2[e.P2PMessage.V2Header.Identifier + e.P2PMessage.Header.MessageSize] = e;
}
}
else if (e.P2PMessage.Version == P2PVersion.P2PV1)
{
lock (ackHandlersV1)
{
ackHandlersV1[e.P2PMessage.V1Header.AckSessionId] = e;
}
}
}
internal bool HandleACK(P2PMessage p2pMessage)
{
bool isAckOrNak = false;
if (p2pMessage.Header.IsAcknowledgement || p2pMessage.Header.IsNegativeAck)
{
P2PAckMessageEventArgs e = null;
uint ackNakId = 0;
isAckOrNak = true;
if (p2pMessage.Version == P2PVersion.P2PV1)
{
lock (ackHandlersV1)
{
if (ackHandlersV1.ContainsKey(p2pMessage.Header.AckIdentifier))
{
ackNakId = p2pMessage.Header.AckIdentifier;
e = ackHandlersV1[ackNakId];
ackHandlersV1.Remove(ackNakId);
}
}
}
else if (p2pMessage.Version == P2PVersion.P2PV2)
{
lock (ackHandlersV2)
{
if (ackHandlersV2.ContainsKey(p2pMessage.Header.AckIdentifier))
{
ackNakId = p2pMessage.Header.AckIdentifier;
e = ackHandlersV2[ackNakId];
ackHandlersV2.Remove(ackNakId);
}
else if (ackHandlersV2.ContainsKey(p2pMessage.V2Header.NakIdentifier))
{
ackNakId = p2pMessage.V2Header.NakIdentifier;
e = ackHandlersV2[ackNakId];
ackHandlersV2.Remove(ackNakId);
}
}
}
if (ackNakId == 0)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
String.Format("!!!!!! No AckHandler registered for ack/nak {0}:\r\n{1}", p2pMessage.Header.AckIdentifier, p2pMessage.ToDebugString()), GetType().Name);
}
else
{
if (e != null && e.AckHandler != null)
{
e.AckHandler(p2pMessage);
}
else
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
String.Format("!!!!!! No AckHandler pair for ack {0}\r\n{1}", ackNakId, p2pMessage.ToDebugString()), GetType().Name);
}
}
}
return isAckOrNak;
}
#region HandleRAK
internal bool HandleRAK(Contact source, Guid sourceGuid, P2PMessage msg)
{
bool requireAck = false;
if (msg.Header.RequireAck)
{
requireAck = true;
P2PMessage ack = msg.CreateAcknowledgement();
if (ack.Header.RequireAck)
{
// SYN
Send(null, source, sourceGuid, ack, DefaultTimeout, delegate(P2PMessage sync)
{
SyncId = sync.Header.AckIdentifier;
Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo,
String.Format("SYNC completed for: {0}", this), GetType().Name);
});
}
else
{
// ACK
Send(null, source, sourceGuid, ack);
}
}
return requireAck;
}
#endregion
#region
public void ProcessP2PMessage(Contact source, Guid sourceGuid, P2PMessage p2pMessage)
{
// HANDLE RAK: RAKs are session independent and mustn't be quoted on bridges.
bool requireAck = HandleRAK(source, sourceGuid, p2pMessage);
// HANDLE ACK: ACK/NAK to our RAK message
if (HandleACK(p2pMessage))
{
return;
}
// PASS TO P2PHandler
if (nsMessageHandler.P2PHandler.ProcessP2PMessage(this, source, sourceGuid, p2pMessage))
{
return;
}
if (!requireAck)
{
// UNHANDLED P2P MESSAGE
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
String.Format("*******Unhandled P2P message ****** \r\n{0}", p2pMessage.ToDebugString()), GetType().Name);
// Keep RemoteID Synchronized, I think we must track remoteIdentifier here...
// Send NAK??????
}
}
#endregion
[MethodImpl(MethodImplOptions.Synchronized)]
protected virtual void ProcessSendQueues()
{
lock (sendQueues) // lock at the queue level, since it might be modified.
{
Dictionary<P2PSession, P2PSendQueue> sendQueuesCopy = new Dictionary<P2PSession, P2PSendQueue>(sendQueues);
foreach (KeyValuePair<P2PSession, P2PSendQueue> pair in sendQueuesCopy)
{
if (Ready(pair.Key))
{
List<P2PMessage> list = new List<P2PMessage>(queueSize);
while ((pair.Value.Count > 0) &&
(queueSize == 0 /*no limit*/ || list.Count < queueSize /* has limit */))
{
P2PSendItem item = pair.Value.Dequeue();
if (!sendingQueues.ContainsKey(pair.Key))
{
lock (sendingQueues)
sendingQueues.Add(pair.Key, new P2PSendList());
}
lock (sendingQueues[pair.Key])
sendingQueues[pair.Key].Add(item);
list.Add(item.P2PMessage);
}
if (list.Count > 0)
{
SendMultiPacket(pair.Key, pair.Key.Remote, pair.Key.RemoteContactEndPointID, list.ToArray());
}
}
}
bool moreQueued = false;
foreach (KeyValuePair<P2PSession, P2PSendQueue> pair in sendQueues)
{
if (pair.Value.Count > 0)
{
moreQueued = true;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("Queue holds {0} messages for session {1}", pair.Value.Count, pair.Key.SessionId), GetType().Name);
}
}
if (!moreQueued)
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Queues are all empty", GetType().Name);
RunRakCleanupIfNecessary();
}
}
protected abstract void SendOnePacket(P2PSession session, Contact remote, Guid remoteGuid, P2PMessage msg);
protected virtual void SendMultiPacket(P2PSession session, Contact remote, Guid remoteGuid, P2PMessage[] sendList)
{
foreach (P2PMessage p2pMessage in sendList)
{
SendOnePacket(session, remote, remoteGuid, p2pMessage);
}
}
/// <summary>
/// Stop sending future messages to the specified <see cref="P2PSession"/>.
/// </summary>
/// <param name="session"></param>
public virtual void StopSending(P2PSession session)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} stop sending for {1}", this.ToString(), session.SessionId), GetType().Name);
lock (stoppedSessions)
{
if (!stoppedSessions.Contains(session))
{
stoppedSessions.Add(session);
}
else
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Session is already in stopped list", GetType().Name);
}
}
/// <summary>
/// Continue to send future messages to the specified <see cref="P2PSession"/>.
/// </summary>
/// <param name="session"></param>
public virtual void ResumeSending(P2PSession session)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} resume sending for {1}", this.ToString(), session.SessionId), GetType().Name);
lock (stoppedSessions)
{
if (stoppedSessions.Contains(session))
{
stoppedSessions.Remove(session);
ProcessSendQueues();
}
else
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Session not present in stopped list", GetType().Name);
}
}
/// <summary>
/// Move the specified <see cref="P2PSession"/> to the new <see cref="P2PBridge"/> specified.
/// </summary>
/// <param name="session"></param>
/// <param name="newBridge"></param>
public virtual void MigrateQueue(P2PSession session, P2PBridge newBridge)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} migrating session {1} queue to new bridge {2}",
this.ToString(), session.SessionId, (newBridge != null) ? newBridge.ToString() : "null"), GetType().Name);
P2PSendQueue newQueue = new P2PSendQueue();
lock (sendingQueues)
{
if (sendingQueues.ContainsKey(session))
{
if (newBridge != null)
{
lock (sendingQueues[session])
{
foreach (P2PSendItem item in sendingQueues[session])
newQueue.Enqueue(item);
}
}
sendingQueues.Remove(session);
}
}
lock (sendQueues)
{
if (sendQueues.ContainsKey(session))
{
if (newBridge != null)
{
while (sendQueues[session].Count > 0)
newQueue.Enqueue(sendQueues[session].Dequeue());
}
sendQueues.Remove(session);
}
}
lock (stoppedSessions)
{
if (stoppedSessions.Contains(session))
{
stoppedSessions.Remove(session);
}
}
if (newBridge != null)
newBridge.AddQueue(session, newQueue);
}
/// <summary>
///
/// </summary>
/// <param name="session"></param>
/// <param name="queue"></param>
public virtual void AddQueue(P2PSession session, P2PSendQueue queue)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} received queue for session {1}", this.ToString(), session.SessionId), GetType().Name);
if (sendQueues.ContainsKey(session))
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
"A queue is already present for this session, merging the queues", GetType().Name);
lock (sendQueues[session])
{
while (queue.Count > 0)
sendQueues[session].Enqueue(queue.Dequeue());
}
}
else
{
lock (sendQueues)
sendQueues[session] = queue;
}
ProcessSendQueues();
}
protected virtual void OnBridgeOpened(EventArgs e)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} opened", this.ToString()), GetType().Name);
if (BridgeOpened != null)
BridgeOpened(this, e);
ProcessSendQueues();
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected internal virtual void OnBridgeSynced(EventArgs e)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("{0} synced, sync id: {1}", this.ToString(), SyncId), GetType().Name);
if (BridgeSynced != null)
BridgeSynced(this, e);
}
/// <summary>
/// Called after the bridge was closed.
/// </summary>
/// <param name="e"></param>
protected virtual void OnBridgeClosed(EventArgs e)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PBridge {0} closed", this.ToString()), GetType().Name);
if (BridgeClosed != null)
BridgeClosed(this, e);
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnBridgeSent(P2PMessageSessionEventArgs e)
{
P2PSession session = e.P2PSession;
lock (sendingQueues)
{
if ((session != null) && sendingQueues.ContainsKey(session))
{
if (sendingQueues[session].Contains(e.P2PMessage))
{
sendingQueues[session].Remove(e.P2PMessage);
}
else
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceError,
"Sent message not present in sending queue", GetType().Name);
}
}
}
if (BridgeSent != null)
BridgeSent(this, e);
ProcessSendQueues();
}
public override string ToString()
{
return String.Format("{0}:{1}", bridgeID, GetType().Name);
}
}
};
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
using System.Diagnostics;
using SharpBox2D.Common;
using SharpBox2D.Pooling;
namespace SharpBox2D.Dynamics.Joints
{
//Linear constraint (point-to-line)
//d = p2 - p1 = x2 + r2 - x1 - r1
//C = dot(perp, d)
//Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
//J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
//
//Angular constraint
//C = a2 - a1 + a_initial
//Cdot = w2 - w1
//J = [0 0 -1 0 0 1]
//
//K = J * invM * JT
//
//J = [-a -s1 a s2]
// [0 -1 0 1]
//a = perp
//s1 = cross(d + r1, a) = cross(p2 - x1, a)
//s2 = cross(r2, a) = cross(p2 - x2, a)
//Motor/Limit linear constraint
//C = dot(ax1, d)
//Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
//J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
//Block Solver
//We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even
//when the mass has poor distribution (leading to large torques about the joint anchor points).
//
//The Jacobian has 3 rows:
//J = [-uT -s1 uT s2] // linear
// [0 -1 0 1] // angular
// [-vT -a1 vT a2] // limit
//
//u = perp
//v = axis
//s1 = cross(d + r1, u), s2 = cross(r2, u)
//a1 = cross(d + r1, v), a2 = cross(r2, v)
//M * (v2 - v1) = JT * df
//J * v2 = bias
//
//v2 = v1 + invM * JT * df
//J * (v1 + invM * JT * df) = bias
//K * df = bias - J * v1 = -Cdot
//K = J * invM * JT
//Cdot = J * v1 - bias
//
//Now solve for f2.
//df = f2 - f1
//K * (f2 - f1) = -Cdot
//f2 = invK * (-Cdot) + f1
//
//Clamp accumulated limit impulse.
//lower: f2(3) = max(f2(3), 0)
//upper: f2(3) = min(f2(3), 0)
//
//Solve for correct f2(1:2)
//K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1
// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3)
//K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2)
//f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
//
//Now compute impulse to be applied:
//df = f2 - f1
/**
* A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in
* bodyA. Relative rotation is prevented. You can use a joint limit to restrict the range of motion
* and a joint motor to drive the motion or to model joint friction.
*
* @author Daniel
*/
public class PrismaticJoint : Joint
{
// Solver shared
internal Vec2 m_localAnchorA;
internal Vec2 m_localAnchorB;
internal Vec2 m_localXAxisA;
internal Vec2 m_localYAxisA;
internal float m_referenceAngle;
private Vec3 m_impulse;
private float m_motorImpulse;
private float m_lowerTranslation;
private float m_upperTranslation;
private float m_maxMotorForce;
private float m_motorSpeed;
private bool m_enableLimit;
private bool m_enableMotor;
private LimitState m_limitState;
// Solver temp
private int m_indexA;
private int m_indexB;
private Vec2 m_localCenterA = new Vec2();
private Vec2 m_localCenterB = new Vec2();
private float m_invMassA;
private float m_invMassB;
private float m_invIA;
private float m_invIB;
private Vec2 m_axis, m_perp;
private float m_s1, m_s2;
private float m_a1, m_a2;
private Mat33 m_K;
private float m_motorMass; // effective mass for motor/limit translational constraint.
internal PrismaticJoint(IWorldPool argWorld, PrismaticJointDef def) :
base(argWorld, def)
{
m_localAnchorA = new Vec2(def.localAnchorA);
m_localAnchorB = new Vec2(def.localAnchorB);
m_localXAxisA = new Vec2(def.localAxisA);
m_localXAxisA.normalize();
m_localYAxisA = new Vec2();
Vec2.crossToOutUnsafe(1f, m_localXAxisA, ref m_localYAxisA);
m_referenceAngle = def.referenceAngle;
m_impulse = new Vec3();
m_motorMass = 0.0f;
m_motorImpulse = 0.0f;
m_lowerTranslation = def.lowerTranslation;
m_upperTranslation = def.upperTranslation;
m_maxMotorForce = def.maxMotorForce;
m_motorSpeed = def.motorSpeed;
m_enableLimit = def.enableLimit;
m_enableMotor = def.enableMotor;
m_limitState = LimitState.INACTIVE;
m_K = new Mat33();
m_axis = new Vec2();
m_perp = new Vec2();
}
public Vec2 getLocalAnchorA()
{
return m_localAnchorA;
}
public Vec2 getLocalAnchorB()
{
return m_localAnchorB;
}
public override void getAnchorA(ref Vec2 argOut)
{
m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut);
}
public override void getAnchorB(ref Vec2 argOut)
{
m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut);
}
public override void getReactionForce(float inv_dt, ref Vec2 argOut)
{
Vec2 temp = pool.popVec2();
temp.set(m_axis);
temp.mulLocal(m_motorImpulse + m_impulse.z);
argOut.set(m_perp);
temp.mulLocal(m_impulse.x);
temp.addLocal(temp);
temp.mulLocal(inv_dt);
pool.pushVec2(1);
}
public override float getReactionTorque(float inv_dt)
{
return inv_dt*m_impulse.y;
}
/**
* Get the current joint translation, usually in meters.
*/
public float getJointSpeed()
{
Body bA = m_bodyA;
Body bB = m_bodyB;
Vec2 temp = pool.popVec2();
Vec2 rA = pool.popVec2();
Vec2 rB = pool.popVec2();
Vec2 p1 = pool.popVec2();
Vec2 p2 = pool.popVec2();
Vec2 d = pool.popVec2();
Vec2 axis = pool.popVec2();
Vec2 temp2 = pool.popVec2();
Vec2 temp3 = pool.popVec2();
temp.set(m_localAnchorA);
temp.subLocal(bA.m_sweep.localCenter);
Rot.mulToOutUnsafe(bA.m_xf.q, temp, ref rA);
temp.set(m_localAnchorB);
temp.subLocal(bB.m_sweep.localCenter);
Rot.mulToOutUnsafe(bB.m_xf.q, temp, ref rB);
p1.set(bA.m_sweep.c);
p1.addLocal(rA);
p2.set(bB.m_sweep.c);
p2.addLocal(rB);
d.set(p2);
d.subLocal(p1);
Rot.mulToOutUnsafe(bA.m_xf.q, m_localXAxisA, ref axis);
Vec2 vA = bA.m_linearVelocity;
Vec2 vB = bB.m_linearVelocity;
float wA = bA.m_angularVelocity;
float wB = bB.m_angularVelocity;
Vec2.crossToOutUnsafe(wA, axis, ref temp);
Vec2.crossToOutUnsafe(wB, rB, ref temp2);
Vec2.crossToOutUnsafe(wA, rA, ref temp3);
temp2.addLocal(vB);
temp2.subLocal(vA);
temp2.subLocal(temp3);
float speed = Vec2.dot(d, temp) + Vec2.dot(axis, temp2);
pool.pushVec2(9);
return speed;
}
public float getJointTranslation()
{
Vec2 pA = pool.popVec2(), pB = pool.popVec2(), axis = pool.popVec2();
m_bodyA.getWorldPointToOut(m_localAnchorA, ref pA);
m_bodyB.getWorldPointToOut(m_localAnchorB, ref pB);
m_bodyA.getWorldVectorToOutUnsafe(m_localXAxisA, ref axis);
pB.subLocal(pA);
float translation = Vec2.dot(pB, axis);
pool.pushVec2(3);
return translation;
}
/**
* Is the joint limit enabled?
*
* @return
*/
public bool isLimitEnabled()
{
return m_enableLimit;
}
/**
* Enable/disable the joint limit.
*
* @param flag
*/
public void enableLimit(bool flag)
{
if (flag != m_enableLimit)
{
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_enableLimit = flag;
m_impulse.z = 0.0f;
}
}
/**
* Get the lower joint limit, usually in meters.
*
* @return
*/
public float getLowerLimit()
{
return m_lowerTranslation;
}
/**
* Get the upper joint limit, usually in meters.
*
* @return
*/
public float getUpperLimit()
{
return m_upperTranslation;
}
/**
* Set the joint limits, usually in meters.
*
* @param lower
* @param upper
*/
public void setLimits(float lower, float upper)
{
Debug.Assert(lower <= upper);
if (lower != m_lowerTranslation || upper != m_upperTranslation)
{
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_lowerTranslation = lower;
m_upperTranslation = upper;
m_impulse.z = 0.0f;
}
}
/**
* Is the joint motor enabled?
*
* @return
*/
public bool isMotorEnabled()
{
return m_enableMotor;
}
/**
* Enable/disable the joint motor.
*
* @param flag
*/
public void enableMotor(bool flag)
{
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_enableMotor = flag;
}
/**
* Set the motor speed, usually in meters per second.
*
* @param speed
*/
public void setMotorSpeed(float speed)
{
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_motorSpeed = speed;
}
/**
* Get the motor speed, usually in meters per second.
*
* @return
*/
public float getMotorSpeed()
{
return m_motorSpeed;
}
/**
* Set the maximum motor force, usually in N.
*
* @param force
*/
public void setMaxMotorForce(float force)
{
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_maxMotorForce = force;
}
/**
* Get the current motor force, usually in N.
*
* @param inv_dt
* @return
*/
public float getMotorForce(float inv_dt)
{
return m_motorImpulse*inv_dt;
}
public float getMaxMotorForce()
{
return m_maxMotorForce;
}
public float getReferenceAngle()
{
return m_referenceAngle;
}
public Vec2 getLocalAxisA()
{
return m_localXAxisA;
}
public override void initVelocityConstraints(SolverData data)
{
m_indexA = m_bodyA.m_islandIndex;
m_indexB = m_bodyB.m_islandIndex;
m_localCenterA.set(m_bodyA.m_sweep.localCenter);
m_localCenterB.set(m_bodyB.m_sweep.localCenter);
m_invMassA = m_bodyA.m_invMass;
m_invMassB = m_bodyB.m_invMass;
m_invIA = m_bodyA.m_invI;
m_invIB = m_bodyB.m_invI;
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
Rot qA = pool.popRot();
Rot qB = pool.popRot();
Vec2 d = pool.popVec2();
Vec2 temp = pool.popVec2();
Vec2 rA = pool.popVec2();
Vec2 rB = pool.popVec2();
qA.set(aA);
qB.set(aB);
// Compute the effective masses.
d.set(m_localAnchorA);
d.subLocal(m_localCenterA);
Rot.mulToOutUnsafe(qA, d, ref rA);
d.set(m_localAnchorB);
d.subLocal(m_localCenterB);
Rot.mulToOutUnsafe(qB, d, ref rB);
d.set(cB);
d.subLocal(cA);
d.addLocal(rB);
d.subLocal(rA);
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
// Compute motor Jacobian and effective mass.
{
Rot.mulToOutUnsafe(qA, m_localXAxisA, ref m_axis);
temp.set(d);
temp.addLocal(rA);
m_a1 = Vec2.cross(temp, m_axis);
m_a2 = Vec2.cross(rB, m_axis);
m_motorMass = mA + mB + iA*m_a1*m_a1 + iB*m_a2*m_a2;
if (m_motorMass > 0.0f)
{
m_motorMass = 1.0f/m_motorMass;
}
}
// Prismatic constraint.
{
Rot.mulToOutUnsafe(qA, m_localYAxisA, ref m_perp);
temp.set(d);
temp.addLocal(rA);
m_s1 = Vec2.cross(temp, m_perp);
m_s2 = Vec2.cross(rB, m_perp);
float k11 = mA + mB + iA*m_s1*m_s1 + iB*m_s2*m_s2;
float k12 = iA*m_s1 + iB*m_s2;
float k13 = iA*m_s1*m_a1 + iB*m_s2*m_a2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
// For bodies with fixed rotation.
k22 = 1.0f;
}
float k23 = iA*m_a1 + iB*m_a2;
float k33 = mA + mB + iA*m_a1*m_a1 + iB*m_a2*m_a2;
m_K.ex.set(k11, k12, k13);
m_K.ey.set(k12, k22, k23);
m_K.ez.set(k13, k23, k33);
}
// Compute motor and limit terms.
if (m_enableLimit)
{
float jointTranslation = Vec2.dot(m_axis, d);
if (MathUtils.abs(m_upperTranslation - m_lowerTranslation) < 2.0f*Settings.linearSlop)
{
m_limitState = LimitState.EQUAL;
}
else if (jointTranslation <= m_lowerTranslation)
{
if (m_limitState != LimitState.AT_LOWER)
{
m_limitState = LimitState.AT_LOWER;
m_impulse.z = 0.0f;
}
}
else if (jointTranslation >= m_upperTranslation)
{
if (m_limitState != LimitState.AT_UPPER)
{
m_limitState = LimitState.AT_UPPER;
m_impulse.z = 0.0f;
}
}
else
{
m_limitState = LimitState.INACTIVE;
m_impulse.z = 0.0f;
}
}
else
{
m_limitState = LimitState.INACTIVE;
m_impulse.z = 0.0f;
}
if (m_enableMotor == false)
{
m_motorImpulse = 0.0f;
}
if (data.step.warmStarting)
{
// Account for variable time step.
m_impulse.mulLocal(data.step.dtRatio);
m_motorImpulse *= data.step.dtRatio;
Vec2 P = pool.popVec2();
temp.set(m_axis);
temp.mulLocal(m_motorImpulse + m_impulse.z);
P.set(m_perp);
P.mulLocal(m_impulse.x);
P.addLocal(temp);
float LA = m_impulse.x*m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z)*m_a1;
float LB = m_impulse.x*m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z)*m_a2;
vA.x -= mA*P.x;
vA.y -= mA*P.y;
wA -= iA*LA;
vB.x += mB*P.x;
vB.y += mB*P.y;
wB += iB*LB;
pool.pushVec2(1);
}
else
{
m_impulse.setZero();
m_motorImpulse = 0.0f;
}
// data.velocities[m_indexA].v.set(vA);
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v.set(vB);
data.velocities[m_indexB].w = wB;
pool.pushRot(2);
pool.pushVec2(4);
}
public override void solveVelocityConstraints(SolverData data)
{
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
Vec2 temp = pool.popVec2();
// Solve linear motor constraint.
if (m_enableMotor && m_limitState != LimitState.EQUAL)
{
temp.set(vB);
temp.subLocal(vA);
float Cdot = Vec2.dot(m_axis, temp) + m_a2*wB - m_a1*wA;
float impulse = m_motorMass*(m_motorSpeed - Cdot);
float oldImpulse = m_motorImpulse;
float maxImpulse = data.step.dt*m_maxMotorForce;
m_motorImpulse = MathUtils.clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
Vec2 P = pool.popVec2();
P.set(m_axis);
P.mulLocal(impulse);
float LA = impulse*m_a1;
float LB = impulse*m_a2;
vA.x -= mA*P.x;
vA.y -= mA*P.y;
wA -= iA*LA;
vB.x += mB*P.x;
vB.y += mB*P.y;
wB += iB*LB;
pool.pushVec2(1);
}
Vec2 Cdot1 = pool.popVec2();
temp.set(vB);
temp.subLocal(vA);
Cdot1.x = Vec2.dot(m_perp, temp) + m_s2*wB - m_s1*wA;
Cdot1.y = wB - wA;
// System.ref.println(Cdot1);
if (m_enableLimit && m_limitState != LimitState.INACTIVE)
{
// Solve prismatic and limit constraint in block form.
float Cdot2;
temp.set(vB);
temp.subLocal(vA);
Cdot2 = Vec2.dot(m_axis, temp) + m_a2*wB - m_a1*wA;
Vec3 Cdot = pool.popVec3();
Cdot.set(Cdot1.x, Cdot1.y, Cdot2);
Vec3 f1 = pool.popVec3();
Vec3 df = pool.popVec3();
f1.set(m_impulse);
Cdot.negateLocal();
m_K.solve33ToOut(Cdot, ref df);
// Cdot.negateLocal(); not used anymore
m_impulse.addLocal(df);
if (m_limitState == LimitState.AT_LOWER)
{
m_impulse.z = MathUtils.max(m_impulse.z, 0.0f);
}
else if (m_limitState == LimitState.AT_UPPER)
{
m_impulse.z = MathUtils.min(m_impulse.z, 0.0f);
}
// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) +
// f1(1:2)
Vec2 b = pool.popVec2();
Vec2 f2r = pool.popVec2();
temp.set(m_K.ez.x, m_K.ez.y);
temp.mulLocal(m_impulse.z - f1.z);
b.set(Cdot1);
b.negateLocal();
b.subLocal(temp);
m_K.solve22ToOut(b, ref f2r);
f2r.addLocal(f1.x, f1.y);
m_impulse.x = f2r.x;
m_impulse.y = f2r.y;
df.set(m_impulse).subLocal(f1);
Vec2 P = pool.popVec2();
temp.set(m_axis);
temp.mulLocal(df.z);
P.set(m_perp);
P.mulLocal(df.x);
P.addLocal(temp);
float LA = df.x*m_s1 + df.y + df.z*m_a1;
float LB = df.x*m_s2 + df.y + df.z*m_a2;
vA.x -= mA*P.x;
vA.y -= mA*P.y;
wA -= iA*LA;
vB.x += mB*P.x;
vB.y += mB*P.y;
wB += iB*LB;
pool.pushVec2(3);
pool.pushVec3(3);
}
else
{
// Limit is inactive, just solve the prismatic constraint in block form.
Vec2 df = pool.popVec2();
Cdot1.negateLocal();
m_K.solve22ToOut(Cdot1, ref df);
Cdot1.negateLocal();
m_impulse.x += df.x;
m_impulse.y += df.y;
Vec2 P = pool.popVec2();
P.set(m_perp);
P.mulLocal(df.x);
float LA = df.x*m_s1 + df.y;
float LB = df.x*m_s2 + df.y;
vA.x -= mA*P.x;
vA.y -= mA*P.y;
wA -= iA*LA;
vB.x += mB*P.x;
vB.y += mB*P.y;
wB += iB*LB;
pool.pushVec2(2);
}
// data.velocities[m_indexA].v.set(vA);
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v.set(vB);
data.velocities[m_indexB].w = wB;
pool.pushVec2(2);
}
public override bool solvePositionConstraints(SolverData data)
{
Rot qA = pool.popRot();
Rot qB = pool.popRot();
Vec2 rA = pool.popVec2();
Vec2 rB = pool.popVec2();
Vec2 d = pool.popVec2();
Vec2 axis = pool.popVec2();
Vec2 perp = pool.popVec2();
Vec2 temp = pool.popVec2();
Vec2 C1 = pool.popVec2();
Vec3 impulse = pool.popVec3();
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
qA.set(aA);
qB.set(aB);
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
// Compute fresh Jacobians
temp.set(m_localAnchorA);
temp.subLocal(m_localCenterA);
Rot.mulToOutUnsafe(qA, temp, ref rA);
temp.set(m_localAnchorB);
temp.subLocal(m_localCenterB);
Rot.mulToOutUnsafe(qB, temp, ref rB);
d.set(cB);
d.addLocal(rB);
d.subLocal(cA);
d.subLocal(rA);
Rot.mulToOutUnsafe(qA, m_localXAxisA, ref axis);
temp.set(d);
temp.addLocal(rA);
float a1 = Vec2.cross(temp, axis);
float a2 = Vec2.cross(rB, axis);
Rot.mulToOutUnsafe(qA, m_localYAxisA, ref perp);
temp.set(d);
temp.addLocal(rA);
float s1 = Vec2.cross(temp, perp);
float s2 = Vec2.cross(rB, perp);
C1.x = Vec2.dot(perp, d);
C1.y = aB - aA - m_referenceAngle;
float linearError = MathUtils.abs(C1.x);
float angularError = MathUtils.abs(C1.y);
bool active = false;
float C2 = 0.0f;
if (m_enableLimit)
{
float translation = Vec2.dot(axis, d);
if (MathUtils.abs(m_upperTranslation - m_lowerTranslation) < 2.0f*Settings.linearSlop)
{
// Prevent large angular corrections
C2 =
MathUtils.clamp(translation, -Settings.maxLinearCorrection,
Settings.maxLinearCorrection);
linearError = MathUtils.max(linearError, MathUtils.abs(translation));
active = true;
}
else if (translation <= m_lowerTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 =
MathUtils.clamp(translation - m_lowerTranslation + Settings.linearSlop,
-Settings.maxLinearCorrection, 0.0f);
linearError = MathUtils.max(linearError, m_lowerTranslation - translation);
active = true;
}
else if (translation >= m_upperTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 =
MathUtils.clamp(translation - m_upperTranslation - Settings.linearSlop, 0.0f,
Settings.maxLinearCorrection);
linearError = MathUtils.max(linearError, translation - m_upperTranslation);
active = true;
}
}
if (active)
{
float k11 = mA + mB + iA*s1*s1 + iB*s2*s2;
float k12 = iA*s1 + iB*s2;
float k13 = iA*s1*a1 + iB*s2*a2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
// For fixed rotation
k22 = 1.0f;
}
float k23 = iA*a1 + iB*a2;
float k33 = mA + mB + iA*a1*a1 + iB*a2*a2;
Mat33 K = pool.popMat33();
K.ex.set(k11, k12, k13);
K.ey.set(k12, k22, k23);
K.ez.set(k13, k23, k33);
Vec3 C = pool.popVec3();
C.x = C1.x;
C.y = C1.y;
C.z = C2;
C.negateLocal();
K.solve33ToOut(C, ref impulse);
pool.pushVec3(1);
pool.pushMat33(1);
}
else
{
float k11 = mA + mB + iA*s1*s1 + iB*s2*s2;
float k12 = iA*s1 + iB*s2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
k22 = 1.0f;
}
Mat22 K = pool.popMat22();
K.ex.set(k11, k12);
K.ey.set(k12, k22);
// temp is impulse1
C1.negateLocal();
K.solveToOut(C1, ref temp);
C1.negateLocal();
impulse.x = temp.x;
impulse.y = temp.y;
impulse.z = 0.0f;
pool.pushMat22(1);
}
float Px = impulse.x*perp.x + impulse.z*axis.x;
float Py = impulse.x*perp.y + impulse.z*axis.y;
float LA = impulse.x*s1 + impulse.y + impulse.z*a1;
float LB = impulse.x*s2 + impulse.y + impulse.z*a2;
cA.x -= mA*Px;
cA.y -= mA*Py;
aA -= iA*LA;
cB.x += mB*Px;
cB.y += mB*Py;
aB += iB*LB;
// data.positions[m_indexA].c.set(cA);
data.positions[m_indexA].a = aA;
// data.positions[m_indexB].c.set(cB);
data.positions[m_indexB].a = aB;
pool.pushVec2(7);
pool.pushVec3(1);
pool.pushRot(2);
return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache.Affinity;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Log;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Impl.Unmanaged.Jni;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Resource;
using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// This class defines a factory for the main Ignite API.
/// <p/>
/// Use <see cref="Start()"/> method to start Ignite with default configuration.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public static class Ignition
{
/// <summary>
/// Default configuration section name.
/// </summary>
public const string ConfigurationSectionName = "igniteConfiguration";
/// <summary>
/// Default configuration section name.
/// </summary>
public const string ClientConfigurationSectionName = "igniteClientConfiguration";
/** */
private static readonly object SyncRoot = new object();
/** GC warning flag. */
private static int _gcWarn;
/** */
private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>();
/** Current DLL name. */
private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
/** Startup info. */
[ThreadStatic]
private static Startup _startup;
/** Client mode flag. */
[ThreadStatic]
private static bool _clientMode;
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static Ignition()
{
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
}
/// <summary>
/// Gets or sets a value indicating whether Ignite should be started in client mode.
/// Client nodes cannot hold data in caches.
/// </summary>
public static bool ClientMode
{
get { return _clientMode; }
set { _clientMode = value; }
}
/// <summary>
/// Starts Ignite with default configuration. By default this method will
/// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c>
/// configuration file. If such file is not found, then all system defaults will be used.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start()
{
return Start(new IgniteConfiguration());
}
/// <summary>
/// Starts all grids specified within given Spring XML configuration file. If Ignite with given name
/// is already started, then exception is thrown. In this case all instances that may
/// have been started so far will be stopped too.
/// </summary>
/// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be
/// absolute or relative to IGNITE_HOME.</param>
/// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st
/// found instance is returned.</returns>
public static IIgnite Start(string springCfgPath)
{
return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath});
}
/// <summary>
/// Reads <see cref="IgniteConfiguration"/> from application configuration
/// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/>
/// name and starts Ignite.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration()
{
// ReSharper disable once IntroduceOptionalParameters.Global
return StartFromApplicationConfiguration(ConfigurationSectionName);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration"/> from application configuration
/// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration(string sectionName)
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection;
if (section == null)
throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'",
typeof(IgniteConfigurationSection).Name, sectionName));
if (section.IgniteConfiguration == null)
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteConfigurationSection).Name, sectionName));
return Start(section.IgniteConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration" /> from application configuration
/// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <param name="configPath">Path to the configuration file.</param>
/// <returns>Started Ignite.</returns>
public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath)
{
var section = GetConfigurationSection<IgniteConfigurationSection>(sectionName, configPath);
if (section.IgniteConfiguration == null)
{
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteConfigurationSection).Name, sectionName, configPath));
}
return Start(section.IgniteConfiguration);
}
/// <summary>
/// Gets the configuration section.
/// </summary>
private static T GetConfigurationSection<T>(string sectionName, string configPath)
where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath");
var fileMap = GetConfigMap(configPath);
var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var section = config.GetSection(sectionName) as T;
if (section == null)
{
throw new ConfigurationErrorsException(
string.Format("Could not find {0} with name '{1}' in file '{2}'",
typeof(T).Name, sectionName, configPath));
}
return section;
}
/// <summary>
/// Gets the configuration file map.
/// </summary>
private static ExeConfigurationFileMap GetConfigMap(string fileName)
{
var fullFileName = Path.GetFullPath(fileName);
if (!File.Exists(fullFileName))
throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName);
return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName };
}
/// <summary>
/// Starts Ignite with given configuration.
/// </summary>
/// <returns>Started Ignite.</returns>
public static IIgnite Start(IgniteConfiguration cfg)
{
IgniteArgumentCheck.NotNull(cfg, "cfg");
cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused.
lock (SyncRoot)
{
// 0. Init logger
var log = cfg.Logger ?? new JavaLogger();
log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version);
// 1. Check GC settings.
CheckServerGc(cfg, log);
// 2. Create context.
JvmDll.Load(cfg.JvmDllPath, log);
var cbs = IgniteManager.CreateJvmContext(cfg, log);
var env = cbs.Jvm.AttachCurrentThread();
log.Debug("JVM started.");
var gridName = cfg.IgniteInstanceName;
if (cfg.AutoGenerateIgniteInstanceName)
{
gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid();
}
// 3. Create startup object which will guide us through the rest of the process.
_startup = new Startup(cfg, cbs);
PlatformJniTarget interopProc = null;
try
{
// 4. Initiate Ignite start.
UU.IgnitionStart(env, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null, cbs.IgniteId,
cfg.RedirectJavaConsoleOutput);
// 5. At this point start routine is finished. We expect STARTUP object to have all necessary data.
var node = _startup.Ignite;
interopProc = (PlatformJniTarget)node.InteropProcessor;
var javaLogger = log as JavaLogger;
if (javaLogger != null)
{
javaLogger.SetIgnite(node);
}
// 6. On-start callback (notify lifecycle components).
node.OnStart();
Nodes[new NodeKey(_startup.Name)] = node;
return node;
}
catch (Exception ex)
{
// 1. Perform keys cleanup.
string name = _startup.Name;
if (name != null)
{
NodeKey key = new NodeKey(name);
if (Nodes.ContainsKey(key))
Nodes.Remove(key);
}
// 2. Stop Ignite node if it was started.
if (interopProc != null)
UU.IgnitionStop(gridName, true);
// 3. Throw error further (use startup error if exists because it is more precise).
if (_startup.Error != null)
{
// Wrap in a new exception to preserve original stack trace.
throw new IgniteException("Failed to start Ignite.NET, check inner exception for details",
_startup.Error);
}
var jex = ex as JavaException;
if (jex == null)
{
throw;
}
throw ExceptionUtils.GetException(null, jex);
}
finally
{
var ignite = _startup.Ignite;
_startup = null;
if (ignite != null)
{
ignite.ProcessorReleaseStart();
}
}
}
}
/// <summary>
/// Check whether GC is set to server mode.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="log">Log.</param>
private static void CheckServerGc(IgniteConfiguration cfg, ILogger log)
{
if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0)
log.Warn("GC server mode is not enabled, this could lead to less " +
"than optimal performance on multi-core machines (to enable see " +
"http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx).");
}
/// <summary>
/// Prepare callback invoked from Java.
/// </summary>
/// <param name="inStream">Input stream with data.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
/// <param name="log">Log.</param>
internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream,
HandleRegistry handleRegistry, ILogger log)
{
try
{
BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream);
PrepareConfiguration(reader, outStream, log);
PrepareLifecycleHandlers(reader, outStream, handleRegistry);
PrepareAffinityFunctions(reader, outStream);
outStream.SynchronizeOutput();
}
catch (Exception e)
{
_startup.Error = e;
throw;
}
}
/// <summary>
/// Prepare configuration.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Response stream.</param>
/// <param name="log">Log.</param>
private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log)
{
// 1. Load assemblies.
IgniteConfiguration cfg = _startup.Configuration;
LoadAllAssemblies(cfg.Assemblies);
ICollection<string> cfgAssembllies;
BinaryConfiguration binaryCfg;
BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg);
LoadAllAssemblies(cfgAssembllies);
// 2. Create marshaller only after assemblies are loaded.
if (cfg.BinaryConfiguration == null)
cfg.BinaryConfiguration = binaryCfg;
_startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log);
// 3. Send configuration details to Java
cfg.Validate(log);
// Use system marshaller.
cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream));
}
/// <summary>
/// Prepare lifecycle handlers.
/// </summary>
/// <param name="reader">Reader.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="handleRegistry">Handle registry.</param>
private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream,
HandleRegistry handleRegistry)
{
IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder>
{
new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events
};
// 1. Read beans defined in Java.
int cnt = reader.ReadInt();
for (int i = 0; i < cnt; i++)
beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader)));
// 2. Append beans defined in local configuration.
ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers;
if (nativeBeans != null)
{
foreach (ILifecycleHandler nativeBean in nativeBeans)
beans.Add(new LifecycleHandlerHolder(nativeBean));
}
// 3. Write bean pointers to Java stream.
outStream.WriteInt(beans.Count);
foreach (LifecycleHandlerHolder bean in beans)
outStream.WriteLong(handleRegistry.AllocateCritical(bean));
// 4. Set beans to STARTUP object.
_startup.LifecycleHandlers = beans;
}
/// <summary>
/// Prepares the affinity functions.
/// </summary>
private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream)
{
var cnt = reader.ReadInt();
var writer = reader.Marshaller.StartMarshal(outStream);
for (var i = 0; i < cnt; i++)
{
var objHolder = new ObjectInfoHolder(reader);
AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder);
}
}
/// <summary>
/// Creates an object and sets the properties.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Resulting object.</returns>
private static T CreateObject<T>(IBinaryRawReader reader)
{
return IgniteUtils.CreateInstance<T>(reader.ReadString(),
reader.ReadDictionaryAsGeneric<string, object>());
}
/// <summary>
/// Kernal start callback.
/// </summary>
/// <param name="interopProc">Interop processor.</param>
/// <param name="stream">Stream.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "PlatformJniTarget is passed further")]
internal static void OnStart(GlobalRef interopProc, IBinaryStream stream)
{
try
{
// 1. Read data and leave critical state ASAP.
BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream);
// ReSharper disable once PossibleInvalidOperationException
var name = reader.ReadString();
// 2. Set ID and name so that Start() method can use them later.
_startup.Name = name;
if (Nodes.ContainsKey(new NodeKey(name)))
throw new IgniteException("Ignite with the same name already started: " + name);
_startup.Ignite = new Ignite(_startup.Configuration, _startup.Name,
new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller,
_startup.LifecycleHandlers, _startup.Callbacks);
}
catch (Exception e)
{
// 5. Preserve exception to throw it later in the "Start" method and throw it further
// to abort startup in Java.
_startup.Error = e;
throw;
}
}
/// <summary>
/// Load assemblies.
/// </summary>
/// <param name="assemblies">Assemblies.</param>
private static void LoadAllAssemblies(IEnumerable<string> assemblies)
{
if (assemblies != null)
{
foreach (var s in assemblies)
{
LoadAssembly(s);
}
}
}
/// <summary>
/// Load assembly from file, directory, or full name.
/// </summary>
/// <param name="asm">Assembly file, directory, or full name.</param>
internal static void LoadAssembly(string asm)
{
// 1. Try loading as directory.
if (Directory.Exists(asm))
{
string[] files = Directory.GetFiles(asm, "*.dll");
foreach (string dllPath in files)
{
if (!SelfAssembly(dllPath))
{
try
{
Assembly.LoadFile(dllPath);
}
catch (BadImageFormatException)
{
// No-op.
}
}
}
return;
}
// 2. Try loading using full-name.
try
{
Assembly assembly = Assembly.Load(asm);
if (assembly != null)
return;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + asm, e);
}
// 3. Try loading using file path.
try
{
Assembly assembly = Assembly.LoadFrom(asm);
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (assembly != null)
return;
}
catch (Exception e)
{
if (!(e is FileNotFoundException || e is FileLoadException))
throw new IgniteException("Failed to load assembly: " + asm, e);
}
// 4. Not found, exception.
throw new IgniteException("Failed to load assembly: " + asm);
}
/// <summary>
/// Whether assembly points to Ignite binary.
/// </summary>
/// <param name="assembly">Assembly to check..</param>
/// <returns><c>True</c> if this is one of GG assemblies.</returns>
private static bool SelfAssembly(string assembly)
{
return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p />
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.</param>
/// <returns>
/// An instance of named grid.
/// </returns>
/// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception>
public static IIgnite GetIgnite(string name)
{
var ignite = TryGetIgnite(name);
if (ignite == null)
throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name);
return ignite;
}
/// <summary>
/// Gets the default Ignite instance with null name, or an instance with any name when there is only one.
/// <para />
/// Note that caller of this method should not assume that it will return the same instance every time.
/// </summary>
/// <returns>Default Ignite instance.</returns>
/// <exception cref="IgniteException">When there is no matching Ignite instance.</exception>
public static IIgnite GetIgnite()
{
lock (SyncRoot)
{
if (Nodes.Count == 0)
{
throw new IgniteException("Failed to get default Ignite instance: " +
"there are no instances started.");
}
if (Nodes.Count == 1)
{
return Nodes.Single().Value;
}
Ignite result;
if (Nodes.TryGetValue(new NodeKey(null), out result))
{
return result;
}
throw new IgniteException(string.Format("Failed to get default Ignite instance: " +
"there are {0} instances started, and none of them has null name.", Nodes.Count));
}
}
/// <summary>
/// Gets all started Ignite instances.
/// </summary>
/// <returns>All Ignite instances.</returns>
public static ICollection<IIgnite> GetAll()
{
lock (SyncRoot)
{
return Nodes.Values.ToArray();
}
}
/// <summary>
/// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string,
/// then default no-name Ignite will be returned. Note that caller of this method
/// should not assume that it will return the same instance every time.
/// <p/>
/// Note that single process can run multiple Ignite instances and every Ignite instance (and its
/// node) can belong to a different grid. Ignite name defines what grid a particular Ignite
/// instance (and correspondingly its node) belongs to.
/// </summary>
/// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>,
/// then Ignite instance belonging to a default no-name Ignite will be returned.
/// </param>
/// <returns>An instance of named grid, or null.</returns>
public static IIgnite TryGetIgnite(string name)
{
lock (SyncRoot)
{
Ignite result;
return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result;
}
}
/// <summary>
/// Gets the default Ignite instance with null name, or an instance with any name when there is only one.
/// Returns null when there are no Ignite instances started, or when there are more than one,
/// and none of them has null name.
/// </summary>
/// <returns>An instance of default no-name grid, or null.</returns>
public static IIgnite TryGetIgnite()
{
lock (SyncRoot)
{
if (Nodes.Count == 1)
{
return Nodes.Single().Value;
}
return TryGetIgnite(null);
}
}
/// <summary>
/// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then
/// all jobs currently executing on local node will be interrupted. If
/// grid name is <c>null</c>, then default no-name Ignite will be stopped.
/// </summary>
/// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param>
/// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled
/// by calling <c>ComputeJob.cancel</c>method.</param>
/// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c>
/// othwerwise (the instance with given <c>name</c> was not found).</returns>
public static bool Stop(string name, bool cancel)
{
lock (SyncRoot)
{
NodeKey key = new NodeKey(name);
Ignite node;
if (!Nodes.TryGetValue(key, out node))
return false;
node.Stop(cancel);
Nodes.Remove(key);
GC.Collect();
return true;
}
}
/// <summary>
/// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then
/// all jobs currently executing on local node will be interrupted.
/// </summary>
/// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled
/// by calling <c>ComputeJob.Cancel()</c> method.</param>
public static void StopAll(bool cancel)
{
lock (SyncRoot)
{
while (Nodes.Count > 0)
{
var entry = Nodes.First();
entry.Value.Stop(cancel);
Nodes.Remove(entry.Key);
}
}
GC.Collect();
}
/// <summary>
/// Connects Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <param name="clientConfiguration">The client configuration.</param>
/// <returns>Ignite client instance.</returns>
public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration)
{
IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration");
return new IgniteClient(clientConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteClientConfiguration"/> from application configuration
/// <see cref="IgniteClientConfigurationSection"/> with <see cref="ClientConfigurationSectionName"/>
/// name and connects Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <returns>Ignite client instance.</returns>
public static IIgniteClient StartClient()
{
// ReSharper disable once IntroduceOptionalParameters.Global
return StartClient(ClientConfigurationSectionName);
}
/// <summary>
/// Reads <see cref="IgniteClientConfiguration" /> from application configuration
/// <see cref="IgniteClientConfigurationSection" /> with specified name and connects
/// Ignite lightweight (thin) client to an Ignite node.
/// <para />
/// Thin client connects to an existing Ignite node with a socket and does not start JVM in process.
/// </summary>
/// <param name="sectionName">Name of the configuration section.</param>
/// <returns>Ignite client instance.</returns>
public static IIgniteClient StartClient(string sectionName)
{
IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName");
var section = ConfigurationManager.GetSection(sectionName) as IgniteClientConfigurationSection;
if (section == null)
{
throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'.",
typeof(IgniteClientConfigurationSection).Name, sectionName));
}
if (section.IgniteClientConfiguration == null)
{
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteClientConfigurationSection).Name, sectionName));
}
return StartClient(section.IgniteClientConfiguration);
}
/// <summary>
/// Reads <see cref="IgniteConfiguration" /> from application configuration
/// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <param name="configPath">Path to the configuration file.</param>
/// <returns>Started Ignite.</returns>
public static IIgniteClient StartClient(string sectionName, string configPath)
{
var section = GetConfigurationSection<IgniteClientConfigurationSection>(sectionName, configPath);
if (section.IgniteClientConfiguration == null)
{
throw new ConfigurationErrorsException(
string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " +
"but not present in configuration.",
typeof(IgniteClientConfigurationSection).Name, sectionName, configPath));
}
return StartClient(section.IgniteClientConfiguration);
}
/// <summary>
/// Handles the DomainUnload event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
// If we don't stop Ignite.NET on domain unload,
// we end up with broken instances in Java (invalid callbacks, etc).
// IIS, in particular, is known to unload and reload domains within the same process.
StopAll(true);
}
/// <summary>
/// Grid key. Workaround for non-null key requirement in Dictionary.
/// </summary>
private class NodeKey
{
/** */
private readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="NodeKey"/> class.
/// </summary>
/// <param name="name">The name.</param>
internal NodeKey(string name)
{
_name = name;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
var other = obj as NodeKey;
return other != null && Equals(_name, other._name);
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _name == null ? 0 : _name.GetHashCode();
}
}
/// <summary>
/// Value object to pass data between .Net methods during startup bypassing Java.
/// </summary>
private class Startup
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="cbs"></param>
internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs)
{
Configuration = cfg;
Callbacks = cbs;
}
/// <summary>
/// Configuration.
/// </summary>
internal IgniteConfiguration Configuration { get; private set; }
/// <summary>
/// Gets unmanaged callbacks.
/// </summary>
internal UnmanagedCallbacks Callbacks { get; private set; }
/// <summary>
/// Lifecycle handlers.
/// </summary>
internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; }
/// <summary>
/// Node name.
/// </summary>
internal string Name { get; set; }
/// <summary>
/// Marshaller.
/// </summary>
internal Marshaller Marshaller { get; set; }
/// <summary>
/// Start error.
/// </summary>
internal Exception Error { get; set; }
/// <summary>
/// Gets or sets the ignite.
/// </summary>
internal Ignite Ignite { get; set; }
}
/// <summary>
/// Internal handler for event notification.
/// </summary>
private class InternalLifecycleHandler : ILifecycleHandler
{
/** */
#pragma warning disable 649 // unused field
[InstanceResource] private readonly IIgnite _ignite;
/** <inheritdoc /> */
public void OnLifecycleEvent(LifecycleEventType evt)
{
if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null)
((Ignite) _ignite).BeforeNodeStop();
}
}
}
}
| |
// 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 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// HttpRedirects operations.
/// </summary>
public partial class HttpRedirects : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpRedirects
{
/// <summary>
/// Initializes a new instance of the HttpRedirects class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public HttpRedirects(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head300", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/300").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<string>>> Get300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get300", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/300").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<IList<string>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MultipleChoices"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<IList<string>>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head301", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/301").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get301", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/301").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put true Boolean value in request returns 301. This request should not be
/// automatically redirected, but should return the received 301 to the
/// caller for evaluation
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put301", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/301").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "MovedPermanently")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head302", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/302").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get302", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/302").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch true Boolean value in request returns 302. This request should not
/// be automatically redirected, but should return the received 302 to the
/// caller for evaluation
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch302", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/302").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "Redirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post true Boolean value in request returns 303. This request should be
/// automatically redirected usign a get, ultimately returning a 200 status
/// code
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post303", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/303").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "SeeOther")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Redirect with 307, resulting in a 200 success
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Head307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head307", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Redirect get with 307, resulting in a 200 success
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Get307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Get307", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Put307", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Patch redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Patch307", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Post redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post307", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Delete redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Delete307", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/redirect/307").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("DELETE");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "TemporaryRedirect")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
namespace EyeInTheSky.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using Castle.Core.Logging;
using EyeInTheSky.Model;
using EyeInTheSky.Model.Interfaces;
using EyeInTheSky.Model.StalkNodes.BaseNodes;
using EyeInTheSky.Services.Interfaces;
using Stwalkerster.IrcClient.Model;
public class SubscriptionHelper : ISubscriptionHelper
{
private readonly ILogger logger;
private readonly IBotUserConfiguration botUserConfiguration;
private readonly IChannelConfiguration channelConfiguration;
public SubscriptionHelper(
ILogger logger,
IBotUserConfiguration botUserConfiguration,
IChannelConfiguration channelConfiguration)
{
this.logger = logger;
this.botUserConfiguration = botUserConfiguration;
this.channelConfiguration = channelConfiguration;
}
public bool SubscribeStalk(IrcUserMask mask, IIrcChannel channel, IStalk stalk, out SubscriptionSource source)
{
if (channel.Identifier != stalk.Channel)
{
throw new Exception("Mismatch between stalk channel and channel!");
}
var stalkSubscriber = stalk.Subscribers.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());
var channelSubscriber = channel.Users.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());
this.logger.DebugFormat(
"Subscription request for {0} to {1} in {2}",
mask,
stalk.Identifier,
channel.Identifier);
if (stalkSubscriber != null)
{
if (stalkSubscriber.Subscribed)
{
if (channelSubscriber != null)
{
if (channelSubscriber.Subscribed)
{
// subscribed to channel
// subscribed to stalk
this.logger.WarnFormat(
"Found subscription request from stalk- ({0}) and channel-subscribed ({1}) user ({2})",
stalk.Identifier,
channel.Identifier,
mask);
this.logger.DebugFormat(
"Unsubscribing from stalk - already subscribed to stalk and channel");
stalk.Subscribers.Remove(stalkSubscriber);
source = SubscriptionSource.Channel;
return false;
}
else
{
// not subscribed to channel
// subscribed to stalk
this.logger.DebugFormat("Not subscribing - already subscribed to stalk");
source = SubscriptionSource.Stalk;
return false;
}
}
else
{
// not subscribed to channel
// subscribed to stalk
this.logger.DebugFormat("Not subscribing - already subscribed to stalk");
source = SubscriptionSource.Stalk;
return false;
}
}
else
{
if (channelSubscriber != null)
{
if (channelSubscriber.Subscribed)
{
// forcibly unsubscribed from stalk
// subscribed to channel
this.logger.DebugFormat("Removing forced unsubscribe - already subscribed to channel");
stalk.Subscribers.Remove(stalkSubscriber);
source = SubscriptionSource.Channel;
return true;
}
else
{
// forcibly unsubscribed from stalk
// not subscribed to channel
this.logger.WarnFormat(
"Found subscription request from stalk-force-unsubscribed ({0}) and channel-unsubscribed ({1}) user ({2})",
stalk.Identifier,
channel.Identifier,
mask);
this.logger.DebugFormat("Converting forced unsubscribe to stalk subscription");
stalkSubscriber.Subscribed = true;
source = SubscriptionSource.Stalk;
return true;
}
}
else
{
// forcibly unsubscribed from stalk
// not subscribed to channel
this.logger.WarnFormat(
"Found subscription request from stalk-force-unsubscribed ({0}) and channel-unsubscribed ({1}) user ({2})",
stalk.Identifier,
channel.Identifier,
mask);
this.logger.DebugFormat("Converting forced unsubscribe to stalk subscription");
stalkSubscriber.Subscribed = true;
source = SubscriptionSource.Stalk;
return true;
}
}
}
else
{
if (channelSubscriber != null)
{
if (channelSubscriber.Subscribed)
{
// already subscribed to channel
// not subscribed to stalk
source = SubscriptionSource.Channel;
return false;
}
else
{
// not subscribed to channel
// not subscribed to stalk
this.logger.DebugFormat("Subscribing to stalk");
stalkSubscriber = new StalkUser(mask, true);
stalk.Subscribers.Add(stalkSubscriber);
source = SubscriptionSource.Stalk;
return true;
}
}
else
{
// not subscribed to channel
// not subscribed to stalk
this.logger.DebugFormat("Subscribing to stalk");
stalkSubscriber = new StalkUser(mask, true);
stalk.Subscribers.Add(stalkSubscriber);
source = SubscriptionSource.Stalk;
return true;
}
}
}
public bool UnsubscribeStalk(IrcUserMask mask, IIrcChannel channel, IStalk stalk, out SubscriptionSource source)
{
if (channel.Identifier != stalk.Channel)
{
throw new Exception("Mismatch between stalk channel and channel!");
}
var stalkSubscriber = stalk.Subscribers.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());
var channelSubscriber = channel.Users.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());
this.logger.DebugFormat(
"Unsubscription request for {0} to {1} in {2}",
mask,
stalk.Identifier,
channel.Identifier);
if (stalkSubscriber != null)
{
if (stalkSubscriber.Subscribed)
{
if (channelSubscriber != null)
{
if (channelSubscriber.Subscribed)
{
// subscribed to channel
// subscribed to stalk
this.logger.WarnFormat(
"Found unsubscription request from stalk- ({0}) and channel-subscribed ({1}) user ({2})",
stalk.Identifier,
channel.Identifier,
mask);
this.logger.DebugFormat(
"Forcing unsubscribe from stalk - already subscribed to stalk and channel");
stalkSubscriber.Subscribed = false;
source = SubscriptionSource.Stalk;
return true;
}
else
{
// not subscribed to channel
// subscribed to stalk
this.logger.DebugFormat("Unsubscribing from stalk");
stalk.Subscribers.Remove(stalkSubscriber);
source = SubscriptionSource.Stalk;
return true;
}
}
else
{
// not subscribed to channel
// subscribed to stalk
this.logger.DebugFormat("Unsubscribing from stalk");
stalk.Subscribers.Remove(stalkSubscriber);
source = SubscriptionSource.Stalk;
return true;
}
}
else
{
if (channelSubscriber != null)
{
if (channelSubscriber.Subscribed)
{
// forcibly unsubscribed from stalk
// subscribed to channel
this.logger.DebugFormat("Already forcibly unsubscribed from stalk");
source = SubscriptionSource.Stalk;
return false;
}
else
{
// forcibly unsubscribed from stalk
// not subscribed to channel
this.logger.WarnFormat(
"Found unsubscription request from stalk-forcibly-unsubscribed ({0}) and channel-unsubscribed ({1}) user ({2})",
stalk.Identifier,
channel.Identifier,
mask);
this.logger.DebugFormat("Removing stalk subscription");
stalk.Subscribers.Remove(stalkSubscriber);
source = SubscriptionSource.Stalk;
return false;
}
}
else
{
// forcibly unsubscribed from stalk
// not subscribed to channel
this.logger.WarnFormat(
"Found unsubscription request from stalk-forcibly-unsubscribed ({0}) and channel-unsubscribed ({1}) user ({2})",
stalk.Identifier,
channel.Identifier,
mask);
this.logger.DebugFormat("Removing stalk subscription");
stalk.Subscribers.Remove(stalkSubscriber);
source = SubscriptionSource.Stalk;
return false;
}
}
}
else
{
if (channelSubscriber != null)
{
if (channelSubscriber.Subscribed)
{
// already subscribed to channel
// not subscribed to stalk
this.logger.DebugFormat("Forcing unsubscribe");
stalkSubscriber = new StalkUser(mask, false);
stalk.Subscribers.Add(stalkSubscriber);
source = SubscriptionSource.Stalk;
return true;
}
else
{
// not subscribed to channel
// not subscribed to stalk
this.logger.DebugFormat("Already not subscribed!");
source = SubscriptionSource.None;
return false;
}
}
else
{
// not subscribed to channel
// not subscribed to stalk
this.logger.DebugFormat("Already not subscribed!");
source = SubscriptionSource.None;
return false;
}
}
}
public bool IsSubscribedToStalk(IBotUser botUser, IIrcChannel channel, IStalk stalk)
{
return this.GetUserSubscriptionsToStalk(channel, stalk)
.Where(x => x.IsSubscribed)
.Any(x => Equals(x.BotUser, botUser));
}
public bool SubscribeChannel(IrcUserMask mask, IIrcChannel channel)
{
var channelUser = channel.Users.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());
if (channelUser == null)
{
channelUser = new ChannelUser(mask);
channel.Users.Add(channelUser);
}
if (channelUser.Subscribed)
{
return false;
}
else
{
channelUser.Subscribed = true;
// remove any overrides
var channelSubscriptions = this.GetUserStalkSubscriptionsInChannel(new BotUser(mask), channel);
foreach (var subscriptionResult in channelSubscriptions.Where(x => x.Source == SubscriptionSource.Stalk))
{
subscriptionResult.Stalk.Subscribers.RemoveAll(x => x.Mask.Equals(mask));
}
return true;
}
}
public bool UnsubscribeChannel(IrcUserMask mask, IIrcChannel channel)
{
var channelUser = channel.Users.FirstOrDefault(x => x.Mask.ToString() == mask.ToString());
if (channelUser == null)
{
return false;
}
var result = channelUser.Subscribed;
channelUser.Subscribed = false;
// remove any overrides
var channelSubscriptions = this.GetUserStalkSubscriptionsInChannel(new BotUser(mask), channel);
foreach (var subscriptionResult in channelSubscriptions.Where(x => x.Source == SubscriptionSource.Stalk))
{
subscriptionResult.Stalk.Subscribers.RemoveAll(x => x.Mask.Equals(mask));
}
return result;
}
public bool IsSubscribedToChannel(IBotUser botUser, IIrcChannel channel)
{
return this.GetUserSubscriptionsToChannel(botUser).Any(x => x.Equals(channel));
}
public IEnumerable<IIrcChannel> GetUserSubscriptionsToChannel(IBotUser botUser)
{
return this.channelConfiguration.Items
.Where(channel => channel.Users.Select(y => y.Mask).Contains(botUser.Mask))
.Where(channel => channel.Users.First(x => x.Mask.Equals(botUser.Mask)).Subscribed)
.ToList();
}
public IEnumerable<SubscriptionResult> GetUserSubscriptionsToStalk(IIrcChannel channel, IStalk stalk)
{
var userData = this.botUserConfiguration.Items.ToDictionary(
x => x,
y => new SubscriptionResult {Stalk = stalk, Channel = channel, BotUser = y});
foreach (var channelUser in channel.Users.Where(x => x.Subscribed))
{
var botUser = this.botUserConfiguration[channelUser.Mask.ToString()];
userData[botUser].IsSubscribed = true;
userData[botUser].Source = SubscriptionSource.Channel;
userData[botUser].Complete = true;
}
foreach (var stalkUser in stalk.Subscribers)
{
var botUser = this.botUserConfiguration[stalkUser.Mask.ToString()];
if (stalkUser.Subscribed)
{
userData[botUser].IsSubscribed = true;
userData[botUser].Overridden = false;
userData[botUser].Source = SubscriptionSource.Stalk;
userData[botUser].Complete = true;
}
else
{
// subscription exclusion for channel users
userData[botUser].IsSubscribed = false;
userData[botUser].Overridden = true;
userData[botUser].Source = SubscriptionSource.Stalk;
userData[botUser].Complete = true;
}
}
return userData.Where(x => x.Value.Complete).Select(x => x.Value).ToList();
}
public IEnumerable<SubscriptionResult> GetUserStalkSubscriptionsInChannel(IBotUser user, IIrcChannel channel)
{
var channelSubscribed = channel.Users.Where(x => x.Subscribed).Any(x => x.Mask.Equals(user.Mask));
var results = new List<SubscriptionResult>();
foreach (var stalk in channel.Stalks)
{
var result = new SubscriptionResult
{
Channel = channel, BotUser = user, Stalk = stalk.Value, Complete = true
};
if (channelSubscribed)
{
result.IsSubscribed = true;
result.Source = SubscriptionSource.Channel;
}
var subscription = stalk.Value.Subscribers.FirstOrDefault(x => x.Mask.Equals(user.Mask));
if (subscription == null)
{
// use the channel result.
results.Add(result);
continue;
}
if (subscription.Subscribed)
{
result.IsSubscribed = true;
result.Source = SubscriptionSource.Stalk;
}
else
{
result.IsSubscribed = false;
result.Overridden = true;
result.Source = SubscriptionSource.Stalk;
}
results.Add(result);
}
return results;
}
public sealed class SubscriptionResult
{
internal SubscriptionResult()
{
}
public IStalk Stalk { get; internal set; }
public IIrcChannel Channel { get; internal set; }
public IBotUser BotUser { get; internal set; }
public bool IsSubscribed { get; internal set; }
public SubscriptionSource Source { get; internal set; }
public bool Overridden { get; internal set; }
// has this item been completely constructed?
internal bool Complete { get; set; }
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridViewTextBoxCell.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Windows.Forms.Internal;
using System.Globalization;
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell"]/*' />
/// <devdoc>
/// <para>Identifies a cell in the dataGridView.</para>
/// </devdoc>
public class DataGridViewTextBoxCell : DataGridViewCell
{
private static readonly int PropTextBoxCellMaxInputLength = PropertyStore.CreateKey();
private static readonly int PropTextBoxCellEditingTextBox = PropertyStore.CreateKey();
private const byte DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick = 0x01;
private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft = 3;
private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight = 4;
private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft = 0;
private const byte DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight = 0;
private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop = 2;
private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetBottom = 1;
private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping = 1;
private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping = 2;
private const byte DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom = 1;
private const int DATAGRIDVIEWTEXTBOXCELL_maxInputLength = 32767;
private byte flagsState; // see DATAGRIDVIEWTEXTBOXCELL_ consts above
private static Type defaultFormattedValueType = typeof(System.String);
private static Type defaultValueType = typeof(System.Object);
private static Type cellType = typeof(DataGridViewTextBoxCell);
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.DataGridViewTextBoxCell"]/*' />
public DataGridViewTextBoxCell()
{
}
private DataGridViewTextBoxEditingControl EditingTextBox
{
get
{
return (DataGridViewTextBoxEditingControl) this.Properties.GetObject(PropTextBoxCellEditingTextBox);
}
set
{
if (value != null || this.Properties.ContainsObject(PropTextBoxCellEditingTextBox))
{
this.Properties.SetObject(PropTextBoxCellEditingTextBox, value);
}
}
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.FormattedValueType"]/*' />
public override Type FormattedValueType
{
get
{
// we return string for the formatted type
return defaultFormattedValueType;
}
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.MaxInputLength"]/*' />
[DefaultValue(DATAGRIDVIEWTEXTBOXCELL_maxInputLength)]
public virtual int MaxInputLength
{
get
{
bool found;
int maxInputLength = this.Properties.GetInteger(PropTextBoxCellMaxInputLength, out found);
if (found)
{
return maxInputLength;
}
return DATAGRIDVIEWTEXTBOXCELL_maxInputLength;
}
set
{
// VSWhidbey 515823
//if (this.DataGridView != null && this.RowIndex == -1)
//{
// throw new InvalidOperationException(SR.GetString(SR.DataGridView_InvalidOperationOnSharedCell));
//}
if (value < 0)
{
throw new ArgumentOutOfRangeException("MaxInputLength", SR.GetString(SR.InvalidLowBoundArgumentEx, "MaxInputLength", value.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
}
this.Properties.SetInteger(PropTextBoxCellMaxInputLength, value);
if (OwnsEditingTextBox(this.RowIndex))
{
this.EditingTextBox.MaxLength = value;
}
}
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.ValueType"]/*' />
public override Type ValueType
{
get
{
Type valueType = base.ValueType;
if (valueType != null)
{
return valueType;
}
return defaultValueType;
}
}
// Called when the row that owns the editing control gets unshared.
internal override void CacheEditingControl()
{
this.EditingTextBox = this.DataGridView.EditingControl as DataGridViewTextBoxEditingControl;
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.Clone"]/*' />
public override object Clone()
{
DataGridViewTextBoxCell dataGridViewCell;
Type thisType = this.GetType();
if(thisType == cellType) //performance improvement
{
dataGridViewCell = new DataGridViewTextBoxCell();
}
else
{
// SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info..
//
dataGridViewCell = (DataGridViewTextBoxCell)System.Activator.CreateInstance(thisType);
}
base.CloneInternal(dataGridViewCell);
dataGridViewCell.MaxInputLength = this.MaxInputLength;
return dataGridViewCell;
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.DetachEditingControl"]/*' />
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
public override void DetachEditingControl()
{
DataGridView dgv = this.DataGridView;
if (dgv == null || dgv.EditingControl == null)
{
throw new InvalidOperationException();
}
TextBox textBox = dgv.EditingControl as TextBox;
if (textBox != null)
{
textBox.ClearUndo();
}
this.EditingTextBox = null;
base.DetachEditingControl();
}
private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds, DataGridViewCellStyle cellStyle)
{
Debug.Assert(cellStyle.WrapMode != DataGridViewTriState.NotSet);
Debug.Assert(this.DataGridView != null);
TextBox txtEditingControl = this.DataGridView.EditingControl as TextBox;
int originalWidth = editingControlBounds.Width;
if (txtEditingControl != null)
{
switch (cellStyle.Alignment)
{
case DataGridViewContentAlignment.TopLeft:
case DataGridViewContentAlignment.MiddleLeft:
case DataGridViewContentAlignment.BottomLeft:
// Add 3 pixels on the left of the editing control to match non-editing text position
if (this.DataGridView.RightToLeftInternal)
{
editingControlBounds.X += 1;
editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 2);
}
else
{
editingControlBounds.X += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft;
editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 1);
}
break;
case DataGridViewContentAlignment.TopCenter:
case DataGridViewContentAlignment.MiddleCenter:
case DataGridViewContentAlignment.BottomCenter:
editingControlBounds.X += 1;
editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - 3);
break;
case DataGridViewContentAlignment.TopRight:
case DataGridViewContentAlignment.MiddleRight:
case DataGridViewContentAlignment.BottomRight:
// Shorten the editing control by 5 pixels to match non-editing text position
if (this.DataGridView.RightToLeftInternal)
{
editingControlBounds.X += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1;
editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight);
}
else
{
editingControlBounds.X += 1;
editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1);
}
break;
}
switch (cellStyle.Alignment)
{
case DataGridViewContentAlignment.TopLeft:
case DataGridViewContentAlignment.TopCenter:
case DataGridViewContentAlignment.TopRight:
editingControlBounds.Y += DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop;
editingControlBounds.Height = Math.Max(0, editingControlBounds.Height - DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop);
break;
case DataGridViewContentAlignment.MiddleLeft:
case DataGridViewContentAlignment.MiddleCenter:
case DataGridViewContentAlignment.MiddleRight:
editingControlBounds.Height++;
break;
case DataGridViewContentAlignment.BottomLeft:
case DataGridViewContentAlignment.BottomCenter:
case DataGridViewContentAlignment.BottomRight:
editingControlBounds.Height = Math.Max(0, editingControlBounds.Height - DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetBottom);
break;
}
int preferredHeight;
if (cellStyle.WrapMode == DataGridViewTriState.False)
{
preferredHeight = txtEditingControl.PreferredSize.Height;
}
else
{
string editedFormattedValue = (string) ((IDataGridViewEditingControl) txtEditingControl).GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting);
if (string.IsNullOrEmpty(editedFormattedValue))
{
editedFormattedValue = " ";
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
{
preferredHeight = DataGridViewCell.MeasureTextHeight(g, editedFormattedValue, cellStyle.Font, originalWidth, flags);
}
}
if (preferredHeight < editingControlBounds.Height)
{
switch (cellStyle.Alignment)
{
case DataGridViewContentAlignment.TopLeft:
case DataGridViewContentAlignment.TopCenter:
case DataGridViewContentAlignment.TopRight:
// Single pixel move - leave it as is for now
break;
case DataGridViewContentAlignment.MiddleLeft:
case DataGridViewContentAlignment.MiddleCenter:
case DataGridViewContentAlignment.MiddleRight:
editingControlBounds.Y += (editingControlBounds.Height - preferredHeight) / 2;
break;
case DataGridViewContentAlignment.BottomLeft:
case DataGridViewContentAlignment.BottomCenter:
case DataGridViewContentAlignment.BottomRight:
editingControlBounds.Y += editingControlBounds.Height - preferredHeight;
break;
}
}
}
return editingControlBounds;
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.GetContentBounds"]/*' />
protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null)
{
return Rectangle.Empty;
}
object value = GetValue(rowIndex);
object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting);
DataGridViewAdvancedBorderStyle dgvabsEffective;
DataGridViewElementStates cellState;
Rectangle cellBounds;
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);
Rectangle textBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
formattedValue,
null /*errorText*/, // textBounds is independent of errorText
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
Rectangle textBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
formattedValue,
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(textBoundsDebug.Equals(textBounds));
#endif
return textBounds;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetErrorIconBounds"]/*' />
protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
if (this.DataGridView == null ||
rowIndex < 0 ||
this.OwningColumn == null ||
!this.DataGridView.ShowCellErrors ||
String.IsNullOrEmpty(GetErrorText(rowIndex)))
{
return Rectangle.Empty;
}
DataGridViewAdvancedBorderStyle dgvabsEffective;
DataGridViewElementStates cellState;
Rectangle cellBounds;
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);
Rectangle errorBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
null /*formattedValue*/, // errorIconBounds is independent of formattedValue
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
object value = GetValue(rowIndex);
object formattedValue = GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting);
Rectangle errorBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
formattedValue,
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(errorBoundsDebug.Equals(errorBounds));
#endif
return errorBounds;
}
/// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetPreferredSize"]/*' />
protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
{
if (this.DataGridView == null)
{
return new Size(-1, -1);
}
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
Size preferredSize;
Rectangle borderWidthsRect = this.StdBorderWidths;
int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal;
int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical;
DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize);
object formattedValue = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize);
string formattedString = formattedValue as string;
if (string.IsNullOrEmpty(formattedString))
{
formattedString = " ";
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1)
{
switch (freeDimension)
{
case DataGridViewFreeDimension.Width:
{
preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics,
formattedString,
cellStyle.Font,
Math.Max(1, constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom),
flags),
0);
break;
}
case DataGridViewFreeDimension.Height:
{
preferredSize = new Size(0,
DataGridViewCell.MeasureTextHeight(graphics,
formattedString,
cellStyle.Font,
Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight),
flags));
break;
}
default:
{
preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics,
formattedString,
cellStyle.Font,
5.0F,
flags);
break;
}
}
}
else
{
switch (freeDimension)
{
case DataGridViewFreeDimension.Width:
{
preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width,
0);
break;
}
case DataGridViewFreeDimension.Height:
{
preferredSize = new Size(0,
DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height);
break;
}
default:
{
preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags);
break;
}
}
}
if (freeDimension != DataGridViewFreeDimension.Height)
{
preferredSize.Width += DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight + borderAndPaddingWidths;
if (this.DataGridView.ShowCellErrors)
{
// Making sure that there is enough room for the potential error icon
preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth);
}
}
if (freeDimension != DataGridViewFreeDimension.Width)
{
int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping;
preferredSize.Height += verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom + borderAndPaddingHeights;
if (this.DataGridView.ShowCellErrors)
{
// Making sure that there is enough room for the potential error icon
preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight);
}
}
return preferredSize;
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.InitializeEditingControl"]/*' />
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
Debug.Assert(this.DataGridView != null &&
this.DataGridView.EditingPanel != null &&
this.DataGridView.EditingControl != null);
Debug.Assert(!this.ReadOnly);
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
TextBox textBox = this.DataGridView.EditingControl as TextBox;
if (textBox != null)
{
textBox.BorderStyle = BorderStyle.None;
textBox.AcceptsReturn = textBox.Multiline = dataGridViewCellStyle.WrapMode == DataGridViewTriState.True;
textBox.MaxLength = this.MaxInputLength;
string initialFormattedValueStr = initialFormattedValue as string;
if (initialFormattedValueStr == null)
{
textBox.Text = string.Empty;
}
else
{
textBox.Text = initialFormattedValueStr;
}
this.EditingTextBox = this.DataGridView.EditingControl as DataGridViewTextBoxEditingControl;
}
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.KeyEntersEditMode"]/*' />
public override bool KeyEntersEditMode(KeyEventArgs e)
{
if (((char.IsLetterOrDigit((char)e.KeyCode) && !(e.KeyCode >= Keys.F1 && e.KeyCode <= Keys.F24)) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.Divide) ||
(e.KeyCode >= Keys.OemSemicolon && e.KeyCode <= Keys.Oem102) ||
(e.KeyCode == Keys.Space && !e.Shift)) &&
!e.Alt &&
!e.Control)
{
return true;
}
return base.KeyEntersEditMode(e);
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.OnEnter"]/*' />
protected override void OnEnter(int rowIndex, bool throughMouseClick)
{
if (this.DataGridView == null)
{
return;
}
if (throughMouseClick)
{
this.flagsState |= (byte)DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick;
}
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.OnLeave"]/*' />
protected override void OnLeave(int rowIndex, bool throughMouseClick)
{
if (this.DataGridView == null)
{
return;
}
this.flagsState = (byte)(this.flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick);
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.OnMouseClick"]/*' />
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
if (this.DataGridView == null)
{
return;
}
Debug.Assert(e.ColumnIndex == this.ColumnIndex);
Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
if (ptCurrentCell.X == e.ColumnIndex && ptCurrentCell.Y == e.RowIndex && e.Button == MouseButtons.Left)
{
if ((this.flagsState & DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick) != 0x00)
{
this.flagsState = (byte)(this.flagsState & ~DATAGRIDVIEWTEXTBOXCELL_ignoreNextMouseClick);
}
else if (this.DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically)
{
this.DataGridView.BeginEdit(true /*selectAll*/);
}
}
}
private bool OwnsEditingTextBox(int rowIndex)
{
return rowIndex != -1 && this.EditingTextBox != null && rowIndex == ((IDataGridViewEditingControl)this.EditingTextBox).EditingControlRowIndex;
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.Paint"]/*' />
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
PaintPrivate(graphics,
clipBounds,
cellBounds,
rowIndex,
cellState,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts,
false /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
true /*paint*/);
}
// PaintPrivate is used in three places that need to duplicate the paint code:
// 1. DataGridViewCell::Paint method
// 2. DataGridViewCell::GetContentBounds
// 3. DataGridViewCell::GetErrorIconBounds
//
// if computeContentBounds is true then PaintPrivate returns the contentBounds
// else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
// else it returns Rectangle.Empty;
private Rectangle PaintPrivate(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts,
bool computeContentBounds,
bool computeErrorIconBounds,
bool paint)
{
// Parameter checking.
// One bit and one bit only should be turned on
Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
Debug.Assert(cellStyle != null);
// If computeContentBounds == TRUE then resultBounds will be the contentBounds.
// If computeErrorIconBounds == TRUE then resultBounds will be the error icon bounds.
// Else resultBounds will be Rectangle.Empty;
Rectangle resultBounds = Rectangle.Empty;
if (paint && DataGridViewCell.PaintBorder(paintParts))
{
PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
Rectangle borderWidths = BorderWidths(advancedBorderStyle);
Rectangle valBounds = cellBounds;
valBounds.Offset(borderWidths.X, borderWidths.Y);
valBounds.Width -= borderWidths.Right;
valBounds.Height -= borderWidths.Bottom;
SolidBrush br;
Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
bool cellCurrent = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex;
bool cellEdited = cellCurrent && this.DataGridView.EditingControl != null;
bool cellSelected = (cellState & DataGridViewElementStates.Selected) != 0;
if (DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected && !cellEdited)
{
br = this.DataGridView.GetCachedBrush(cellStyle.SelectionBackColor);
}
else
{
br = this.DataGridView.GetCachedBrush(cellStyle.BackColor);
}
if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 0 && valBounds.Height > 0)
{
graphics.FillRectangle(br, valBounds);
}
if (cellStyle.Padding != Padding.Empty)
{
if (this.DataGridView.RightToLeftInternal)
{
valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
}
else
{
valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
}
valBounds.Width -= cellStyle.Padding.Horizontal;
valBounds.Height -= cellStyle.Padding.Vertical;
}
if (paint && cellCurrent && !cellEdited)
{
// Draw focus rectangle
if (DataGridViewCell.PaintFocus(paintParts) &&
this.DataGridView.ShowFocusCues &&
this.DataGridView.Focused &&
valBounds.Width > 0 &&
valBounds.Height > 0)
{
ControlPaint.DrawFocusRectangle(graphics, valBounds, Color.Empty, br.Color);
}
}
Rectangle errorBounds = valBounds;
string formattedString = formattedValue as string;
if (formattedString != null && ((paint && !cellEdited) || computeContentBounds))
{
// Font independent margins
int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping;
valBounds.Offset(DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft, verticalTextMarginTop);
valBounds.Width -= DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight;
valBounds.Height -= verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom;
if (valBounds.Width > 0 && valBounds.Height > 0)
{
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
if (paint)
{
if (DataGridViewCell.PaintContentForeground(paintParts))
{
if ((flags & TextFormatFlags.SingleLine) != 0)
{
flags |= TextFormatFlags.EndEllipsis;
}
TextRenderer.DrawText(graphics,
formattedString,
cellStyle.Font,
valBounds,
cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor,
flags);
}
}
else
{
resultBounds = DataGridViewUtilities.GetTextBounds(valBounds, formattedString, flags, cellStyle);
}
}
}
else if (computeErrorIconBounds)
{
if (!String.IsNullOrEmpty(errorText))
{
resultBounds = ComputeErrorIconBounds(errorBounds);
}
}
else
{
Debug.Assert(cellEdited || formattedString == null);
Debug.Assert(paint || computeContentBounds);
}
if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
{
PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText);
}
return resultBounds;
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.PositionEditingControl"]/*' />
public override void PositionEditingControl(bool setLocation,
bool setSize,
Rectangle cellBounds,
Rectangle cellClip,
DataGridViewCellStyle cellStyle,
bool singleVerticalBorderAdded,
bool singleHorizontalBorderAdded,
bool isFirstDisplayedColumn,
bool isFirstDisplayedRow)
{
Rectangle editingControlBounds = PositionEditingPanel(cellBounds,
cellClip,
cellStyle,
singleVerticalBorderAdded,
singleHorizontalBorderAdded,
isFirstDisplayedColumn,
isFirstDisplayedRow);
editingControlBounds = GetAdjustedEditingControlBounds(editingControlBounds, cellStyle);
this.DataGridView.EditingControl.Location = new Point(editingControlBounds.X, editingControlBounds.Y);
this.DataGridView.EditingControl.Size = new Size(editingControlBounds.Width, editingControlBounds.Height);
}
/// <include file='doc\DataGridViewTextBoxCell.uex' path='docs/doc[@for="DataGridViewTextBoxCell.ToString"]/*' />
public override string ToString()
{
return "DataGridViewTextBoxCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Omu.ValueInjecter.Flat;
using Tests.Utils;
namespace Tests
{
[TestFixture]
public class UberFlatterTests
{
public class Bar1
{
public string Name { get; set; }
}
public class FooBar1
{
public string Name { get; set; }
}
public class Foo1
{
public Bar1 Bar { get; set; }
}
public class Unflat
{
public Unflat The { get; set; }
public Foo1 Foo { get; set; }
public FooBar1 FooBar { get; set; }
public Unflat The2 { get; set; }
}
public class Flat
{
public string FooBarName { get; set; }
}
private bool Match(string upn, PropertyInfo propertyInfo)
{
return upn == propertyInfo.Name && propertyInfo.PropertyType == typeof(string);
}
private bool MatchIgnoreCase(string upn, PropertyInfo propertyInfo)
{
return upn.Equals(propertyInfo.Name, StringComparison.OrdinalIgnoreCase) && propertyInfo.PropertyType == typeof(string);
}
[Test]
public void FlatTest()
{
var u = new Unflat() { Foo = new Foo1() { Bar = new Bar1() { Name = "dasName" } }, FooBar = new FooBar1() { Name = "uber" } };
var vv = UberFlatter.Flat("FooBarName", u, Match);
vv.Count().IsEqualTo(2);
var vvv = UberFlatter.Flat("FooBarName", u);
vvv.Count().IsEqualTo(2);
}
[Test]
public void FlatTestIgnoreCase()
{
var u = new Unflat() { Foo = new Foo1() { Bar = new Bar1() { Name = "dasName" } }, FooBar = new FooBar1() { Name = "uber" } };
var vv = UberFlatter.Flat("foobarname", u, MatchIgnoreCase, StringComparison.OrdinalIgnoreCase);
vv.Count().IsEqualTo(2);
var vvv = UberFlatter.Flat("foobarname", u, MatchIgnoreCase, StringComparison.OrdinalIgnoreCase);
vvv.Count().IsEqualTo(2);
}
[Test]
public void UnflatTest()
{
var u = new Unflat();
var es = UberFlatter.Unflat("FooBarName", u, Match);
es.Count().IsEqualTo(2);
UberFlatter.Unflat("FooBarName", u).Count().IsEqualTo(2);
}
[Test]
public void UnflatTestIgnoreCase()
{
var u = new Unflat();
var es = UberFlatter.Unflat("foobarname", u, MatchIgnoreCase, StringComparison.OrdinalIgnoreCase);
es.Count().IsEqualTo(2);
UberFlatter.Unflat("foobarname", u, (upn, pi) => upn.Equals(pi.Name, StringComparison.OrdinalIgnoreCase), StringComparison.OrdinalIgnoreCase).Count().IsEqualTo(2);
}
[Test]
public void GetTrails()
{
var l = TrailFinder.GetTrails("TheFooBarName", typeof(Unflat).GetProperties().Single(o => o.Name == "The"), Match, new List<string>(), StringComparison.Ordinal).ToList();
l.Count.IsEqualTo(2);
}
[Test]
public void GetAllTrails()
{
var l = TrailFinder.GetTrails("The2FooBarName", typeof(Unflat).GetProperties(), Match, StringComparison.Ordinal);
l.Count().IsEqualTo(2);
}
[Test]
public void Speed()
{
var w = new Stopwatch();
w.Start();
var f = "hello";
for (int i = 0; i < 1000; i++)
{
f = string.Format("{0}.{1}", f, "hello");
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var s = "hello";
for (int i = 0; i < 1000; i++)
{
s = s + "." + "hello";
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var x = new[] { "hello" };
for (int i = 0; i < 1000; i++)
{
x = x.Concat(new[] { "hello" }).ToArray();
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var z = new List<string>();
for (int i = 0; i < 1000; i++)
{
var zz = new List<string> { "hello" };
z.AddRange(zz);
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
}
[Test]
public void S2()
{
var w = new Stopwatch();
w.Start();
var f = "hello";
for (int i = 0; i < 10000; i++)
{
var b = f == string.Format("{0}{1}", string.Empty, "hello");
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var z = "hello";
for (int i = 0; i < 10000; i++)
{
var b = z == string.Empty + "hello";
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var n = "hello";
for (int i = 0; i < 10000; i++)
{
var b = n == null + "hello";
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var x = "hello";
for (int i = 0; i < 10000; i++)
{
var b = x == "hello";
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
w.Reset(); w.Start();
var y = "hello";
for (int i = 0; i < 10000; i++)
{
var b = y.Equals("hello");
}
w.Stop();
Console.Out.WriteLine(w.Elapsed);
}
}
}
| |
/*
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.Linq;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Globalization;
using Adxstudio.Xrm.Partner;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Web.UI.WebControls;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Site.Pages;
namespace Site.Areas.Opportunities.Pages
{
public partial class CreateNewOpportunity : PortalPage
{
public TextBox PotentialCustomer
{
get { return (TextBox)createOpp.FindControl("PotentialCustomer"); }
}
private Entity _account;
public Entity ParentCustomerAccount
{
get
{
if (_account != null)
{
return _account;
}
Guid accountId;
if (!Guid.TryParse(Request["AccountID"], out accountId))
{
return null;
}
_account = XrmContext.CreateQuery("account").FirstOrDefault(c => c.GetAttributeValue<Guid>("accountid") == accountId);
return _account;
}
}
protected void Page_Load(object sender, EventArgs e)
{
RedirectToLoginIfAnonymous();
if (Page.IsPostBack)
{
return;
}
var opportunityPermissions = XrmContext.GetOpportunityAccessByContact(Contact).ToList();
if (!opportunityPermissions.Any())
{
NoOpportunityPermissionsRecordError.Visible = true;
OpportunityDetailsPanel.Visible = false;
return;
}
bool createAccess = false;
foreach (var access in opportunityPermissions)
{
var opportunityCreateAccess = (access != null && access.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false));
if (opportunityCreateAccess)
{
createAccess = true;
}
}
if (!createAccess)
{
OpportunityPermissionsError.Visible = true;
OpportunityDetailsPanel.Visible = false;
return;
}
var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
var channelCreateAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false));
var parentCustomerAccount = Contact.GetAttributeValue<EntityReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EntityReference>("parentcustomerid").Id);
var validAcccountClassificationCode = parentCustomerAccount != null && parentCustomerAccount.GetAttributeValue<OptionSetValue>("accountclassificationcode") != null && parentCustomerAccount.GetAttributeValue<OptionSetValue>("accountclassificationcode").Value == (int)CustomerManagement.Enums.AccountClassificationCode.Partner;
if (channelPermission == null)
{
NoChannelPermissionsRecordError.Visible = true;
CreateCustomerButton.Visible = false;
}
else
{
if (!channelCreateAccess)
{
ChannelPermissionsError.Visible = true;
}
else
{
if (parentCustomerAccount == null)
{
NoParentAccountError.Visible = true;
}
else
{
ParentAccountClassificationCodeError.Visible = !validAcccountClassificationCode;
}
}
if ((!channelCreateAccess) || parentCustomerAccount == null || !validAcccountClassificationCode)
{
CreateCustomerButton.Visible = false;
}
}
var partnerAccounts = ServiceContext.CreateQuery("account").Where(a => a.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null && a.GetAttributeValue<EntityReference>("msa_managingpartnerid").Equals(parentCustomerAccount.ToEntityReference())).ToList();
var accounts = partnerAccounts
.Where(a => a.GetAttributeValue<EntityReference>("primarycontactid") != null)
.OrderBy(a => a.GetAttributeValue<string>("name"))
.Select(a => new ListItem(a.GetAttributeValue<string>("name"), a.GetAttributeValue<Guid>("accountid").ToString())).ToList();
if (!accounts.Any())
{
Account_dropdown.Enabled = false;
if (!partnerAccounts.Any())
{
NoManagingPartnerCustomerAccountsMessage.Visible = true;
}
else
{
NoPrimaryContactOnManagingPartnerCustomerAccountsMessage.Visible = true;
ManageCustomersButton.Visible = true;
}
}
else
{
NoManagingPartnerCustomerAccountsMessage.Visible = false;
NoPrimaryContactOnManagingPartnerCustomerAccountsMessage.Visible = false;
Account_dropdown.DataSource = accounts;
Account_dropdown.DataTextField = "Text";
Account_dropdown.DataValueField = "Value";
Account_dropdown.DataBind();
if (ParentCustomerAccount != null)
{
Account_dropdown.ClearSelection();
foreach (ListItem li in Account_dropdown.Items)
{
Guid id;
if (Guid.TryParse(li.Value, out id) && id == ParentCustomerAccount.GetAttributeValue<Guid>("accountid"))
{
li.Selected = true;
}
}
}
}
}
protected void SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Account_dropdown.SelectedValue))
{
createOpp.Visible = true;
CreateCustomerButton.Visible = false;
}
}
protected void OnItemInserting(object sender, CrmEntityFormViewInsertingEventArgs e)
{
var currentContact = XrmContext.MergeClone(Contact);
if (currentContact == null)
{
return;
}
var contactParentCustomerAccount = currentContact.GetRelatedEntity(XrmContext, new Relationship("contact_customer_accounts"));
if (contactParentCustomerAccount != null)
{
e.Values["msa_partnerid"] = contactParentCustomerAccount.ToEntityReference();
}
e.Values["msa_partneroppid"] = currentContact.ToEntityReference();
e.Values["adx_createdbyusername"] = Contact.GetAttributeValue<string>("fullname");
// e.Values["adx_createdbyipaddress"] = Request.UserHostAddress ?? "";
e.Values["adx_partnercreated"] = true;
// If no estimated revenue was submitted, leave as system-calculated.
e.Values["isrevenuesystemcalculated"] = (!e.Values.ContainsKey("estimatedvalue")) || (e.Values["estimatedvalue"] == null);
Guid accountId;
if ((Account_dropdown.SelectedItem == null || Account_dropdown.SelectedIndex == 0) || !Guid.TryParse(Account_dropdown.SelectedItem.Value, out accountId))
{
return;
}
var account = XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == accountId);
if (account != null)
{
e.Values["customerid"] = account.ToEntityReference();
}
}
protected void OnItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e)
{
var opportunity = XrmContext.CreateQuery("opportunity").First(o => o.GetAttributeValue<Guid>("opportunityid") == e.EntityId);
var opportunityProductsFromLead = opportunity.GetAttributeValue<string>("adx_opportunityproductsfromlead");
var productsList = new List<Entity>();
if (!string.IsNullOrEmpty(opportunityProductsFromLead))
{
var products = XrmContext.CreateQuery("product");
var words = opportunityProductsFromLead.Split(',');
foreach (var word in words)
{
foreach (var product in products)
{
if (product.GetAttributeValue<string>("name").Trim().ToUpper() == word.Trim().ToUpper())
{
productsList.Add(product);
}
}
}
}
foreach (var leadProduct in productsList)
{
if (!XrmContext.IsAttached(leadProduct))
{
XrmContext.Attach(leadProduct);
}
XrmContext.AddLink(opportunity, new Relationship("adx_opportunity_product"), leadProduct);
}
opportunity.SetAttributeValue("adx_referencecode", GetOpportunityReferenceCode());
var salesStage = opportunity.GetAttributeValue<OptionSetValue>("salesstagecode") == null ? 0 : opportunity.GetAttributeValue<OptionSetValue>("salesstagecode").Value;
var response = (RetrieveAttributeResponse)ServiceContext.Execute(new RetrieveAttributeRequest
{
EntityLogicalName = "opportunity",
LogicalName = "salesstagecode"
});
var picklist = response.AttributeMetadata as PicklistAttributeMetadata;
if (picklist == null)
{
return;
}
foreach (var option in picklist.OptionSet.Options)
{
if (option != null && option.Value != null && option.Value.Value == salesStage)
{
opportunity.SetAttributeValue("stepname", option.Label.GetLocalizedLabelString());
}
}
var leadType = XrmContext.CreateQuery("adx_leadtype").FirstOrDefault(lt => lt.GetAttributeValue<string>("adx_name") == "Partner Created");
if (leadType != null)
{
opportunity.SetAttributeValue("adx_leadtypeid", leadType.ToEntityReference());
}
XrmContext.UpdateObject(opportunity);
XrmContext.SaveChanges();
var url = GetUrlForRequiredSiteMarker("Accepted Opportunities");
Response.Redirect(url);
}
protected void CreateCustomerButton_Click(object sender, EventArgs args)
{
var url = GetUrlForRequiredSiteMarker("Create Customer Account");
url.QueryString.Set("FromCreateOpportunity", "true");
Response.Redirect(url.PathWithQueryString);
}
protected void ManageCustomerButton_Click(object sender, EventArgs args)
{
var url = GetUrlForRequiredSiteMarker("Manage Customer Accounts");
Response.Redirect(url.PathWithQueryString);
}
public string GetOpportunityReferenceCode()
{
var str = "OPP-";
var random = new Random();
for (var i = 0; i < 12; i++)
{
var r = random.Next(0x10);
char s = ' ';
switch (r)
{
case 0: s = '0'; break;
case 1: s = '1'; break;
case 2: s = '2'; break;
case 3: s = '3'; break;
case 4: s = '4'; break;
case 5: s = '5'; break;
case 6: s = '6'; break;
case 7: s = '7'; break;
case 8: s = '8'; break;
case 9: s = '9'; break;
case 10: s = 'A'; break;
case 11: s = 'B'; break;
case 12: s = 'C'; break;
case 13: s = 'D'; break;
case 14: s = 'E'; break;
case 15: s = 'F'; break;
}
str = str + s;
}
var uuid = str;
return uuid;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Debug.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Debug.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
[ActiveIssue("Sporadic failure, needs a port of https://github.com/dotnet/coreclr/pull/4340", TargetFrameworkMonikers.NetFramework)]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetFromArrayTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Theory]
[InlineData(new int[] { }, new int[] { })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void ToImmutableSortedSetFromEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = enumerableInput.ToImmutableSortedSet();
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Theory]
[InlineData(new int[] { }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 1, 1 }, new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 3, 2, 1 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 3 }, new int[] { 1, 3 })]
[InlineData(new int[] { 1, 2, 2 }, new int[] { 1, 2 })]
[InlineData(new int[] { 1, 2, 2, 3, 3, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 1, 2, 3 }, new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 3 }, new int[] { 1, 2, 3 })]
public void UnionWithEnumerableTest(int[] input, int[] expectedOutput)
{
IEnumerable<int> enumerableInput = input.Select(i => i); // prevent querying for indexable interfaces
var set = ImmutableSortedSet.Create(1).Union(enumerableInput);
Assert.Equal((IEnumerable<int>)expectedOutput, set.ToArray());
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
var nullableSet = ImmutableSortedSet<int?>.Empty;
Assert.Equal(~0, nullableSet.IndexOf(null));
nullableSet = nullableSet.Add(null).Add(0);
Assert.Equal(0, nullableSet.IndexOf(null));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => set[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create(default(string));
Assert.Equal(1, set.Count);
set = ImmutableSortedSet.CreateRange(new[] { null, "a", null, "b" });
Assert.Equal(3, set.Count);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.Create<int>());
ImmutableSortedSet<string> set = ImmutableSortedSet.Create("1", "2", "3");
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(set);
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedSet.Create<object>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
string[] items = itemProperty.GetValue(info.Instance) as string[];
Assert.Equal(set, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSortedSet.Create("1", "2", "3"));
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void SymmetricExceptWithComparerTests()
{
var set = ImmutableSortedSet.Create<string>("a").WithComparer(StringComparer.OrdinalIgnoreCase);
var otherCollection = new[] {"A"};
var expectedSet = new SortedSet<string>(set, set.KeyComparer);
expectedSet.SymmetricExceptWith(otherCollection);
var actualSet = set.SymmetricExcept(otherCollection);
CollectionAssertAreEquivalent(expectedSet.ToList(), actualSet.ToList());
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableSortedSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of a sorted set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
{
Assert.NotNull(emptySet);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
// 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.
//
//
//
// The SecurityManager class provides a general purpose API for interacting
// with the security system.
//
namespace System.Security {
using System;
using System.Security.Util;
using System.Security.Policy;
using System.Security.Permissions;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
#if FEATURE_CLICKONCE
using System.Runtime.Hosting;
#endif // FEATURE_CLICKONCE
using System.Text;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum PolicyLevelType
{
User = 0,
Machine = 1,
Enterprise = 2,
AppDomain = 3
}
[System.Runtime.InteropServices.ComVisible(true)]
static public class SecurityManager {
#if FEATURE_CAS_POLICY
private static volatile SecurityPermission executionSecurityPermission = null;
private static PolicyManager polmgr = new PolicyManager();
internal static PolicyManager PolicyManager {
get {
return polmgr;
}
}
//
// Public APIs
//
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("IsGranted is obsolete and will be removed in a future release of the .NET Framework. Please use the PermissionSet property of either AppDomain or Assembly instead.")]
public static bool IsGranted( IPermission perm )
{
if (perm == null)
return true;
PermissionSet granted = null, denied = null;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
GetGrantedPermissions( JitHelpers.GetObjectHandleOnStack(ref granted),
JitHelpers.GetObjectHandleOnStack(ref denied),
JitHelpers.GetStackCrawlMarkHandle(ref stackMark) );
return granted.Contains( perm ) && (denied == null || !denied.Contains( perm ));
}
// Get a sandbox permission set that the CLR considers safe to grant an application with the given
// evidence. Note that this API is not a policy API, but rather a host helper API so that a host can
// determine if an application's requested permission set is reasonable. This is esentially just a
// hard coded mapping of Zone -> Sandbox and is not configurable in any way.
public static PermissionSet GetStandardSandbox(Evidence evidence)
{
if (evidence == null)
throw new ArgumentNullException(nameof(evidence));
Contract.EndContractBlock();
//
// The top-level switch for grant set is based upon Zone
// MyComputer -> FullTrust
// Intranet -> LocalIntranet
// Trusted -> Internet
// Internet -> Internet
// All else -> Nothing
//
// Both the Internet and LocalIntranet zones can have permission set extensions applied to them
// if there is Activation.
//
Zone zone = evidence.GetHostEvidence<Zone>();
if (zone == null)
{
return new PermissionSet(PermissionState.None);
}
#if FEATURE_CAS_POLICY
else if (zone.SecurityZone == SecurityZone.MyComputer)
{
return new PermissionSet(PermissionState.Unrestricted);
}
else if (zone.SecurityZone == SecurityZone.Intranet)
{
PermissionSet intranetGrantSet = BuiltInPermissionSets.LocalIntranet;
// We also need to add in same site web and file IO permission
PolicyStatement webPolicy =
new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
PolicyStatement filePolicy =
new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery).Resolve(evidence);
if (webPolicy != null)
{
intranetGrantSet.InplaceUnion(webPolicy.PermissionSet);
}
if (filePolicy != null)
{
intranetGrantSet.InplaceUnion(filePolicy.PermissionSet);
}
return intranetGrantSet;
}
else if (zone.SecurityZone == SecurityZone.Internet ||
zone.SecurityZone == SecurityZone.Trusted)
{
PermissionSet internetGrantSet = BuiltInPermissionSets.Internet;
// We also need to add in same site web permission
PolicyStatement webPolicy =
new NetCodeGroup(new AllMembershipCondition()).Resolve(evidence);
if (webPolicy != null)
{
internetGrantSet.InplaceUnion(webPolicy.PermissionSet);
}
return internetGrantSet;
}
#endif // FEATURE_CAS_POLICY
else
{
return new PermissionSet(PermissionState.None);
}
}
/// <internalonly/>
[System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public void GetZoneAndOrigin( out ArrayList zone, out ArrayList origin )
{
StackCrawlMark mark = StackCrawlMark.LookForMyCaller;
CodeAccessSecurityEngine.GetZoneAndOrigin( ref mark, out zone, out origin );
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public PolicyLevel LoadPolicyLevelFromFile(string path, PolicyLevelType type)
{
if (path == null)
throw new ArgumentNullException( nameof(path) );
Contract.EndContractBlock();
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
// We need to retain V1.x compatibility by throwing the same exception type.
if (!File.InternalExists(path))
throw new ArgumentException( Environment.GetResourceString("Argument_PolicyFileDoesNotExist"));
String fullPath = Path.GetFullPath( path );
FileIOPermission perm = new FileIOPermission( PermissionState.None );
perm.AddPathList( FileIOPermissionAccess.Read, fullPath );
perm.AddPathList( FileIOPermissionAccess.Write, fullPath );
perm.Demand();
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
using (StreamReader reader = new StreamReader(stream)) {
return LoadPolicyLevelFromStringHelper(reader.ReadToEnd(), path, type);
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public PolicyLevel LoadPolicyLevelFromString(string str, PolicyLevelType type)
{
return LoadPolicyLevelFromStringHelper(str, null, type);
}
private static PolicyLevel LoadPolicyLevelFromStringHelper (string str, string path, PolicyLevelType type)
{
if (str == null)
throw new ArgumentNullException( nameof(str) );
Contract.EndContractBlock();
PolicyLevel level = new PolicyLevel(type, path);
Parser parser = new Parser( str );
SecurityElement elRoot = parser.GetTopElement();
if (elRoot == null)
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "configuration" ) );
SecurityElement elMscorlib = elRoot.SearchForChildByTag( "mscorlib" );
if (elMscorlib == null)
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "mscorlib" ) );
SecurityElement elSecurity = elMscorlib.SearchForChildByTag( "security" );
if (elSecurity == null)
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "security" ) );
SecurityElement elPolicy = elSecurity.SearchForChildByTag( "policy" );
if (elPolicy == null)
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), "policy" ) );
SecurityElement elPolicyLevel = elPolicy.SearchForChildByTag( "PolicyLevel" );
if (elPolicyLevel != null)
level.FromXml( elPolicyLevel );
else
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Policy_BadXml" ), nameof(PolicyLevel) ) );
return level;
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public void SavePolicyLevel( PolicyLevel level )
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
PolicyManager.EncodeLevel( level );
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public PermissionSet ResolvePolicy(Evidence evidence,
PermissionSet reqdPset,
PermissionSet optPset,
PermissionSet denyPset,
out PermissionSet denied)
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
return ResolvePolicy(evidence, reqdPset, optPset, denyPset, out denied, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public PermissionSet ResolvePolicy(Evidence evidence)
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
// If we aren't passed any evidence, just make an empty object
if (evidence == null)
{
evidence = new Evidence();
}
return polmgr.Resolve(evidence);
}
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public PermissionSet ResolvePolicy( Evidence[] evidences )
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
if (evidences == null || evidences.Length == 0)
evidences = new Evidence[] { null };
PermissionSet retval = ResolvePolicy( evidences[0] );
if (retval == null)
return null;
for (int i = 1; i < evidences.Length; ++i)
{
retval = retval.Intersect( ResolvePolicy( evidences[i] ) );
if (retval == null || retval.IsEmpty())
return retval;
}
return retval;
}
#if FEATURE_CAS_POLICY
// Determine if the current thread would require a security context capture if the security state of
// the thread needs to be re-created at a later point in time. This can be used, for instance, if
// sensitive data is being obtained after security demands succeed, and that data is to be cached.
// If there is an Assert up the stack, then we wouldn't want to cache the data without capturing the
// corresponding security context to go along with it - otherwise we risk leaking data obtained
// under an assert to code which may no longer be running with that assert in place.
//
// A return value of false indicates that the CLR guarantees all of the following conditions are true:
// 1. No partial trust AppDomains are on the stack
// 2. No partial trust assemblies are on the stack
// 3. There are no currently active PermitOnly or Deny modifiers on the stack
//
// A return value of true means only that the CLR cannot guarantee that all of the conditions are
// true, and not that one of the conditions really is false.
//
// IMPORTANT: The above means is only reliable in the false return case. If we say that the thread
// does not require a context capture, then that answer is guaranteed to be correct. However, we may
// say that the thread does require a capture when it does not actually strictly need to capture the
// state. This is fine, as being overly conservative when capturing context will not lead to
// security holes; being overly agresssive in avoding the capture could lead to holes however.
//
// This API is SecurityCritical because its main use is to optimize away unnecessary security
// context captures, which means that the code using it is security sensitive and needs to be audited.
[SecurityCritical]
public static bool CurrentThreadRequiresSecurityContextCapture()
{
// If we know that the thread is not made up of entirely full trust code, and that there are no
// security stack modifiers on the thread, then there is no need to capture a security context.
return !CodeAccessSecurityEngine.QuickCheckForAllDemands();
}
#endif // FEATURE_CAS_POLICY
//
// This method resolves the policy for the specified evidence, but it
// ignores the AppDomain level even when one is available in the current policy.
//
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static PermissionSet ResolveSystemPolicy (Evidence evidence)
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
if (PolicyManager.IsGacAssembly(evidence))
{
return new PermissionSet(PermissionState.Unrestricted);
}
return polmgr.CodeGroupResolve(evidence, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public IEnumerator ResolvePolicyGroups(Evidence evidence)
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
return polmgr.ResolveCodeGroups(evidence);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static IEnumerator PolicyHierarchy()
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
return polmgr.PolicyHierarchy();
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPolicy )]
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static void SavePolicy()
{
if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
}
polmgr.Save();
}
[System.Security.SecurityCritical] // auto-generated
private static PermissionSet ResolveCasPolicy(Evidence evidence,
PermissionSet reqdPset,
PermissionSet optPset,
PermissionSet denyPset,
out PermissionSet denied,
out int securitySpecialFlags,
bool checkExecutionPermission)
{
Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);
CodeAccessPermission.Assert(true);
PermissionSet granted = ResolvePolicy(evidence,
reqdPset,
optPset,
denyPset,
out denied,
checkExecutionPermission);
securitySpecialFlags = SecurityManager.GetSpecialFlags(granted, denied);
return granted;
}
[System.Security.SecurityCritical] // auto-generated
static private PermissionSet ResolvePolicy(Evidence evidence,
PermissionSet reqdPset,
PermissionSet optPset,
PermissionSet denyPset,
out PermissionSet denied,
bool checkExecutionPermission)
{
Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);
if (executionSecurityPermission == null)
executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
PermissionSet requested = null;
PermissionSet optional;
PermissionSet allowed;
Exception savedException = null;
// We don't want to recurse back into here as a result of a
// stackwalk during resolution. So simply assert full trust (this
// implies that custom permissions cannot use any permissions that
// don't implement IUnrestrictedPermission.
// PermissionSet.s_fullTrust.Assert();
// The requested set is the union of the minimal request and the
// optional request. Minimal request defaults to empty, optional
// is "AllPossible" (includes any permission that can be defined)
// which is symbolized by null.
optional = optPset;
if (reqdPset == null)
requested = optional;
else
// If optional is null, the requested set becomes null/"AllPossible".
requested = optional == null ? null : reqdPset.Union(optional);
// Make sure that the right to execute is requested (if this feature is
// enabled).
if (requested != null && !requested.IsUnrestricted())
requested.AddPermission( executionSecurityPermission );
// If we aren't passed any evidence, just make an empty object
if (evidence == null)
{
evidence = new Evidence();
}
allowed = polmgr.Resolve(evidence);
// Intersect the grant with the RequestOptional
if (requested != null)
allowed.InplaceIntersect(requested);
// Check that we were granted the right to execute.
if (checkExecutionPermission)
{
if (!allowed.Contains(executionSecurityPermission) ||
(denyPset != null && denyPset.Contains(executionSecurityPermission)))
{
throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
System.__HResults.CORSEC_E_NO_EXEC_PERM,
savedException);
}
}
// Check that we were granted at least the minimal set we asked for. Do
// this before pruning away any overlap with the refused set so that
// users have the flexability of defining minimal permissions that are
// only expressable as set differences (e.g. allow access to "C:\" but
// disallow "C:\Windows").
if (reqdPset != null && !reqdPset.IsSubsetOf(allowed))
{
BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
throw new PolicyException(Environment.GetResourceString( "Policy_NoRequiredPermission" ),
System.__HResults.CORSEC_E_MIN_GRANT_FAIL,
savedException );
}
// Remove any granted permissions that are safe subsets of some denied
// permission. The remaining denied permissions (if any) are returned
// along with the modified grant set for use in checks.
if (denyPset != null)
{
BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
denied = denyPset.Copy();
allowed.MergeDeniedSet(denied);
if (denied.IsEmpty())
denied = null;
}
else
denied = null;
allowed.IgnoreTypeLoadFailures = true;
return allowed;
}
[Obsolete("Because execution permission checks can no longer be turned off, the CheckExecutionRights property no longer has any effect.")]
static public bool CheckExecutionRights
{
get { return true; }
set
{
// The setter for this property is a no-op since execution checking can no longer be turned off
}
}
[Obsolete("Because security can no longer be turned off, the SecurityEnabled property no longer has any effect.")]
public static bool SecurityEnabled
{
get { return true; }
set
{
// The setter for this property is a no-op since security cannot be turned off
}
}
#endif // #if FEATURE_CAS_POLICY
private static int[][] s_BuiltInPermissionIndexMap = {
new int[] { BuiltInPermissionIndex.EnvironmentPermissionIndex, (int) PermissionType.EnvironmentPermission },
new int[] { BuiltInPermissionIndex.FileDialogPermissionIndex, (int) PermissionType.FileDialogPermission },
new int[] { BuiltInPermissionIndex.FileIOPermissionIndex, (int) PermissionType.FileIOPermission },
new int[] { BuiltInPermissionIndex.ReflectionPermissionIndex, (int) PermissionType.ReflectionPermission },
new int[] { BuiltInPermissionIndex.SecurityPermissionIndex, (int) PermissionType.SecurityPermission },
new int[] { BuiltInPermissionIndex.UIPermissionIndex, (int) PermissionType.UIPermission }
};
private static CodeAccessPermission[] s_UnrestrictedSpecialPermissionMap = {
new EnvironmentPermission(PermissionState.Unrestricted),
new FileDialogPermission(PermissionState.Unrestricted),
new FileIOPermission(PermissionState.Unrestricted),
new ReflectionPermission(PermissionState.Unrestricted),
new SecurityPermission(PermissionState.Unrestricted),
new UIPermission(PermissionState.Unrestricted)
};
internal static int GetSpecialFlags (PermissionSet grantSet, PermissionSet deniedSet) {
if ((grantSet != null && grantSet.IsUnrestricted()) && (deniedSet == null || deniedSet.IsEmpty())) {
return -1;
}
else {
SecurityPermission securityPermission = null;
#pragma warning disable 618
SecurityPermissionFlag securityPermissionFlags = SecurityPermissionFlag.NoFlags;
#pragma warning restore 618
ReflectionPermission reflectionPermission = null;
ReflectionPermissionFlag reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
CodeAccessPermission[] specialPermissions = new CodeAccessPermission[6];
if (grantSet != null) {
if (grantSet.IsUnrestricted()) {
#pragma warning disable 618
securityPermissionFlags = SecurityPermissionFlag.AllFlags;
#pragma warning restore 618
reflectionPermissionFlags = ReflectionPermission.AllFlagsAndMore;
for (int i = 0; i < specialPermissions.Length; i++) {
specialPermissions[i] = s_UnrestrictedSpecialPermissionMap[i];
}
}
else {
securityPermission = grantSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
if (securityPermission != null)
securityPermissionFlags = securityPermission.Flags;
reflectionPermission = grantSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
if (reflectionPermission != null)
reflectionPermissionFlags = reflectionPermission.Flags;
for (int i = 0; i < specialPermissions.Length; i++) {
specialPermissions[i] = grantSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
}
}
}
if (deniedSet != null) {
if (deniedSet.IsUnrestricted()) {
#pragma warning disable 618
securityPermissionFlags = SecurityPermissionFlag.NoFlags;
#pragma warning restore 618
reflectionPermissionFlags = ReflectionPermissionFlag.NoFlags;
for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) {
specialPermissions[i] = null;
}
}
else {
securityPermission = deniedSet.GetPermission(BuiltInPermissionIndex.SecurityPermissionIndex) as SecurityPermission;
if (securityPermission != null)
securityPermissionFlags &= ~securityPermission.Flags;
reflectionPermission = deniedSet.GetPermission(BuiltInPermissionIndex.ReflectionPermissionIndex) as ReflectionPermission;
if (reflectionPermission != null)
reflectionPermissionFlags &= ~reflectionPermission.Flags;
for (int i = 0; i < s_BuiltInPermissionIndexMap.Length; i++) {
CodeAccessPermission deniedSpecialPermission = deniedSet.GetPermission(s_BuiltInPermissionIndexMap[i][0]) as CodeAccessPermission;
if (deniedSpecialPermission != null && !deniedSpecialPermission.IsSubsetOf(null))
specialPermissions[i] = null; // we don't care about the exact value here.
}
}
}
int flags = MapToSpecialFlags(securityPermissionFlags, reflectionPermissionFlags);
if (flags != -1) {
for (int i = 0; i < specialPermissions.Length; i++) {
if (specialPermissions[i] != null && ((IUnrestrictedPermission) specialPermissions[i]).IsUnrestricted())
flags |= (1 << (int) s_BuiltInPermissionIndexMap[i][1]);
}
}
return flags;
}
}
#pragma warning disable 618
private static int MapToSpecialFlags (SecurityPermissionFlag securityPermissionFlags, ReflectionPermissionFlag reflectionPermissionFlags) {
int flags = 0;
if ((securityPermissionFlags & SecurityPermissionFlag.UnmanagedCode) == SecurityPermissionFlag.UnmanagedCode)
flags |= (1 << (int) PermissionType.SecurityUnmngdCodeAccess);
if ((securityPermissionFlags & SecurityPermissionFlag.SkipVerification) == SecurityPermissionFlag.SkipVerification)
flags |= (1 << (int) PermissionType.SecuritySkipVerification);
if ((securityPermissionFlags & SecurityPermissionFlag.Assertion) == SecurityPermissionFlag.Assertion)
flags |= (1 << (int) PermissionType.SecurityAssert);
if ((securityPermissionFlags & SecurityPermissionFlag.SerializationFormatter) == SecurityPermissionFlag.SerializationFormatter)
flags |= (1 << (int) PermissionType.SecuritySerialization);
if ((securityPermissionFlags & SecurityPermissionFlag.BindingRedirects) == SecurityPermissionFlag.BindingRedirects)
flags |= (1 << (int) PermissionType.SecurityBindingRedirects);
if ((securityPermissionFlags & SecurityPermissionFlag.ControlEvidence) == SecurityPermissionFlag.ControlEvidence)
flags |= (1 << (int) PermissionType.SecurityControlEvidence);
if ((securityPermissionFlags & SecurityPermissionFlag.ControlPrincipal) == SecurityPermissionFlag.ControlPrincipal)
flags |= (1 << (int) PermissionType.SecurityControlPrincipal);
if ((reflectionPermissionFlags & ReflectionPermissionFlag.RestrictedMemberAccess) == ReflectionPermissionFlag.RestrictedMemberAccess)
flags |= (1 << (int)PermissionType.ReflectionRestrictedMemberAccess);
if ((reflectionPermissionFlags & ReflectionPermissionFlag.MemberAccess) == ReflectionPermissionFlag.MemberAccess)
flags |= (1 << (int) PermissionType.ReflectionMemberAccess);
return flags;
}
#pragma warning restore 618
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool IsSameType(String strLeft, String strRight);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool _SetThreadSecurity(bool bThreadSecurity);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void GetGrantedPermissions(ObjectHandleOnStack retGranted, ObjectHandleOnStack retDenied, StackCrawlMarkHandle stackMark);
}
}
| |
//==============================================================================
// TorqueLab -> MeshRoadEditor - Road Manager - NodeData
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
// Custom PhysicsTools Functions
//==============================================================================
//==============================================================================
function Lab::togglePhysicToolbar(%this,%val) {
if (%val $="")
%val = !PhysicsToolsToolbar.visible;
PhysicsToolsToolbar.visible = %val;
}
//------------------------------------------------------------------------------
//==============================================================================
function togglePhysicToolbar(%val) {
Lab.togglePhysicToolbar(%val);
}
//------------------------------------------------------------------------------
//==============================================================================
// Custom PhysicsTools Functions
//==============================================================================
function PT::physicsToggleSimulation(%this) {
%isEnabled = physicsSimulationEnabled();
if ( %isEnabled ) {
physicsStateText.setText( "Simulation is paused." );
PT.physicsStopSimulation( "client" );
PT.physicsStopSimulation( "server" );
} else {
physicsStateText.setText( "Simulation is unpaused." );
PT.physicsStartSimulation( "client" );
PT.physicsStartSimulation( "server" );
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Custom PhysicsTools Functions
//==============================================================================
function PT::setInitialPhysicsState(%this,%startDelay) {
%isEnabled = physicsSimulationEnabled();
if ( %isEnabled ) {
// physicsStateText.setText( "Simulation is paused." );
PT.physicsStopSimulation( "client" );
PT.physicsStopSimulation( "server" );
}
PT.physicsRestoreState();
if (%startDelay $= "")
return;
%this.schedule(%startDelay,"doAction","start");
}
//------------------------------------------------------------------------------
//==============================================================================
// Custom PhysicsTools Functions
//==============================================================================
function PT::doAction(%this,%action) {
%isEnabled = physicsSimulationEnabled();
switch$(%action) {
case "start":
PT.physicsSetTimeScale(1);
if (%isEnabled)
return;
PT.physicsStartSimulation( "client" );
PT.physicsStartSimulation( "server" );
case "pause":
PT.physicsSetTimeScale(0);
case "stop":
if (!%isEnabled)
return;
PT.physicsStopSimulation( "client" );
PT.physicsStopSimulation( "server" );
case "restart":
PT.setInitialPhysicsState(500);
case "store":
PT.physicsStoreState();
case "refresh":
PT.setInitialPhysicsState();
}
}
//------------------------------------------------------------------------------
function PhysicsToolsIcon::onClick(%this) {
%action = %this.internalName;
PT.doAction(%action);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function PhysicsToolsSlider::doCommand(%this) {
%action = %this.internalName;
switch$(%action) {
case "timeScale":
%scale = mFloatLength(%this.getValue(),1);
PT.physicsSetTimeScale(%scale);
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function PhysicsToolsSlider::doAltCommand(%this) {
%action = %this.internalName;
switch$(%action) {
case "timeScale":
%scale = mFloatLength(%this.getValue(),1);
PT.physicsSetTimeScale(%scale);
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Physics Plugin Functions
//==============================================================================
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsPluginPresent(%this) {
return physicsPluginPresent();
}
//------------------------------------------------------------------------------
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsInit(%this,%library) {
return physicsInit(%library);
}
//------------------------------------------------------------------------------
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsDestroy(%this) {
physicsDestroy();
}
//------------------------------------------------------------------------------
//==============================================================================
// Physics World Functions
//==============================================================================
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsInitWorld(%this,%worldName) {
return physicsInitWorld(%worldName);
}
//------------------------------------------------------------------------------
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsDestroyWorld(%this,%worldName) {
physicsDestroyWorld(%worldName);
}
//------------------------------------------------------------------------------
//==============================================================================
// Physics Simulation Functions
//==============================================================================
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsStartSimulation(%this,%worldName) {
physicsStartSimulation(%worldName);
}
//------------------------------------------------------------------------------
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsStopSimulation(%this,%worldName) {
physicsStopSimulation(%worldName);
}
//------------------------------------------------------------------------------
//==============================================================================
//Returns true if a physics plugin exists and is initialized
function PT::physicsSimulationEnabled(%this,%worldName) {
return physicsSimulationEnabled(%worldName);
}
//------------------------------------------------------------------------------
//==============================================================================
// Physics TimeScale Functions
//==============================================================================
//==============================================================================
// Used for slowing down time on the physics simulation, and for pausing/restarting the simulation.
function PT::physicsSetTimeScale(%this,%scale) {
logd("PT::physicsSetTimeScale(%this,%scale)",%scale);
physicsSetTimeScale(%scale);
}
//------------------------------------------------------------------------------
//==============================================================================
// Get the currently set time scale.
function PT::physicsGetTimeScale(%this,%scale) {
return physicsGetTimeScale();
}
//------------------------------------------------------------------------------
//==============================================================================
// Physics State Functions
//==============================================================================
//==============================================================================
// Used to send a signal to objects in the
// physics simulation that they should store
// their current state for later restoration,
// such as when the editor is closed.
function PT::physicsStoreState(%this) {
physicsStoreState();
}
//------------------------------------------------------------------------------
//==============================================================================
// Used to send a signal to objects in the
// physics simulation that they should restore
// their saved state, such as when the editor is opened.
function PT::physicsRestoreState(%this) {
physicsRestoreState();
}
//------------------------------------------------------------------------------
//==============================================================================
// Physics Debug Functions
//==============================================================================
//==============================================================================
// Get the currently set time scale.
function PT::physicsDebugDraw(%this,%enable) {
physicsDebugDraw(%enable);
}
//------------------------------------------------------------------------------
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\SpectatorPawn.h:16
namespace UnrealEngine
{
[ManageType("ManageSpectatorPawn")]
public partial class ManageSpectatorPawn : ASpectatorPawn, IManageWrapper
{
public ManageSpectatorPawn(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_LookUpAtRate(IntPtr self, float rate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_MoveForward(IntPtr self, float val);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_MoveRight(IntPtr self, float val);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_MoveUp_World(IntPtr self, float val);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_TurnAtRate(IntPtr self, float rate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_AddControllerPitchInput(IntPtr self, float val);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_AddControllerRollInput(IntPtr self, float val);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_AddControllerYawInput(IntPtr self, float val);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_DestroyPlayerInputComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_DetachFromControllerPendingDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_Controller(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_PlayerState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PawnClientRestart(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PawnStartFire(IntPtr self, byte fireModeNum);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_RecalculateBaseEyeHeight(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_Restart(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_SetPlayerDefaults(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_SpawnDefaultController(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_TurnOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_UnPossessed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_UpdateNavigationRelevance(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_ClearCrossLevelReferences(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_Destroyed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_ForceNetRelevant(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_ForceNetUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_GatherCurrentMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_K2_DestroyActor(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_LifeSpanExpired(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_MarkComponentsAsPendingKill(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_NotifyActorBeginCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_NotifyActorEndCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_AttachmentReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_Instigator(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_Owner(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_ReplicatedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnRep_ReplicateMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OutsideWorldBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostActorCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostNetInit(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostNetReceiveLocationAndRotation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostNetReceivePhysicState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostNetReceiveRole(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostUnregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PreInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PreRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_RegisterActorTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_RegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_ReregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_RerunConstructionScripts(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_Reset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_RewindForReplay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_SetActorHiddenInGame(IntPtr self, bool bNewHidden);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_SetLifeSpan(IntPtr self, float inLifespan);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_SetReplicateMovement(IntPtr self, bool bInReplicateMovement);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_TearOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_TeleportSucceeded(IntPtr self, bool bIsATest);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_Tick(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_TornOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_UnregisterAllComponents(IntPtr self, bool bForReregister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__ASpectatorPawn_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Called via input to look up at a given rate (or down if Rate is negative).
/// </summary>
/// <param name="rate">This is a normalized rate, i.e. 1.0 means 100% of desired turn rate</param>
public override void LookUpAtRate(float rate)
=> E__Supper__ASpectatorPawn_LookUpAtRate(this, rate);
/// <summary>
/// Input callback to move forward in local space (or backward if Val is negative).
/// <see cref="APawn"/>
/// </summary>
/// <param name="val">Amount of movement in the forward direction (or backward if negative).</param>
public override void MoveForward(float val)
=> E__Supper__ASpectatorPawn_MoveForward(this, val);
/// <summary>
/// Input callback to strafe right in local space (or left if Val is negative).
/// <see cref="APawn"/>
/// </summary>
/// <param name="val">Amount of movement in the right direction (or left if negative).</param>
public override void MoveRight(float val)
=> E__Supper__ASpectatorPawn_MoveRight(this, val);
/// <summary>
/// Input callback to move up in world space (or down if Val is negative).
/// <see cref="APawn"/>
/// </summary>
/// <param name="val">Amount of movement in the world up direction (or down if negative).</param>
public override void MoveUp_World(float val)
=> E__Supper__ASpectatorPawn_MoveUp_World(this, val);
/// <summary>
/// Called via input to turn at a given rate.
/// </summary>
/// <param name="rate">This is a normalized rate, i.e. 1.0 means 100% of desired turn rate</param>
public override void TurnAtRate(float rate)
=> E__Supper__ASpectatorPawn_TurnAtRate(this, rate);
/// <summary>
/// Add input (affecting Pitch) to the Controller's ControlRotation, if it is a local PlayerController.
/// <para>This value is multiplied by the PlayerController's InputPitchScale value. </para>
/// <see cref="PlayerController"/>
/// </summary>
/// <param name="val">Amount to add to Pitch. This value is multiplied by the PlayerController's InputPitchScale value.</param>
public override void AddControllerPitchInput(float val)
=> E__Supper__ASpectatorPawn_AddControllerPitchInput(this, val);
/// <summary>
/// Add input (affecting Roll) to the Controller's ControlRotation, if it is a local PlayerController.
/// <para>This value is multiplied by the PlayerController's InputRollScale value. </para>
/// <see cref="PlayerController"/>
/// </summary>
/// <param name="val">Amount to add to Roll. This value is multiplied by the PlayerController's InputRollScale value.</param>
public override void AddControllerRollInput(float val)
=> E__Supper__ASpectatorPawn_AddControllerRollInput(this, val);
/// <summary>
/// Add input (affecting Yaw) to the Controller's ControlRotation, if it is a local PlayerController.
/// <para>This value is multiplied by the PlayerController's InputYawScale value. </para>
/// <see cref="PlayerController"/>
/// </summary>
/// <param name="val">Amount to add to Yaw. This value is multiplied by the PlayerController's InputYawScale value.</param>
public override void AddControllerYawInput(float val)
=> E__Supper__ASpectatorPawn_AddControllerYawInput(this, val);
/// <summary>
/// Destroys the player input component and removes any references to it.
/// </summary>
protected override void DestroyPlayerInputComponent()
=> E__Supper__ASpectatorPawn_DestroyPlayerInputComponent(this);
/// <summary>
/// Call this function to detach safely pawn from its controller, knowing that we will be destroyed soon.
/// </summary>
public override void DetachFromControllerPendingDestroy()
=> E__Supper__ASpectatorPawn_DetachFromControllerPendingDestroy(this);
public override void OnRep_Controller()
=> E__Supper__ASpectatorPawn_OnRep_Controller(this);
public override void OnRep_PlayerState()
=> E__Supper__ASpectatorPawn_OnRep_PlayerState(this);
/// <summary>
/// Tell client that the Pawn is begin restarted. Calls Restart().
/// </summary>
public override void PawnClientRestart()
=> E__Supper__ASpectatorPawn_PawnClientRestart(this);
/// <summary>
/// Handle StartFire() passed from PlayerController
/// </summary>
public override void PawnStartFire(byte fireModeNum)
=> E__Supper__ASpectatorPawn_PawnStartFire(this, fireModeNum);
/// <summary>
/// Set BaseEyeHeight based on current state.
/// </summary>
public override void RecalculateBaseEyeHeight()
=> E__Supper__ASpectatorPawn_RecalculateBaseEyeHeight(this);
/// <summary>
/// Called when the Pawn is being restarted (usually by being possessed by a Controller).
/// </summary>
public override void Restart()
=> E__Supper__ASpectatorPawn_Restart(this);
/// <summary>
/// Make sure pawn properties are back to default.
/// </summary>
public override void SetPlayerDefaults()
=> E__Supper__ASpectatorPawn_SetPlayerDefaults(this);
/// <summary>
/// Spawn default controller for this Pawn, and get possessed by it.
/// </summary>
public override void SpawnDefaultController()
=> E__Supper__ASpectatorPawn_SpawnDefaultController(this);
/// <summary>
/// Freeze pawn - stop sounds, animations, physics, weapon firing
/// </summary>
public override void TurnOff()
=> E__Supper__ASpectatorPawn_TurnOff(this);
/// <summary>
/// Called when our Controller no longer possesses us.
/// </summary>
public override void UnPossessed()
=> E__Supper__ASpectatorPawn_UnPossessed(this);
/// <summary>
/// Update all components relevant for navigation generators to match bCanAffectNavigationGeneration flag
/// </summary>
public override void UpdateNavigationRelevance()
=> E__Supper__ASpectatorPawn_UpdateNavigationRelevance(this);
/// <summary>
/// Overridable native event for when play begins for this actor.
/// </summary>
protected override void BeginPlay()
=> E__Supper__ASpectatorPawn_BeginPlay(this);
/// <summary>
/// Do anything needed to clear out cross level references; Called from ULevel::PreSave
/// </summary>
public override void ClearCrossLevelReferences()
=> E__Supper__ASpectatorPawn_ClearCrossLevelReferences(this);
/// <summary>
/// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending
/// </summary>
public override void Destroyed()
=> E__Supper__ASpectatorPawn_Destroyed(this);
/// <summary>
/// Forces this actor to be net relevant if it is not already by default
/// </summary>
public override void ForceNetRelevant()
=> E__Supper__ASpectatorPawn_ForceNetRelevant(this);
/// <summary>
/// Force actor to be updated to clients/demo net drivers
/// </summary>
public override void ForceNetUpdate()
=> E__Supper__ASpectatorPawn_ForceNetUpdate(this);
/// <summary>
/// Fills ReplicatedMovement property
/// </summary>
public override void GatherCurrentMovement()
=> E__Supper__ASpectatorPawn_GatherCurrentMovement(this);
/// <summary>
/// Invalidates anything produced by the last lighting build.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bTranslationOnly)
=> E__Supper__ASpectatorPawn_InvalidateLightingCacheDetailed(this, bTranslationOnly);
/// <summary>
/// Destroy the actor
/// </summary>
public override void DestroyActor()
=> E__Supper__ASpectatorPawn_K2_DestroyActor(this);
/// <summary>
/// Called when the lifespan of an actor expires (if he has one).
/// </summary>
public override void LifeSpanExpired()
=> E__Supper__ASpectatorPawn_LifeSpanExpired(this);
/// <summary>
/// Called to mark all components as pending kill when the actor is being destroyed
/// </summary>
public override void MarkComponentsAsPendingKill()
=> E__Supper__ASpectatorPawn_MarkComponentsAsPendingKill(this);
/// <summary>
/// Event when this actor has the mouse moved over it with the clickable interface.
/// </summary>
public override void NotifyActorBeginCursorOver()
=> E__Supper__ASpectatorPawn_NotifyActorBeginCursorOver(this);
/// <summary>
/// Event when this actor has the mouse moved off of it with the clickable interface.
/// </summary>
public override void NotifyActorEndCursorOver()
=> E__Supper__ASpectatorPawn_NotifyActorEndCursorOver(this);
public override void OnRep_AttachmentReplication()
=> E__Supper__ASpectatorPawn_OnRep_AttachmentReplication(this);
public override void OnRep_Instigator()
=> E__Supper__ASpectatorPawn_OnRep_Instigator(this);
protected override void OnRep_Owner()
=> E__Supper__ASpectatorPawn_OnRep_Owner(this);
public override void OnRep_ReplicatedMovement()
=> E__Supper__ASpectatorPawn_OnRep_ReplicatedMovement(this);
public override void OnRep_ReplicateMovement()
=> E__Supper__ASpectatorPawn_OnRep_ReplicateMovement(this);
/// <summary>
/// Called on the client when the replication paused value is changed
/// </summary>
public override void OnReplicationPausedChanged(bool bIsReplicationPaused)
=> E__Supper__ASpectatorPawn_OnReplicationPausedChanged(this, bIsReplicationPaused);
/// <summary>
/// Called when the Actor is outside the hard limit on world bounds
/// </summary>
public override void OutsideWorldBounds()
=> E__Supper__ASpectatorPawn_OutsideWorldBounds(this);
/// <summary>
/// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay
/// <para>For actors with a root component, the location and rotation will have already been set. </para>
/// This is called before calling construction scripts, but after native components have been created
/// </summary>
public override void PostActorCreated()
=> E__Supper__ASpectatorPawn_PostActorCreated(this);
/// <summary>
/// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay
/// </summary>
public override void PostInitializeComponents()
=> E__Supper__ASpectatorPawn_PostInitializeComponents(this);
/// <summary>
/// Always called immediately after spawning and reading in replicated properties
/// </summary>
public override void PostNetInit()
=> E__Supper__ASpectatorPawn_PostNetInit(this);
/// <summary>
/// Update location and rotation from ReplicatedMovement. Not called for simulated physics!
/// </summary>
public override void PostNetReceiveLocationAndRotation()
=> E__Supper__ASpectatorPawn_PostNetReceiveLocationAndRotation(this);
/// <summary>
/// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity()
/// </summary>
public override void PostNetReceivePhysicState()
=> E__Supper__ASpectatorPawn_PostNetReceivePhysicState(this);
/// <summary>
/// Always called immediately after a new Role is received from the remote.
/// </summary>
public override void PostNetReceiveRole()
=> E__Supper__ASpectatorPawn_PostNetReceiveRole(this);
/// <summary>
/// Called after all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PostRegisterAllComponents()
=> E__Supper__ASpectatorPawn_PostRegisterAllComponents(this);
/// <summary>
/// Called after all currently registered components are cleared
/// </summary>
public override void PostUnregisterAllComponents()
=> E__Supper__ASpectatorPawn_PostUnregisterAllComponents(this);
/// <summary>
/// Called right before components are initialized, only called during gameplay
/// </summary>
public override void PreInitializeComponents()
=> E__Supper__ASpectatorPawn_PreInitializeComponents(this);
/// <summary>
/// Called before all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PreRegisterAllComponents()
=> E__Supper__ASpectatorPawn_PreRegisterAllComponents(this);
/// <summary>
/// Calls PrestreamTextures() for all the actor's meshcomponents.
/// </summary>
/// <param name="seconds">Number of seconds to force all mip-levels to be resident</param>
/// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param>
/// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param>
public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups)
=> E__Supper__ASpectatorPawn_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups);
/// <summary>
/// Virtual call chain to register all tick functions for the actor class hierarchy
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterActorTickFunctions(bool bRegister)
=> E__Supper__ASpectatorPawn_RegisterActorTickFunctions(this, bRegister);
/// <summary>
/// Ensure that all the components in the Components array are registered
/// </summary>
public override void RegisterAllComponents()
=> E__Supper__ASpectatorPawn_RegisterAllComponents(this);
/// <summary>
/// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty.
/// </summary>
public override void ReregisterAllComponents()
=> E__Supper__ASpectatorPawn_ReregisterAllComponents(this);
/// <summary>
/// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location.
/// </summary>
public override void RerunConstructionScripts()
=> E__Supper__ASpectatorPawn_RerunConstructionScripts(this);
/// <summary>
/// Reset actor to initial state - used when restarting level without reloading.
/// </summary>
public override void Reset()
=> E__Supper__ASpectatorPawn_Reset(this);
/// <summary>
/// Called on the actor before checkpoint data is applied during a replay.
/// <para>Only called if bReplayRewindable is set. </para>
/// </summary>
public override void RewindForReplay()
=> E__Supper__ASpectatorPawn_RewindForReplay(this);
/// <summary>
/// Sets the actor to be hidden in the game
/// </summary>
/// <param name="bNewHidden">Whether or not to hide the actor and all its components</param>
public override void SetActorHiddenInGame(bool bNewHidden)
=> E__Supper__ASpectatorPawn_SetActorHiddenInGame(this, bNewHidden);
/// <summary>
/// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed.
/// </summary>
public override void SetLifeSpan(float inLifespan)
=> E__Supper__ASpectatorPawn_SetLifeSpan(this, inLifespan);
/// <summary>
/// Set whether this actor's movement replicates to network clients.
/// </summary>
/// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param>
public override void SetReplicateMovement(bool bInReplicateMovement)
=> E__Supper__ASpectatorPawn_SetReplicateMovement(this, bInReplicateMovement);
/// <summary>
/// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true.
/// </summary>
public override void TearOff()
=> E__Supper__ASpectatorPawn_TearOff(this);
/// <summary>
/// Called from TeleportTo() when teleport succeeds
/// </summary>
public override void TeleportSucceeded(bool bIsATest)
=> E__Supper__ASpectatorPawn_TeleportSucceeded(this, bIsATest);
/// <summary>
/// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame.
/// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para>
/// </summary>
/// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param>
public override void Tick(float deltaSeconds)
=> E__Supper__ASpectatorPawn_Tick(this, deltaSeconds);
/// <summary>
/// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients.
/// <para>@see bTearOff </para>
/// </summary>
public override void TornOff()
=> E__Supper__ASpectatorPawn_TornOff(this);
/// <summary>
/// Unregister all currently registered components
/// </summary>
/// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param>
public override void UnregisterAllComponents(bool bForReregister)
=> E__Supper__ASpectatorPawn_UnregisterAllComponents(this, bForReregister);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__ASpectatorPawn_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__ASpectatorPawn_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__ASpectatorPawn_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__ASpectatorPawn_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__ASpectatorPawn_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__ASpectatorPawn_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__ASpectatorPawn_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__ASpectatorPawn_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__ASpectatorPawn_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__ASpectatorPawn_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__ASpectatorPawn_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__ASpectatorPawn_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__ASpectatorPawn_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__ASpectatorPawn_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__ASpectatorPawn_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageSpectatorPawn self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageSpectatorPawn(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageSpectatorPawn>(PtrDesc);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Runtime.Serialization;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using JustGestures.Properties;
using JustGestures.GestureParts;
using JustGestures.Features;
namespace JustGestures.TypeOfAction
{
[Serializable]
class KeystrokesOptions : BaseActionClass
{
public const string NAME = "keystrokes_name";
public const string KEYSTROKES_CUSTOM = "keystrokes_custom";
public const string KEYSTROKES_PRIVATE_COPY_TEXT = "keystrokes_private_copy_text";
public const string KEYSTROKES_PRIVATE_PASTE_TEXT = "keystrokes_private_paste_text";
public const string KEYSTROKES_SYSTEM_COPY = "keystrokes_system_copy";
public const string KEYSTROKES_SYSTEM_CUT = "keystrokes_system_cut";
public const string KEYSTROKES_SYSTEM_PASTE = "keystrokes_system_paste";
public const string KEYSTROKES_PLAIN_TEXT = "keystrokes_plain_text";
public const string KEYSTROKES_ZOOM_IN = "keystrokes_zoom_in";
public const string KEYSTROKES_ZOOM_OUT = "keystrokes_zoom_out";
const string KEYSTROKES_INSERT_NUMBER = "keystrokes_inser_number_to_icon";
private Point m_location;
public KeystrokesOptions()
{
m_actions = new List<string>
(new string[] {
KEYSTROKES_SYSTEM_COPY,
KEYSTROKES_SYSTEM_CUT,
KEYSTROKES_SYSTEM_PASTE,
KEYSTROKES_PRIVATE_COPY_TEXT,
KEYSTROKES_PRIVATE_PASTE_TEXT,
KEYSTROKES_ZOOM_IN,
KEYSTROKES_ZOOM_OUT,
KEYSTROKES_PLAIN_TEXT,
KEYSTROKES_CUSTOM
});
}
public KeystrokesOptions(KeystrokesOptions action) : base(action) { }
public KeystrokesOptions(SerializationInfo info, StreamingContext context)
: base (info, context)
{
}
public override object Clone()
{
return new KeystrokesOptions(this);
}
public KeystrokesOptions(string action)
: base(action)
{
switch (this.Name)
{
case KEYSTROKES_PRIVATE_COPY_TEXT:
case KEYSTROKES_SYSTEM_COPY:
this.KeyScript = new List<List<MyKey>>();
this.KeyScript.Add(new List<MyKey>() { AllKeys.KEY_CONTROL_DOWN, AllKeys.KEY_C, AllKeys.KEY_CONTROL_UP });
break;
case KEYSTROKES_PLAIN_TEXT:
case KEYSTROKES_PRIVATE_PASTE_TEXT:
case KEYSTROKES_SYSTEM_PASTE:
this.KeyScript = new List<List<MyKey>>();
this.KeyScript.Add(new List<MyKey>() { AllKeys.KEY_CONTROL_DOWN, AllKeys.KEY_V, AllKeys.KEY_CONTROL_UP });
break;
case KEYSTROKES_SYSTEM_CUT:
this.KeyScript = new List<List<MyKey>>();
this.KeyScript.Add(new List<MyKey>() { AllKeys.KEY_CONTROL_DOWN, AllKeys.KEY_X, AllKeys.KEY_CONTROL_UP });
break;
case KEYSTROKES_ZOOM_IN:
this.KeyScript = new List<List<MyKey>>();
this.KeyScript.Add(new List<MyKey>() { AllKeys.KEY_CONTROL_DOWN, AllKeys.MOUSE_WHEEL_DOWN, AllKeys.KEY_CONTROL_UP });
break;
case KEYSTROKES_ZOOM_OUT:
this.KeyScript = new List<List<MyKey>>();
this.KeyScript.Add(new List<MyKey>() { AllKeys.KEY_CONTROL_DOWN, AllKeys.MOUSE_WHEEL_UP, AllKeys.KEY_CONTROL_UP });
break;
}
if (this.KeyScript != null)
{
this.KeyScript.Add(new List<MyKey>());
this.KeyScript.Add(new List<MyKey>());
this.KeyScript.Add(new List<MyKey>());
}
}
public override void ExecuteAction(IntPtr activeWnd, Point location)
{
IntPtr hwnd = Win32.GetForegroundWindow();
if (hwnd != activeWnd)
{
Win32.SetForegroundWindow(activeWnd);
Win32.SetActiveWindow(activeWnd);
System.Threading.Thread.Sleep(100);
}
m_location = location;
Thread threadExecuteInSta;
switch (this.Name)
{
case KEYSTROKES_PRIVATE_COPY_TEXT:
threadExecuteInSta = new Thread(new ThreadStart(CopyToClip));
threadExecuteInSta.SetApartmentState(ApartmentState.STA);
threadExecuteInSta.Start();
//CopyToClip();
break;
case KEYSTROKES_PRIVATE_PASTE_TEXT:
threadExecuteInSta = new Thread(new ThreadStart(PasteFromClip));
threadExecuteInSta.SetApartmentState(ApartmentState.STA);
threadExecuteInSta.Start();
//PasteFromClip();
break;
case KEYSTROKES_PLAIN_TEXT:
threadExecuteInSta = new Thread(new ThreadStart(InsertText));
threadExecuteInSta.SetApartmentState(ApartmentState.STA);
threadExecuteInSta.Start();
//InsertText();
break;
case KEYSTROKES_ZOOM_IN:
case KEYSTROKES_ZOOM_OUT:
case KEYSTROKES_SYSTEM_COPY:
case KEYSTROKES_SYSTEM_CUT:
case KEYSTROKES_SYSTEM_PASTE:
case KEYSTROKES_CUSTOM:
ExecuteKeyList(MouseAction.ModifierClick, location);
break;
}
}
public override bool IsSameType(BaseActionClass action)
{
if (!base.IsSameType(action))
return false;
else
{
switch (this.Name)
{
case KEYSTROKES_CUSTOM:
case KEYSTROKES_PLAIN_TEXT:
return (this.Name == action.Name);
case KEYSTROKES_PRIVATE_COPY_TEXT:
case KEYSTROKES_PRIVATE_PASTE_TEXT:
if (action.Name == KEYSTROKES_PRIVATE_COPY_TEXT ||
action.Name == KEYSTROKES_PRIVATE_PASTE_TEXT)
return true;
else
return false;
}
switch (action.Name)
{
case KEYSTROKES_CUSTOM:
case KEYSTROKES_PLAIN_TEXT:
return (this.Name == action.Name);
case KEYSTROKES_PRIVATE_COPY_TEXT:
case KEYSTROKES_PRIVATE_PASTE_TEXT:
if (this.Name == KEYSTROKES_PRIVATE_COPY_TEXT ||
this.Name == KEYSTROKES_PRIVATE_PASTE_TEXT)
return true;
else
return false;
}
return true;
}
}
public override string GetDescription()
{
string str = this.Details;
switch (this.Name)
{
case KEYSTROKES_ZOOM_IN:
case KEYSTROKES_ZOOM_OUT:
case KEYSTROKES_SYSTEM_COPY:
case KEYSTROKES_SYSTEM_PASTE:
case KEYSTROKES_SYSTEM_CUT:
case KEYSTROKES_CUSTOM:
str = string.Format("{0} - {1}",Languages.Translation.GetText("C_CK_gB_keyScript"), KeysFromDetails(this.Details));
break;
case KEYSTROKES_PRIVATE_PASTE_TEXT:
case KEYSTROKES_PRIVATE_COPY_TEXT:
if (this.Details != string.Empty)
str = string.Format("{0} {1}", Languages.Translation.GetText(this.Name), int.Parse(this.Details) + 1);
break;
case KEYSTROKES_PLAIN_TEXT:
str = string.Format("{0}: {1}", Languages.Translation.GetText(this.Name), str);
break;
}
return str;
}
public override Bitmap GetIcon(int size)
{
Bitmap bmp = null;
switch (this.Name)
{
case NAME:
return Resources.keystrokes;
//break;
case KEYSTROKES_ZOOM_IN:
return Resources.zoom_in;
//break;
case KEYSTROKES_ZOOM_OUT:
return Resources.zoom_out;
//break;
case KEYSTROKES_CUSTOM:
return Resources.keystrokes;
//break;
case KEYSTROKES_SYSTEM_COPY:
return Resources.edit_copy;
//break;
case KEYSTROKES_SYSTEM_PASTE:
return Resources.edit_paste;
//break;
case KEYSTROKES_SYSTEM_CUT:
return Resources.edit_cut;
//break;
case KEYSTROKES_PRIVATE_COPY_TEXT:
bmp = Resources.edit_copy;
goto case KEYSTROKES_INSERT_NUMBER;
//break;
case KEYSTROKES_PRIVATE_PASTE_TEXT:
bmp = Resources.edit_paste;
goto case KEYSTROKES_INSERT_NUMBER;
//break;
case KEYSTROKES_INSERT_NUMBER:
int height = Convert.ToInt16(bmp.Height / 1.75);
Graphics g = Graphics.FromImage(bmp);
string number = this.Details == string.Empty ? "x" : (int.Parse(this.Details) + 1).ToString();
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
Font font = new Font(FontFamily.GenericSansSerif, height, FontStyle.Regular);
g.DrawString(number, font, Brushes.Black, new RectangleF(bmp.Width - height, bmp.Height - height, height, height), format);
g.Dispose();
return bmp;
//break;
case KEYSTROKES_PLAIN_TEXT:
return Resources.text;
//break;
default:
return Resources.keystrokes;
//break;
}
}
delegate void emptydel();
private void InsertText()
{
ReadOnlyCollection<ClipData> clipData = ClipboardHandler.GetClipboard();
Thread.Sleep(50);
Clipboard.SetText(this.Details);
Thread.Sleep(50);
ExecuteKeyList(MouseAction.ModifierClick, m_location);
Thread.Sleep(200);
ClipboardHandler.SetClipboard(clipData);
}
private void CopyToClip()
{
//ReadOnlyCollection<ClipData> backup = ClipboardHandler.GetClipboard();
//ClipboardHandler.EmptyClipboard();
//KeyInput.ExecuteKeyInput(AllKeys.KEY_CONTROL_DOWN);
//KeyInput.ExecuteKeyInput(AllKeys.KEY_C);
//KeyInput.ExecuteKeyInput(AllKeys.KEY_CONTROL_UP);
ExecuteKeyList(MouseAction.ModifierClick, m_location);
System.Threading.Thread.Sleep(250);
//SendKeys.SendWait("^c");
//Win32.SendMessage(hwnd, Win32.WM_COPY, 0, 0);
int index = int.Parse(this.Details);
Form_engine.PrivateTextClipboards[index] = Clipboard.GetText();
//Form_engine.PrivateClipboards[index] = ClipboardHandler.GetClipboard();
//ClipboardHandler.EmptyClipboard();
//ClipboardHandler.SetClipboard(backup);
}
private void PasteFromClip()
{
//ReadOnlyCollection<ClipData> backup = ClipboardHandler.GetClipboard();
int index = int.Parse(this.Details);
Clipboard.SetText(Form_engine.PrivateTextClipboards[index]);
System.Threading.Thread.Sleep(50);
//ClipboardHandler.SetClipboard(Form_engine.PrivateClipboards[index]);
//KeyInput.ExecuteKeyInput(AllKeys.KEY_CONTROL_DOWN);
//KeyInput.ExecuteKeyInput(AllKeys.KEY_V);
//KeyInput.ExecuteKeyInput(AllKeys.KEY_CONTROL_UP);
ExecuteKeyList(MouseAction.ModifierClick, m_location);
//SendKeys.SendWait("^v");
//Win32.SendMessage(hwnd, Win32.WM_PASTE, 0, 0);
//ClipboardHandler.SetClipboard(backup);
}
public static string KeysFromDetails(string _details)
{
return _details;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Xml;
using Umbraco.Core;
using System.Collections.Generic;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using RazorDataTypeModelStaticMappingItem = umbraco.MacroEngines.RazorDataTypeModelStaticMappingItem;
namespace umbraco
{
/// <summary>
/// The UmbracoSettings Class contains general settings information for the entire Umbraco instance based on information from the /config/umbracoSettings.config file
/// </summary>
[Obsolete("Use UmbracoConfiguration.Current.UmbracoSettings instead, it offers all settings in strongly typed formats. This class will be removed in future versions.")]
public class UmbracoSettings
{
[Obsolete("This hasn't been used since 4.1!")]
public const string TEMP_FRIENDLY_XML_CHILD_CONTAINER_NODENAME = ""; // "children";
/// <summary>
/// Gets the umbraco settings document.
/// </summary>
/// <value>The _umbraco settings.</value>
public static XmlDocument _umbracoSettings
{
get
{
var us = (XmlDocument)HttpRuntime.Cache["umbracoSettingsFile"] ?? EnsureSettingsDocument();
return us;
}
}
/// <summary>
/// Gets a value indicating whether the media library will create new directories in the /media directory.
/// </summary>
/// <value>
/// <c>true</c> if new directories are allowed otherwise, <c>false</c>.
/// </value>
public static bool UploadAllowDirectories
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UploadAllowDirectories; }
}
/// <summary>
/// Gets a value indicating whether logging is enabled in umbracoSettings.config (/settings/logging/enableLogging).
/// </summary>
/// <value><c>true</c> if logging is enabled; otherwise, <c>false</c>.</value>
public static bool EnableLogging
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.EnableLogging; }
}
/// <summary>
/// Gets a value indicating whether logging happens async.
/// </summary>
/// <value><c>true</c> if async logging is enabled; otherwise, <c>false</c>.</value>
public static bool EnableAsyncLogging
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.EnableAsyncLogging; }
}
/// <summary>
/// Gets the assembly of an external logger that can be used to store log items in 3rd party systems
/// </summary>
public static string ExternalLoggerAssembly
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerAssembly; }
}
/// <summary>
/// Gets the type of an external logger that can be used to store log items in 3rd party systems
/// </summary>
public static string ExternalLoggerType
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerType; }
}
/// <summary>
/// Long Audit Trail to external log too
/// </summary>
public static bool ExternalLoggerLogAuditTrail
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerEnableAuditTrail; }
}
/// <summary>
/// Keep user alive as long as they have their browser open? Default is true
/// </summary>
public static bool KeepUserLoggedIn
{
get { return UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn; }
}
/// <summary>
/// Show disabled users in the tree in the Users section in the backoffice
/// </summary>
public static bool HideDisabledUsersInBackoffice
{
get { return UmbracoConfig.For.UmbracoSettings().Security.HideDisabledUsersInBackoffice; }
}
/// <summary>
/// Gets a value indicating whether the logs will be auto cleaned
/// </summary>
/// <value><c>true</c> if logs are to be automatically cleaned; otherwise, <c>false</c></value>
public static bool AutoCleanLogs
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.AutoCleanLogs; }
}
/// <summary>
/// Gets the value indicating the log cleaning frequency (in miliseconds)
/// </summary>
public static int CleaningMiliseconds
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.CleaningMiliseconds; }
}
public static int MaxLogAge
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.MaxLogAge; }
}
/// <summary>
/// Gets the disabled log types.
/// </summary>
/// <value>The disabled log types.</value>
public static XmlNode DisabledLogTypes
{
get { return GetKeyAsNode("/settings/logging/disabledLogTypes"); }
}
/// <summary>
/// Gets the package server url.
/// </summary>
/// <value>The package server url.</value>
public static string PackageServer
{
get { return "packages.umbraco.org"; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use domain prefixes.
/// </summary>
/// <value><c>true</c> if umbraco will use domain prefixes; otherwise, <c>false</c>.</value>
public static bool UseDomainPrefixes
{
get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.UseDomainPrefixes; }
}
/// <summary>
/// This will add a trailing slash (/) to urls when in directory url mode
/// NOTICE: This will always return false if Directory Urls in not active
/// </summary>
public static bool AddTrailingSlash
{
get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.AddTrailingSlash; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use ASP.NET MasterPages for rendering instead of its propriatary templating system.
/// </summary>
/// <value><c>true</c> if umbraco will use ASP.NET MasterPages; otherwise, <c>false</c>.</value>
public static bool UseAspNetMasterPages
{
get { return UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages; }
}
/// <summary>
/// Gets a value indicating whether umbraco will attempt to load any skins to override default template files
/// </summary>
/// <value><c>true</c> if umbraco will override templates with skins if present and configured <c>false</c>.</value>
public static bool EnableTemplateFolders
{
get { return UmbracoConfig.For.UmbracoSettings().Templates.EnableTemplateFolders; }
}
/// <summary>
/// razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml
/// </summary>
public static List<string> NotDynamicXmlDocumentElements
{
get { return UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.Select(x => x.Element).ToList(); }
}
public static List<RazorDataTypeModelStaticMappingItem> RazorDataTypeModelStaticMapping
{
get
{
var mapping = UmbracoConfig.For.UmbracoSettings().Scripting.DataTypeModelStaticMappings;
//now we need to map to the old object until we can clean all this nonsense up
return mapping.Select(x => new RazorDataTypeModelStaticMappingItem()
{
DataTypeGuid = x.DataTypeGuid,
NodeTypeAlias = x.NodeTypeAlias,
PropertyTypeAlias = x.PropertyTypeAlias,
Raw = string.Empty,
TypeName = x.MappingName
}).ToList();
}
}
/// <summary>
/// Gets a value indicating whether umbraco will clone XML cache on publish.
/// </summary>
/// <value>
/// <c>true</c> if umbraco will clone XML cache on publish; otherwise, <c>false</c>.
/// </value>
public static bool CloneXmlCacheOnPublish
{
get { return UmbracoConfig.For.UmbracoSettings().Content.CloneXmlContent; }
}
/// <summary>
/// Gets a value indicating whether rich text editor content should be parsed by tidy.
/// </summary>
/// <value><c>true</c> if content is parsed; otherwise, <c>false</c>.</value>
public static bool TidyEditorContent
{
get { return UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent; }
}
/// <summary>
/// Gets the encoding type for the tidyied content.
/// </summary>
/// <value>The encoding type as string.</value>
public static string TidyCharEncoding
{
get { return UmbracoConfig.For.UmbracoSettings().Content.TidyCharEncoding; }
}
/// <summary>
/// Gets the property context help option, this can either be 'text', 'icon' or 'none'
/// </summary>
/// <value>The property context help option.</value>
public static string PropertyContextHelpOption
{
get { return UmbracoConfig.For.UmbracoSettings().Content.PropertyContextHelpOption; }
}
public static string DefaultBackofficeProvider
{
get { return UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider; }
}
/// <summary>
/// Whether to force safe aliases (no spaces, no special characters) at businesslogic level on contenttypes and propertytypes
/// </summary>
public static bool ForceSafeAliases
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ForceSafeAliases; }
}
/// <summary>
/// File types that will not be allowed to be uploaded via the content/media upload control
/// </summary>
public static IEnumerable<string> DisallowedUploadFiles
{
get { return UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles; }
}
/// <summary>
/// Gets the allowed image file types.
/// </summary>
/// <value>The allowed image file types.</value>
public static string ImageFileTypes
{
get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Select(x => x.ToLowerInvariant())); }
}
/// <summary>
/// Gets the allowed script file types.
/// </summary>
/// <value>The allowed script file types.</value>
public static string ScriptFileTypes
{
get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ScriptFileTypes); }
}
/// <summary>
/// Gets the duration in seconds to cache queries to umbraco library member and media methods
/// Default is 1800 seconds (30 minutes)
/// </summary>
public static int UmbracoLibraryCacheDuration
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration; }
}
/// <summary>
/// Gets the path to the scripts folder used by the script editor.
/// </summary>
/// <value>The script folder path.</value>
public static string ScriptFolderPath
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptFolderPath; }
}
/// <summary>
/// Enabled or disable the script/code editor
/// </summary>
public static bool ScriptDisableEditor
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptEditorDisable; }
}
/// <summary>
/// Gets a value indicating whether umbraco will ensure unique node naming.
/// This will ensure that nodes cannot have the same url, but will add extra characters to a url.
/// ex: existingnodename.aspx would become existingnodename(1).aspx if a node with the same name is found
/// </summary>
/// <value><c>true</c> if umbraco ensures unique node naming; otherwise, <c>false</c>.</value>
public static bool EnsureUniqueNaming
{
get { return UmbracoConfig.For.UmbracoSettings().Content.EnsureUniqueNaming; }
}
/// <summary>
/// Gets the notification email sender.
/// </summary>
/// <value>The notification email sender.</value>
public static string NotificationEmailSender
{
get { return UmbracoConfig.For.UmbracoSettings().Content.NotificationEmailAddress; }
}
/// <summary>
/// Gets a value indicating whether notification-emails are HTML.
/// </summary>
/// <value>
/// <c>true</c> if html notification-emails are disabled; otherwise, <c>false</c>.
/// </value>
public static bool NotificationDisableHtmlEmail
{
get { return UmbracoConfig.For.UmbracoSettings().Content.DisableHtmlEmail; }
}
/// <summary>
/// Gets the allowed attributes on images.
/// </summary>
/// <value>The allowed attributes on images.</value>
public static string ImageAllowedAttributes
{
get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageTagAllowedAttributes); }
}
public static XmlNode ImageAutoFillImageProperties
{
get { return GetKeyAsNode("/settings/content/imaging/autoFillImageProperties"); }
}
/// <summary>
/// Gets the scheduled tasks as XML
/// </summary>
/// <value>The scheduled tasks.</value>
public static XmlNode ScheduledTasks
{
get { return GetKeyAsNode("/settings/scheduledTasks"); }
}
/// <summary>
/// Gets a list of characters that will be replaced when generating urls
/// </summary>
/// <value>The URL replacement characters.</value>
public static XmlNode UrlReplaceCharacters
{
get { return GetKeyAsNode("/settings/requestHandler/urlReplacing"); }
}
/// <summary>
/// Whether to replace double dashes from url (ie my--story----from--dash.aspx caused by multiple url replacement chars
/// </summary>
public static bool RemoveDoubleDashesFromUrlReplacing
{
get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.RemoveDoubleDashes; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use distributed calls.
/// This enables umbraco to share cache and content across multiple servers.
/// Used for load-balancing high-traffic sites.
/// </summary>
/// <value><c>true</c> if umbraco uses distributed calls; otherwise, <c>false</c>.</value>
public static bool UseDistributedCalls
{
get { return UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled; }
}
/// <summary>
/// Gets the ID of the user with access rights to perform the distributed calls.
/// </summary>
/// <value>The distributed call user.</value>
public static int DistributedCallUser
{
get { return UmbracoConfig.For.UmbracoSettings().DistributedCall.UserId; }
}
/// <summary>
/// Gets the html injected into a (x)html page if Umbraco is running in preview mode
/// </summary>
public static string PreviewBadge
{
get { return UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge; }
}
/// <summary>
/// Gets IP or hostnames of the distribution servers.
/// These servers will receive a call everytime content is created/deleted/removed
/// and update their content cache accordingly, ensuring a consistent cache on all servers
/// </summary>
/// <value>The distribution servers.</value>
public static XmlNode DistributionServers
{
get
{
try
{
return GetKeyAsNode("/settings/distributedCall/servers");
}
catch
{
return null;
}
}
}
/// <summary>
/// Gets HelpPage configurations.
/// A help page configuration specify language, user type, application, application url and
/// the target help page url.
/// </summary>
public static XmlNode HelpPages
{
get
{
try
{
return GetKeyAsNode("/settings/help");
}
catch
{
return null;
}
}
}
/// <summary>
/// Gets all repositories registered, and returns them as XmlNodes, containing name, alias and webservice url.
/// These repositories are used by the build-in package installer and uninstaller to install new packages and check for updates.
/// All repositories should have a unique alias.
/// All packages installed from a repository gets the repository alias included in the install information
/// </summary>
/// <value>The repository servers.</value>
public static XmlNode Repositories
{
get
{
try
{
return GetKeyAsNode("/settings/repositories");
}
catch
{
return null;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco will use the viewstate mover module.
/// The viewstate mover will move all asp.net viewstate information to the bottom of the aspx page
/// to ensure that search engines will index text instead of javascript viewstate information.
/// </summary>
/// <value>
/// <c>true</c> if umbraco will use the viewstate mover module; otherwise, <c>false</c>.
/// </value>
public static bool UseViewstateMoverModule
{
get { return UmbracoConfig.For.UmbracoSettings().ViewStateMoverModule.Enable; }
}
/// <summary>
/// Tells us whether the Xml Content cache is disabled or not
/// Default is enabled
/// </summary>
public static bool isXmlContentCacheDisabled
{
get { return UmbracoConfig.For.UmbracoSettings().Content.XmlCacheEnabled == false; }
}
/// <summary>
/// Check if there's changes to the umbraco.config xml file cache on disk on each request
/// Makes it possible to updates environments by syncing the umbraco.config file across instances
/// Relates to http://umbraco.codeplex.com/workitem/30722
/// </summary>
public static bool XmlContentCheckForDiskChanges
{
get { return UmbracoConfig.For.UmbracoSettings().Content.XmlContentCheckForDiskChanges; }
}
/// <summary>
/// If this is enabled, all Umbraco objects will generate data in the preview table (cmsPreviewXml).
/// If disabled, only documents will generate data.
/// This feature is useful if anyone would like to see how data looked at a given time
/// </summary>
public static bool EnableGlobalPreviewStorage
{
get { return UmbracoConfig.For.UmbracoSettings().Content.GlobalPreviewStorageEnabled; }
}
/// <summary>
/// Whether to use the new 4.1 schema or the old legacy schema
/// </summary>
/// <value>
/// <c>true</c> if yes, use the old node/data model; otherwise, <c>false</c>.
/// </value>
public static bool UseLegacyXmlSchema
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; }
}
public static IEnumerable<string> AppCodeFileExtensionsList
{
get { return UmbracoConfig.For.UmbracoSettings().Developer.AppCodeFileExtensions.Select(x => x.Extension); }
}
[Obsolete("Use AppCodeFileExtensionsList instead")]
public static XmlNode AppCodeFileExtensions
{
get
{
XmlNode value = GetKeyAsNode("/settings/developer/appCodeFileExtensions");
if (value != null)
{
return value;
}
// default is .cs and .vb
value = _umbracoSettings.CreateElement("appCodeFileExtensions");
value.AppendChild(XmlHelper.AddTextNode(_umbracoSettings, "ext", "cs"));
value.AppendChild(XmlHelper.AddTextNode(_umbracoSettings, "ext", "vb"));
return value;
}
}
/// <summary>
/// Tells us whether the Xml to always update disk cache, when changes are made to content
/// Default is enabled
/// </summary>
public static bool continouslyUpdateXmlDiskCache
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ContinouslyUpdateXmlDiskCache; }
}
/// <summary>
/// Tells us whether to use a splash page while umbraco is initializing content.
/// If not, requests are queued while umbraco loads content. For very large sites (+10k nodes) it might be usefull to
/// have a splash page
/// Default is disabled
/// </summary>
public static bool EnableSplashWhileLoading
{
get { return UmbracoConfig.For.UmbracoSettings().Content.EnableSplashWhileLoading; }
}
public static bool ResolveUrlsFromTextString
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString; }
}
/// <summary>
/// This configuration setting defines how to handle macro errors:
/// - Inline - Show error within macro as text (default and current Umbraco 'normal' behavior)
/// - Silent - Suppress error and hide macro
/// - Throw - Throw an exception and invoke the global error handler (if one is defined, if not you'll get a YSOD)
/// </summary>
/// <value>MacroErrorBehaviour enum defining how to handle macro errors.</value>
public static MacroErrorBehaviour MacroErrorBehaviour
{
get { return UmbracoConfig.For.UmbracoSettings().Content.MacroErrorBehaviour; }
}
/// <summary>
/// This configuration setting defines how to show icons in the document type editor.
/// - ShowDuplicates - Show duplicates in files and sprites. (default and current Umbraco 'normal' behaviour)
/// - HideSpriteDuplicates - Show files on disk and hide duplicates from the sprite
/// - HideFileDuplicates - Show files in the sprite and hide duplicates on disk
/// </summary>
/// <value>MacroErrorBehaviour enum defining how to show icons in the document type editor.</value>
[Obsolete("This is no longer used and will be removed from the core in future versions")]
public static IconPickerBehaviour IconPickerBehaviour
{
get { return IconPickerBehaviour.ShowDuplicates; }
}
/// <summary>
/// Gets the default document type property used when adding new properties through the back-office
/// </summary>
/// <value>Configured text for the default document type property</value>
/// <remarks>If undefined, 'Textstring' is the default</remarks>
public static string DefaultDocumentTypeProperty
{
get { return UmbracoConfig.For.UmbracoSettings().Content.DefaultDocumentTypeProperty; }
}
private static string _path;
/// <summary>
/// Gets the settings file path
/// </summary>
internal static string SettingsFilePath
{
get { return _path ?? (_path = GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar); }
}
internal const string Filename = "umbracoSettings.config";
internal static XmlDocument EnsureSettingsDocument()
{
var settingsFile = HttpRuntime.Cache["umbracoSettingsFile"];
// Check for language file in cache
if (settingsFile == null)
{
var temp = new XmlDocument();
var settingsReader = new XmlTextReader(SettingsFilePath + Filename);
try
{
temp.Load(settingsReader);
HttpRuntime.Cache.Insert("umbracoSettingsFile", temp,
new CacheDependency(SettingsFilePath + Filename));
}
catch (XmlException e)
{
throw new XmlException("Your umbracoSettings.config file fails to pass as valid XML. Refer to the InnerException for more information", e);
}
catch (Exception e)
{
LogHelper.Error<UmbracoSettings>("Error reading umbracoSettings file: " + e.ToString(), e);
}
settingsReader.Close();
return temp;
}
else
return (XmlDocument)settingsFile;
}
internal static void Save()
{
_umbracoSettings.Save(SettingsFilePath + Filename);
}
/// <summary>
/// Selects a xml node in the umbraco settings config file.
/// </summary>
/// <param name="key">The xpath query to the specific node.</param>
/// <returns>If found, it returns the specific configuration xml node.</returns>
internal static XmlNode GetKeyAsNode(string key)
{
if (key == null)
throw new ArgumentException("Key cannot be null");
EnsureSettingsDocument();
if (_umbracoSettings == null || _umbracoSettings.DocumentElement == null)
return null;
return _umbracoSettings.DocumentElement.SelectSingleNode(key);
}
/// <summary>
/// Gets the value of configuration xml node with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
internal static string GetKey(string key)
{
EnsureSettingsDocument();
string attrName = null;
var pos = key.IndexOf('@');
if (pos > 0)
{
attrName = key.Substring(pos + 1);
key = key.Substring(0, pos - 1);
}
var node = _umbracoSettings.DocumentElement.SelectSingleNode(key);
if (node == null)
return string.Empty;
if (pos < 0)
{
if (node.FirstChild == null || node.FirstChild.Value == null)
return string.Empty;
return node.FirstChild.Value;
}
else
{
var attr = node.Attributes[attrName];
if (attr == null)
return string.Empty;
return attr.Value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Convenient wrapper for an array, an offset, and
** a count. Ideally used in streams & collections.
** Net Classes will consume an array of these.
**
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System
{
// Note: users should make sure they copy the fields out of an ArraySegment onto their stack
// then validate that the fields describe valid bounds within the array. This must be done
// because assignments to value types are not atomic, and also because one thread reading
// three fields from an ArraySegment may not see the same ArraySegment from one call to another
// (ie, users could assign a new value to the old location).
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
private T[] _array;
private int _offset;
private int _count;
public ArraySegment(T[] array)
{
if (array == null)
throw new ArgumentNullException("array");
Contract.EndContractBlock();
_array = array;
_offset = 0;
_count = array.Length;
}
public ArraySegment(T[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
_array = array;
_offset = offset;
_count = count;
}
public T[] Array
{
get
{
Contract.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _array;
}
}
public int Offset
{
get
{
// Since copying value types is not atomic & callers cannot atomically
// read all three fields, we cannot guarantee that Offset is within
// the bounds of Array. That is our intent, but let's not specify
// it as a postcondition - force callers to re-verify this themselves
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _offset;
}
}
public int Count
{
get
{
// Since copying value types is not atomic & callers cannot atomically
// read all three fields, we cannot guarantee that Count is within
// the bounds of Array. That's our intent, but let's not specify
// it as a postcondition - force callers to re-verify this themselves
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _count;
}
}
public override int GetHashCode()
{
return null == _array
? 0
: _array.GetHashCode() ^ _offset ^ _count;
}
public override bool Equals(Object obj)
{
if (obj is ArraySegment<T>)
return Equals((ArraySegment<T>)obj);
else
return false;
}
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
#region IList<T>
T IList<T>.this[int index]
{
get
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException("index");
Contract.EndContractBlock();
return _array[_offset + index];
}
set
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException("index");
Contract.EndContractBlock();
_array[_offset + index] = value;
}
}
int IList<T>.IndexOf(T item)
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Contract.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
}
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
#endregion
#region IReadOnlyList<T>
T IReadOnlyList<T>.this[int index]
{
get
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException("index");
Contract.EndContractBlock();
return _array[_offset + index];
}
}
#endregion IReadOnlyList<T>
#region ICollection<T>
bool ICollection<T>.IsReadOnly
{
get
{
// the indexer setter does not throw an exception although IsReadOnly is true.
// This is to match the behavior of arrays.
return true;
}
}
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Contract.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
}
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
System.Array.Copy(_array, _offset, array, arrayIndex, _count);
}
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region IEnumerable<T>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
return new ArraySegmentEnumerator(this);
}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
if (_array == null)
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
Contract.EndContractBlock();
return new ArraySegmentEnumerator(this);
}
#endregion
private sealed class ArraySegmentEnumerator : IEnumerator<T>
{
private T[] _array;
private int _start;
private int _end;
private int _current;
internal ArraySegmentEnumerator(ArraySegment<T> arraySegment)
{
Contract.Requires(arraySegment.Array != null);
Contract.Requires(arraySegment.Offset >= 0);
Contract.Requires(arraySegment.Count >= 0);
Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
_array = arraySegment._array;
_start = arraySegment._offset;
_end = _start + arraySegment._count;
_current = _start - 1;
}
public bool MoveNext()
{
if (_current < _end)
{
_current++;
return (_current < _end);
}
return false;
}
public T Current
{
get
{
if (_current < _start) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_current >= _end) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _array[_current];
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
void IEnumerator.Reset()
{
_current = _start - 1;
}
public void Dispose()
{
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.