context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing;
namespace Revit.SDK.Samples.NewOpenings.CS
{
/// <summary>
/// Tool used to draw arc.
/// </summary>
class ArcTool : ITool
{
private bool m_isFinished = false;
/// <summary>
/// Default constructor
/// </summary>
public ArcTool()
{
m_type = ToolType.Arc;
}
/// <summary>
/// Draw Arcs
/// </summary>
/// <param name="graphic">Graphics object</param>
public override void Draw(System.Drawing.Graphics graphic)
{
foreach (List<Point> line in m_lines)
{
int count = line.Count;
if (count == 3)
{
DrawArc(graphic, m_foreGroundPen, line[0], line[1], line[3]);
}
else if (count > 3)
{
DrawArc(graphic, m_foreGroundPen, line[0], line[1], line[2]);
for (int i = 1; i < count - 3; i += 2)
{
DrawArc(graphic, m_foreGroundPen, line[i], line[i + 2], line[i + 3]);
}
}
}
}
/// <summary>
/// Mouse down event handler
/// </summary>
/// <param name="graphic">Graphics object, used to draw geometry</param>
/// <param name="e">Mouse event argument</param>
public override void OnMouseDown(Graphics graphic, MouseEventArgs e)
{
if (MouseButtons.Left == e.Button)
{
m_points.Add(e.Location);
m_preMovePoint = e.Location;
if (m_points.Count >= 4 && m_points.Count % 2 == 0)
{
graphic.DrawLine(m_backGroundPen,
m_points[m_points.Count - 3], m_preMovePoint);
}
Draw(graphic);
if (m_isFinished)
{
m_isFinished = false;
List<Point> line = new List<Point>(m_points);
m_lines.Add(line);
m_points.Clear();
}
}
}
/// <summary>
/// Mouse move event handler
/// </summary>
/// <param name="graphic">Graphics object, used to draw geometry</param>
/// <param name="e">Mouse event argument</param>
public override void OnMouseMove(Graphics graphic, MouseEventArgs e)
{
if (2 == m_points.Count)
{
DrawArc(graphic, m_backGroundPen, m_points[0], m_points[1], m_preMovePoint);
m_preMovePoint = e.Location;
DrawArc(graphic, m_foreGroundPen, m_points[0], m_points[1], e.Location);
}
else if (m_points.Count > 2 && m_points.Count % 2 == 0)
{
DrawArc(graphic, m_backGroundPen, m_points[m_points.Count - 3],
m_points[m_points.Count - 1], m_preMovePoint);
m_preMovePoint = e.Location;
DrawArc(graphic, m_foreGroundPen, m_points[m_points.Count - 3],
m_points[m_points.Count - 1], e.Location);
}
else if (!m_isFinished && m_points.Count > 2 && m_points.Count % 2 == 1)
{
graphic.DrawLine(m_backGroundPen, m_points[m_points.Count - 2], m_preMovePoint);
m_preMovePoint = e.Location;
graphic.DrawLine(m_foreGroundPen, m_points[m_points.Count - 2], e.Location);
}
}
/// <summary>
/// Mouse right key click
/// </summary>
/// <param name="graphic">Graphics object, used to draw geometry</param>
/// <param name="e">Mouse event argument</param>
public override void OnRightMouseClick(Graphics graphic, MouseEventArgs e)
{
if (!m_isFinished && e.Button == MouseButtons.Right && m_points.Count > 0)
{
m_isFinished = true;
m_points.Add(m_points[0]);
graphic.DrawLine(m_backGroundPen, m_points[m_points.Count - 3], e.Location);
}
}
/// <summary>
/// Mouse middle key down event handler
/// </summary>
/// <param name="graphic">Graphics object, used to draw geometry</param>
/// <param name="e">Mouse event argument</param>
public override void OnMidMouseDown(Graphics graphic, MouseEventArgs e)
{
base.OnMidMouseDown(graphic, e);
if (m_isFinished)
{
m_isFinished = false;
}
}
/// <summary>
/// Calculate the arc center
/// </summary>
/// <param name="p1">Point on arc</param>
/// <param name="p2">Point on arc</param>
/// <param name="p3">Point on arc</param>
/// <returns></returns>
private PointF ComputeCenter(PointF p1, PointF p2, PointF p3)
{
float deta = 4 * (p2.X - p1.X) * (p3.Y - p1.Y) - 4 * (p2.Y - p1.Y) * (p3.X - p1.X);
if (deta == 0)
{
throw new Exception("Divided by Zero!");
}
float constD1 = p2.X * p2.X + p2.Y * p2.Y - (p1.X * p1.X + p1.Y * p1.Y);
float constD2 = p3.X * p3.X + p3.Y * p3.Y - (p1.X * p1.X + p1.Y * p1.Y);
float centerX = (constD1 * 2 * (p3.Y - p1.Y) - constD2 * 2 * (p2.Y - p1.Y)) / deta;
float centerY = (constD2 * 2 * (p2.X - p1.X) - constD1 * 2 * (p3.X - p1.X)) / deta;
return new PointF(centerX, centerY);
}
/// <summary>
/// Draw arc
/// </summary>
/// <param name="graphic">Graphics object, used to draw geometry</param>
/// <param name="pen">Used to set drawing color</param>
/// <param name="p1">Point on arc</param>
/// <param name="p2">Point on arc</param>
/// <param name="p3">Point on arc</param>
private void DrawArc(Graphics graphic, Pen pen, PointF p1, PointF p2, PointF p3)
{
try
{
PointF pCenter = ComputeCenter(p1, p2, p3);
//computer the arc rectangle
float radius = (float)Math.Sqrt((p1.X - pCenter.X) * (p1.X - pCenter.X)
+ (p1.Y - pCenter.Y) * (p1.Y - pCenter.Y));
SizeF size = new SizeF(radius, radius);
PointF upLeft = pCenter - size;
SizeF sizeRect = new SizeF(2 * radius, 2 * radius);
RectangleF rectF = new RectangleF(upLeft, sizeRect);
double startCos = (p1.X - pCenter.X) / radius;
double startSin = (p1.Y - pCenter.Y) / radius;
double endCos = (p2.X - pCenter.X) / radius;
double endSin = (p2.Y - pCenter.Y) / radius;
double midCos = (p3.X - pCenter.X) / radius;
double midSin = (p3.Y - pCenter.Y) / radius;
double startAngle = 0, endAngle = 0, midAngle = 0;
//computer the angle between [0, 360]
startAngle = GetAngle(startSin, startCos);
endAngle = GetAngle(endSin, endCos);
midAngle = GetAngle(midSin, midCos);
//get the min angle and sweep angle
double minAngle = Math.Min(startAngle, endAngle);
double maxAngle = Math.Max(startAngle, endAngle);
double sweepAngle = Math.Abs(endAngle - startAngle);
if (midAngle < minAngle || midAngle > maxAngle)
{
minAngle = maxAngle;
sweepAngle = 360 - sweepAngle;
}
graphic.DrawArc(pen, rectF, (float)minAngle, (float)sweepAngle);
}
//catch divided by zero exception
catch (Exception)
{
return;
}
}
/// <summary>
/// Get angle between [0,360]
/// </summary>
/// <param name="sin">Sin(Angle) value</param>
/// <param name="cos">Cos(Angle) value</param>
/// <returns></returns>
private double GetAngle(double sin, double cos)
{
double result = 0;
if (sin > 0)
{
result = (180 / Math.PI) * Math.Acos(cos);
}
else if (cos < 0)
{
result = 180 + (180 / Math.PI) * Math.Acos(Math.Abs(cos));
}
else if (cos > 0)
{
result = 360 - (180 / Math.PI) * Math.Acos(Math.Abs(cos));
}
return result;
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using umbraco.DataLayer;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
namespace umbraco.cms.businesslogic.template
{
/// <summary>
/// Summary description for Template.
/// </summary>
//[Obsolete("Obsolete, This class will eventually be phased out - Use Umbraco.Core.Models.Template", false)]
public class Template : CMSNode
{
#region Private members
private string _OutputContentType;
private string _design;
private string _alias;
private string _oldAlias;
private int _mastertemplate;
private bool _hasChildrenInitialized = false;
private bool _hasChildren;
#endregion
#region Static members
public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master";
private static Hashtable _templateAliases = new Hashtable();
private static volatile bool _templateAliasesInitialized = false;
private static readonly object TemplateLoaderLocker = new object();
private static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.Template);
private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray();
#endregion
[Obsolete("Use TemplateFilePath instead")]
public string MasterPageFile
{
get { return TemplateFilePath; }
}
/// <summary>
/// Returns the file path for the current template
/// </summary>
public string TemplateFilePath
{
get
{
switch (DetermineRenderingEngine(this))
{
case RenderingEngine.Mvc:
return ViewHelper.GetFilePath(this);
case RenderingEngine.WebForms:
return MasterPageHelper.GetFilePath(this);
default:
throw new ArgumentOutOfRangeException();
}
}
}
public static Hashtable TemplateAliases
{
get { return _templateAliases; }
set { _templateAliases = value; }
}
#region Constructors
public Template(int id) : base(id) { }
public Template(Guid id) : base(id) { }
#endregion
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
SaveEventArgs e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
base.Save();
FireAfterSave(e);
}
}
public string GetRawText()
{
return base.Text;
}
public override string Text
{
get
{
string tempText = base.Text;
if (!tempText.StartsWith("#"))
return tempText;
else
{
language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(tempText.Substring(1, tempText.Length - 1)))
{
Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(tempText.Substring(1, tempText.Length - 1));
if (di != null)
return di.Value(lang.id);
}
}
return "[" + tempText + "]";
}
}
set
{
FlushCache();
base.Text = value;
}
}
public string OutputContentType
{
get { return _OutputContentType; }
set { _OutputContentType = value; }
}
protected override void setupNode()
{
base.setupNode();
IRecordsReader dr = SqlHelper.ExecuteReader("Select alias,design,master from cmsTemplate where nodeId = " + this.Id);
bool hasRows = dr.Read();
if (hasRows)
{
_alias = dr.GetString("alias");
_design = dr.GetString("design");
//set the master template to zero if it's null
_mastertemplate = dr.IsNull("master") ? 0 : dr.GetInt("master");
}
dr.Close();
if (Umbraco.Core.Configuration.UmbracoSettings.DefaultRenderingEngine == RenderingEngine.Mvc && ViewHelper.ViewExists(this))
_design = ViewHelper.GetFileContents(this);
else
_design = MasterPageHelper.GetFileContents(this);
}
public new string Path
{
get
{
List<int> path = new List<int>();
Template working = this;
while (working != null)
{
path.Add(working.Id);
try
{
if (working.MasterTemplate != 0)
{
working = new Template(working.MasterTemplate);
}
else
{
working = null;
}
}
catch (ArgumentException)
{
working = null;
}
}
path.Add(-1);
path.Reverse();
string sPath = string.Join(",", path.ConvertAll(item => item.ToString()).ToArray());
return sPath;
}
set
{
base.Path = value;
}
}
public string Alias
{
get { return _alias; }
set
{
FlushCache();
_oldAlias = _alias;
_alias = value;
SqlHelper.ExecuteNonQuery("Update cmsTemplate set alias = @alias where NodeId = " + this.Id, SqlHelper.CreateParameter("@alias", _alias));
_templateAliasesInitialized = false;
InitTemplateAliases();
}
}
public bool HasMasterTemplate
{
get { return (_mastertemplate > 0); }
}
public override bool HasChildren
{
get
{
if (!_hasChildrenInitialized)
{
_hasChildren = SqlHelper.ExecuteScalar<int>("select count(NodeId) as tmp from cmsTemplate where master = " + Id) > 0;
}
return _hasChildren;
}
set
{
_hasChildrenInitialized = true;
_hasChildren = value;
}
}
public int MasterTemplate
{
get { return _mastertemplate; }
set
{
FlushCache();
_mastertemplate = value;
//set to null if it's zero
object masterVal = value;
if (value == 0) masterVal = DBNull.Value;
SqlHelper.ExecuteNonQuery("Update cmsTemplate set master = @master where NodeId = @nodeId",
SqlHelper.CreateParameter("@master", masterVal),
SqlHelper.CreateParameter("@nodeId", this.Id));
}
}
public string Design
{
get { return _design; }
set
{
FlushCache();
_design = value.Trim(NewLineChars);
//we only switch to MVC View editing if the template has a view file, and MVC editing is enabled
if (Umbraco.Core.Configuration.UmbracoSettings.DefaultRenderingEngine == RenderingEngine.Mvc && !MasterPageHelper.IsMasterPageSyntax(_design))
{
MasterPageHelper.RemoveMasterPageFile(this.Alias);
MasterPageHelper.RemoveMasterPageFile(_oldAlias);
_design = ViewHelper.UpdateViewFile(this, _oldAlias);
}
else if (UmbracoSettings.UseAspNetMasterPages)
{
ViewHelper.RemoveViewFile(this.Alias);
ViewHelper.RemoveViewFile(_oldAlias);
_design = MasterPageHelper.UpdateMasterPageFile(this, _oldAlias);
}
SqlHelper.ExecuteNonQuery("Update cmsTemplate set design = @design where NodeId = @id",
SqlHelper.CreateParameter("@design", _design),
SqlHelper.CreateParameter("@id", Id));
}
}
public XmlNode ToXml(XmlDocument doc)
{
XmlNode template = doc.CreateElement("Template");
template.AppendChild(xmlHelper.addTextNode(doc, "Name", this.Text));
template.AppendChild(xmlHelper.addTextNode(doc, "Alias", this.Alias));
if (this.MasterTemplate != 0)
{
template.AppendChild(xmlHelper.addTextNode(doc, "Master", new Template(this.MasterTemplate).Alias));
}
template.AppendChild(xmlHelper.addCDataNode(doc, "Design", this.Design));
return template;
}
/// <summary>
/// Removes any references to this templates from child templates, documenttypes and documents
/// </summary>
public void RemoveAllReferences()
{
if (HasChildren)
{
foreach (Template t in Template.GetAllAsList().FindAll(delegate(Template t) { return t.MasterTemplate == this.Id; }))
{
t.MasterTemplate = 0;
}
}
RemoveFromDocumentTypes();
// remove from documents
Document.RemoveTemplateFromDocument(this.Id);
}
public void RemoveFromDocumentTypes()
{
foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)))
{
dt.RemoveTemplate(this.Id);
dt.Save();
}
}
public IEnumerable<DocumentType> GetDocumentTypes()
{
return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id));
}
/// <summary>
/// This checks what the default rendering engine is set in config but then also ensures that there isn't already
/// a template that exists in the opposite rendering engine's template folder, then returns the appropriate
/// rendering engine to use.
/// </summary>
/// <param name="t"></param>
/// <param name="design">If a template body is specified we'll check if it contains master page markup, if it does we'll auto assume its webforms </param>
/// <returns></returns>
/// <remarks>
/// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx
/// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml
/// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page.
/// This is mostly related to installing packages since packages install file templates to the file system and then create the
/// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package.
/// </remarks>
private static RenderingEngine DetermineRenderingEngine(Template t, string design = null)
{
var engine = Umbraco.Core.Configuration.UmbracoSettings.DefaultRenderingEngine;
if (!design.IsNullOrWhiteSpace() && MasterPageHelper.IsMasterPageSyntax(design))
{
//there is a design but its definitely a webforms design
return RenderingEngine.WebForms;
}
switch (engine)
{
case RenderingEngine.Mvc:
//check if there's a view in ~/masterpages
if (MasterPageHelper.MasterPageExists(t) && !ViewHelper.ViewExists(t))
{
//change this to webforms since there's already a file there for this template alias
engine = RenderingEngine.WebForms;
}
break;
case RenderingEngine.WebForms:
//check if there's a view in ~/views
if (ViewHelper.ViewExists(t) && !MasterPageHelper.MasterPageExists(t))
{
//change this to mvc since there's already a file there for this template alias
engine = RenderingEngine.Mvc;
}
break;
}
return engine;
}
public static Template MakeNew(string Name, BusinessLogic.User u, Template master)
{
return MakeNew(Name, u, master, null);
}
private static Template MakeNew(string name, BusinessLogic.User u, string design)
{
return MakeNew(name, u, null, design);
}
public static Template MakeNew(string name, BusinessLogic.User u)
{
return MakeNew(name, u, design: null);
}
private static Template MakeNew(string name, BusinessLogic.User u, Template master, string design)
{
// CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)
CMSNode n = CMSNode.MakeNew(-1, ObjectType, u.Id, 1, name, Guid.NewGuid());
//ensure unique alias
name = helpers.Casing.SafeAlias(name);
if (GetByAlias(name) != null)
name = EnsureUniqueAlias(name, 1);
name = name.Replace("/", ".").Replace("\\", "");
if (name.Length > 100)
name = name.Substring(0, 95) + "...";
SqlHelper.ExecuteNonQuery("INSERT INTO cmsTemplate (NodeId, Alias, design, master) VALUES (@nodeId, @alias, @design, @master)",
SqlHelper.CreateParameter("@nodeId", n.Id),
SqlHelper.CreateParameter("@alias", name),
SqlHelper.CreateParameter("@design", ' '),
SqlHelper.CreateParameter("@master", DBNull.Value));
Template t = new Template(n.Id);
NewEventArgs e = new NewEventArgs();
t.OnNew(e);
if (master != null)
t.MasterTemplate = master.Id;
switch (DetermineRenderingEngine(t, design))
{
case RenderingEngine.Mvc:
ViewHelper.CreateViewFile(t, true);
break;
case RenderingEngine.WebForms:
MasterPageHelper.CreateMasterPage(t, true);
break;
}
//if a design is supplied ensure it is updated.
if (!design.IsNullOrWhiteSpace())
{
t.ImportDesign(design);
}
return t;
}
private static string EnsureUniqueAlias(string alias, int attempts)
{
if (GetByAlias(alias + attempts.ToString()) == null)
return alias + attempts.ToString();
else
{
attempts++;
return EnsureUniqueAlias(alias, attempts);
}
}
public static Template GetByAlias(string Alias)
{
return GetByAlias(Alias, false);
}
public static Template GetByAlias(string Alias, bool useCache)
{
if (!useCache)
{
try
{
return new Template(SqlHelper.ExecuteScalar<int>("select nodeId from cmsTemplate where alias = @alias", SqlHelper.CreateParameter("@alias", Alias)));
}
catch
{
return null;
}
}
//return from cache instead
var id = GetTemplateIdFromAlias(Alias);
return id == 0 ? null : GetTemplate(id);
}
[Obsolete("Obsolete, please use GetAllAsList() method instead", true)]
public static Template[] getAll()
{
return GetAllAsList().ToArray();
}
public static List<Template> GetAllAsList()
{
Guid[] ids = CMSNode.TopMostNodeIds(ObjectType);
List<Template> retVal = new List<Template>();
foreach (Guid id in ids)
{
retVal.Add(new Template(id));
}
retVal.Sort(delegate(Template t1, Template t2) { return t1.Text.CompareTo(t2.Text); });
return retVal;
}
public static int GetTemplateIdFromAlias(string alias)
{
alias = alias.ToLower();
InitTemplateAliases();
if (TemplateAliases.ContainsKey(alias))
return (int)TemplateAliases[alias];
else
return 0;
}
private static void InitTemplateAliases()
{
if (!_templateAliasesInitialized)
{
lock (TemplateLoaderLocker)
{
//double check
if (!_templateAliasesInitialized)
{
_templateAliases.Clear();
foreach (Template t in GetAllAsList())
TemplateAliases.Add(t.Alias.ToLower(), t.Id);
_templateAliasesInitialized = true;
}
}
}
}
public override void delete()
{
// don't allow template deletion if it has child templates
if (this.HasChildren)
{
var ex = new InvalidOperationException("Can't delete a master template. Remove any bindings from child templates first.");
LogHelper.Error<Template>("Can't delete a master template. Remove any bindings from child templates first.", ex);
throw ex;
}
// NH: Changed this; if you delete a template we'll remove all references instead of
// throwing an exception
if (DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)).Count() > 0)
RemoveAllReferences();
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
//re-set the template aliases
_templateAliasesInitialized = false;
InitTemplateAliases();
//delete the template
SqlHelper.ExecuteNonQuery("delete from cmsTemplate where NodeId =" + this.Id);
base.delete();
// remove masterpages
if (System.IO.File.Exists(MasterPageFile))
System.IO.File.Delete(MasterPageFile);
if (System.IO.File.Exists(Umbraco.Core.IO.IOHelper.MapPath(ViewHelper.ViewPath(this.Alias))))
System.IO.File.Delete(Umbraco.Core.IO.IOHelper.MapPath(ViewHelper.ViewPath(this.Alias)));
FireAfterDelete(e);
}
}
[Obsolete("This method, doesnt actually do anything, as the file is created when the design is set", false)]
public void _SaveAsMasterPage()
{
//SaveMasterPageFile(ConvertToMasterPageSyntax(Design));
}
public string GetMasterContentElement(int masterTemplateId)
{
if (masterTemplateId != 0)
{
string masterAlias = new Template(masterTemplateId).Alias.Replace(" ", "");
return
String.Format("<asp:Content ContentPlaceHolderID=\"{1}ContentPlaceHolder\" runat=\"server\">",
Alias.Replace(" ", ""), masterAlias);
}
else
return
String.Format("<asp:Content ContentPlaceHolderID=\"ContentPlaceHolderDefault\" runat=\"server\">",
Alias.Replace(" ", ""));
}
public List<string> contentPlaceholderIds()
{
List<string> retVal = new List<string>();
string masterPageFile = this.MasterPageFile;
string mp = System.IO.File.ReadAllText(masterPageFile);
string pat = "<asp:ContentPlaceHolder+(\\s+[a-zA-Z]+\\s*=\\s*(\"([^\"]*)\"|'([^']*)'))*\\s*/?>";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(mp);
while (m.Success)
{
CaptureCollection cc = m.Groups[3].Captures;
foreach (Capture c in cc)
{
if (c.Value != "server")
retVal.Add(c.Value);
}
m = m.NextMatch();
}
return retVal;
}
public string ConvertToMasterPageSyntax(string templateDesign)
{
string masterPageContent = GetMasterContentElement(MasterTemplate) + Environment.NewLine;
masterPageContent += templateDesign;
// Parse the design for getitems
masterPageContent = EnsureMasterPageSyntax(masterPageContent);
// append ending asp:content element
masterPageContent += Environment.NewLine
+ "</asp:Content>"
+ Environment.NewLine;
return masterPageContent;
}
public string EnsureMasterPageSyntax(string masterPageContent)
{
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", false);
// Parse the design for macros
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", false);
// Parse the design for load childs
masterPageContent = masterPageContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>", GetAspNetMasterPageContentContainer()).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", GetAspNetMasterPageContentContainer());
// Parse the design for aspnet forms
GetAspNetMasterPageForm(ref masterPageContent);
masterPageContent = masterPageContent.Replace("</?ASPNET_FORM>", "</form>");
// Parse the design for aspnet heads
masterPageContent = masterPageContent.Replace("</ASPNET_HEAD>", String.Format("<head id=\"{0}Head\" runat=\"server\">", Alias.Replace(" ", "")));
masterPageContent = masterPageContent.Replace("</?ASPNET_HEAD>", "</head>");
return masterPageContent;
}
public void ImportDesign(string design)
{
Design = design;
}
public void SaveMasterPageFile(string masterPageContent)
{
//this will trigger the helper and store everything
this.Design = masterPageContent;
}
private void GetAspNetMasterPageForm(ref string design)
{
Match formElement = Regex.Match(design, GetElementRegExp("?ASPNET_FORM", false), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
if (formElement != null && formElement.Value != "")
{
string formReplace = String.Format("<form id=\"{0}Form\" runat=\"server\">", Alias.Replace(" ", ""));
if (formElement.Groups.Count == 0)
{
formReplace += "<asp:scriptmanager runat=\"server\"></asp:scriptmanager>";
}
design = design.Replace(formElement.Value, formReplace);
}
}
private string GetAspNetMasterPageContentContainer()
{
return String.Format(
"<asp:ContentPlaceHolder ID=\"{0}ContentPlaceHolder\" runat=\"server\"></asp:ContentPlaceHolder>",
Alias.Replace(" ", ""));
}
private void ReplaceElement(ref string design, string elementName, string newElementName, bool checkForQuotes)
{
MatchCollection m =
Regex.Matches(design, GetElementRegExp(elementName, checkForQuotes),
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match match in m)
{
GroupCollection groups = match.Groups;
// generate new element (compensate for a closing trail on single elements ("/"))
string elementAttributes = groups[1].Value;
// test for macro alias
if (elementName == "?UMBRACO_MACRO")
{
Hashtable tags = helpers.xhtml.ReturnAttributes(match.Value);
if (tags["macroAlias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroAlias"].ToString()) + elementAttributes;
else if (tags["macroalias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroalias"].ToString()) + elementAttributes;
}
string newElement = "<" + newElementName + " runat=\"server\" " + elementAttributes.Trim() + ">";
if (elementAttributes.EndsWith("/"))
{
elementAttributes = elementAttributes.Substring(0, elementAttributes.Length - 1);
}
else if (groups[0].Value.StartsWith("</"))
// It's a closing element, so generate that instead of a starting element
newElement = "</" + newElementName + ">";
if (checkForQuotes)
{
// if it's inside quotes, we'll change element attribute quotes to single quotes
newElement = newElement.Replace("\"", "'");
newElement = String.Format("\"{0}\"", newElement);
}
design = design.Replace(match.Value, newElement);
}
}
private string GetElementRegExp(string elementName, bool checkForQuotes)
{
if (checkForQuotes)
return String.Format("\"<[^>\\s]*\\b{0}(\\b[^>]*)>\"", elementName);
else
return String.Format("<[^>\\s]*\\b{0}(\\b[^>]*)>", elementName);
}
[Obsolete("Umbraco automatically ensures that template cache is cleared when saving or deleting")]
protected virtual void FlushCache()
{
ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id));
}
public static Template GetTemplate(int id)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(id),
TimeSpan.FromMinutes(30),
() =>
{
try
{
return new Template(id);
}
catch
{
return null;
}
});
}
private static string GetCacheKey(int id)
{
return CacheKeys.TemplateBusinessLogicCacheKey + id;
}
public static Template Import(XmlNode n, User u)
{
string alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Alias"));
Template t = Template.GetByAlias(alias);
var design = xmlHelper.GetNodeValue(n.SelectSingleNode("Design"));
if (t == null)
{
//create the template with the design if one is specified
t = MakeNew(xmlHelper.GetNodeValue(n.SelectSingleNode("Name")), u,
design.IsNullOrWhiteSpace() ? null : design);
}
t.Alias = alias;
return t;
}
#region Events
//EVENTS
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Template sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Template sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Template sender, DeleteEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
public static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
/// <summary>
/// Occurs when [after save].
/// </summary>
public static event SaveEventHandler AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
#region Copyright (c) 2016 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace WebLinq.Mime
{
using System;
using System.Collections.Generic;
using System.IO;
using Mannex.Collections.Generic;
static class MimeMapping
{
public static string FindMimeTypeFromFileName(string fileName)
{
if (fileName == null) throw new ArgumentNullException(nameof(fileName));
if (fileName[0] == '.' && fileName.IndexOf('.', 1) < 0)
return null;
var extension = Path.GetExtension(fileName);
return extension.Length > 0 ? Map.Find(extension) : null;
}
#region MIME table
static readonly Dictionary<string, string> Map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
[".*"] = "application/octet-stream",
[".323"] = "text/h323",
[".3g2"] = "video/3gpp2",
[".3gp2"] = "video/3gpp2",
[".3gp"] = "video/3gpp",
[".3gpp"] = "video/3gpp",
[".aac"] = "audio/aac",
[".aaf"] = "application/octet-stream",
[".aca"] = "application/octet-stream",
[".accdb"] = "application/msaccess",
[".accde"] = "application/msaccess",
[".accdt"] = "application/msaccess",
[".acx"] = "application/internet-property-stream",
[".adt"] = "audio/vnd.dlna.adts",
[".adts"] = "audio/vnd.dlna.adts",
[".afm"] = "application/octet-stream",
[".ai"] = "application/postscript",
[".aif"] = "audio/x-aiff",
[".aifc"] = "audio/aiff",
[".aiff"] = "audio/aiff",
[".application"] = "application/x-ms-application",
[".art"] = "image/x-jg",
[".asd"] = "application/octet-stream",
[".asf"] = "video/x-ms-asf",
[".asi"] = "application/octet-stream",
[".asm"] = "text/plain",
[".asr"] = "video/x-ms-asf",
[".asx"] = "video/x-ms-asf",
[".atom"] = "application/atom+xml",
[".au"] = "audio/basic",
[".avi"] = "video/x-msvideo",
[".axs"] = "application/olescript",
[".bas"] = "text/plain",
[".bcpio"] = "application/x-bcpio",
[".bin"] = "application/octet-stream",
[".bmp"] = "image/bmp",
[".c"] = "text/plain",
[".cab"] = "application/vnd.ms-cab-compressed",
[".calx"] = "application/vnd.ms-office.calx",
[".cat"] = "application/vnd.ms-pki.seccat",
[".cdf"] = "application/x-cdf",
[".chm"] = "application/octet-stream",
[".class"] = "application/x-java-applet",
[".clp"] = "application/x-msclip",
[".cmx"] = "image/x-cmx",
[".cnf"] = "text/plain",
[".cod"] = "image/cis-cod",
[".coffee"] = "text/plain",
[".cpio"] = "application/x-cpio",
[".cpp"] = "text/plain",
[".crd"] = "application/x-mscardfile",
[".crl"] = "application/pkix-crl",
[".crt"] = "application/x-x509-ca-cert",
[".csh"] = "application/x-csh",
[".css"] = "text/css",
[".csv"] = "application/octet-stream",
[".cur"] = "application/octet-stream",
[".dcr"] = "application/x-director",
[".deploy"] = "application/octet-stream",
[".der"] = "application/x-x509-ca-cert",
[".dib"] = "image/bmp",
[".dir"] = "application/x-director",
[".disco"] = "text/xml",
[".dll"] = "application/x-msdownload",
[".dll.config"] = "text/xml",
[".dlm"] = "text/dlm",
[".doc"] = "application/msword",
[".docm"] = "application/vnd.ms-word.document.macroEnabled.12",
[".docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
[".dot"] = "application/msword",
[".dotm"] = "application/vnd.ms-word.template.macroEnabled.12",
[".dotx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
[".dsp"] = "application/octet-stream",
[".dtd"] = "text/xml",
[".dvi"] = "application/x-dvi",
[".dvr-ms"] = "video/x-ms-dvr",
[".dwf"] = "drawing/x-dwf",
[".dwp"] = "application/octet-stream",
[".dxr"] = "application/x-director",
[".eml"] = "message/rfc822",
[".emz"] = "application/octet-stream",
[".eot"] = "application/vnd.ms-fontobject",
[".eps"] = "application/postscript",
[".etx"] = "text/x-setext",
[".evy"] = "application/envoy",
[".exe"] = "application/octet-stream",
[".exe.config"] = "text/xml",
[".fdf"] = "application/vnd.fdf",
[".fif"] = "application/fractals",
[".fla"] = "application/octet-stream",
[".flr"] = "x-world/x-vrml",
[".flv"] = "video/x-flv",
[".gif"] = "image/gif",
[".gtar"] = "application/x-gtar",
[".gz"] = "application/x-gzip",
[".h"] = "text/plain",
[".hdf"] = "application/x-hdf",
[".hdml"] = "text/x-hdml",
[".hhc"] = "application/x-oleobject",
[".hhk"] = "application/octet-stream",
[".hhp"] = "application/octet-stream",
[".hlp"] = "application/winhlp",
[".hqx"] = "application/mac-binhex40",
[".hta"] = "application/hta",
[".htc"] = "text/x-component",
[".htm"] = "text/html",
[".html"] = "text/html",
[".htt"] = "text/webviewhtml",
[".hxt"] = "text/html",
[".ical"] = "text/calendar",
[".icalendar"] = "text/calendar",
[".ico"] = "image/x-icon",
[".ics"] = "text/calendar",
[".ief"] = "image/ief",
[".ifb"] = "text/calendar",
[".iii"] = "application/x-iphone",
[".inf"] = "application/octet-stream",
[".ins"] = "application/x-internet-signup",
[".isp"] = "application/x-internet-signup",
[".IVF"] = "video/x-ivf",
[".jar"] = "application/java-archive",
[".java"] = "application/octet-stream",
[".jck"] = "application/liquidmotion",
[".jcz"] = "application/liquidmotion",
[".jfif"] = "image/pjpeg",
[".jpb"] = "application/octet-stream",
[".jpe"] = "image/jpeg",
[".jpeg"] = "image/jpeg",
[".jpg"] = "image/jpeg",
[".js"] = "application/javascript",
[".jsx"] = "text/jscript",
[".latex"] = "application/x-latex",
[".lit"] = "application/x-ms-reader",
[".lpk"] = "application/octet-stream",
[".lsf"] = "video/x-la-asf",
[".lsx"] = "video/x-la-asf",
[".lzh"] = "application/octet-stream",
[".m13"] = "application/x-msmediaview",
[".m14"] = "application/x-msmediaview",
[".m1v"] = "video/mpeg",
[".m2ts"] = "video/vnd.dlna.mpeg-tts",
[".m3u"] = "audio/x-mpegurl",
[".m4a"] = "audio/mp4",
[".m4v"] = "video/mp4",
[".man"] = "application/x-troff-man",
[".manifest"] = "application/x-ms-manifest",
[".map"] = "text/plain",
[".mdb"] = "application/x-msaccess",
[".mdp"] = "application/octet-stream",
[".me"] = "application/x-troff-me",
[".mht"] = "message/rfc822",
[".mhtml"] = "message/rfc822",
[".mid"] = "audio/mid",
[".midi"] = "audio/mid",
[".mix"] = "application/octet-stream",
[".mmf"] = "application/x-smaf",
[".mno"] = "text/xml",
[".mny"] = "application/x-msmoney",
[".mov"] = "video/quicktime",
[".movie"] = "video/x-sgi-movie",
[".mp2"] = "video/mpeg",
[".mp3"] = "audio/mpeg",
[".mp4"] = "video/mp4",
[".mp4v"] = "video/mp4",
[".mpa"] = "video/mpeg",
[".mpe"] = "video/mpeg",
[".mpeg"] = "video/mpeg",
[".mpg"] = "video/mpeg",
[".mpp"] = "application/vnd.ms-project",
[".mpv2"] = "video/mpeg",
[".ms"] = "application/x-troff-ms",
[".msi"] = "application/octet-stream",
[".mso"] = "application/octet-stream",
[".mvb"] = "application/x-msmediaview",
[".mvc"] = "application/x-miva-compiled",
[".nc"] = "application/x-netcdf",
[".nsc"] = "video/x-ms-asf",
[".nws"] = "message/rfc822",
[".ocx"] = "application/octet-stream",
[".oda"] = "application/oda",
[".odc"] = "text/x-ms-odc",
[".ods"] = "application/oleobject",
[".oga"] = "audio/ogg",
[".ogg"] = "video/ogg",
[".ogv"] = "video/ogg",
[".ogx"] = "application/ogg",
[".one"] = "application/onenote",
[".onea"] = "application/onenote",
[".onetoc"] = "application/onenote",
[".onetoc2"] = "application/onenote",
[".onetmp"] = "application/onenote",
[".onepkg"] = "application/onenote",
[".osdx"] = "application/opensearchdescription+xml",
[".otf"] = "font/otf",
[".p10"] = "application/pkcs10",
[".p12"] = "application/x-pkcs12",
[".p7b"] = "application/x-pkcs7-certificates",
[".p7c"] = "application/pkcs7-mime",
[".p7m"] = "application/pkcs7-mime",
[".p7r"] = "application/x-pkcs7-certreqresp",
[".p7s"] = "application/pkcs7-signature",
[".pbm"] = "image/x-portable-bitmap",
[".pcx"] = "application/octet-stream",
[".pcz"] = "application/octet-stream",
[".pdf"] = "application/pdf",
[".pfb"] = "application/octet-stream",
[".pfm"] = "application/octet-stream",
[".pfx"] = "application/x-pkcs12",
[".pgm"] = "image/x-portable-graymap",
[".pko"] = "application/vnd.ms-pki.pko",
[".pma"] = "application/x-perfmon",
[".pmc"] = "application/x-perfmon",
[".pml"] = "application/x-perfmon",
[".pmr"] = "application/x-perfmon",
[".pmw"] = "application/x-perfmon",
[".png"] = "image/png",
[".pnm"] = "image/x-portable-anymap",
[".pnz"] = "image/png",
[".pot"] = "application/vnd.ms-powerpoint",
[".potm"] = "application/vnd.ms-powerpoint.template.macroEnabled.12",
[".potx"] = "application/vnd.openxmlformats-officedocument.presentationml.template",
[".ppam"] = "application/vnd.ms-powerpoint.addin.macroEnabled.12",
[".ppm"] = "image/x-portable-pixmap",
[".pps"] = "application/vnd.ms-powerpoint",
[".ppsm"] = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
[".ppsx"] = "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
[".ppt"] = "application/vnd.ms-powerpoint",
[".pptm"] = "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
[".pptx"] = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
[".prf"] = "application/pics-rules",
[".prm"] = "application/octet-stream",
[".prx"] = "application/octet-stream",
[".ps"] = "application/postscript",
[".psd"] = "application/octet-stream",
[".psm"] = "application/octet-stream",
[".psp"] = "application/octet-stream",
[".pub"] = "application/x-mspublisher",
[".qt"] = "video/quicktime",
[".qtl"] = "application/x-quicktimeplayer",
[".qxd"] = "application/octet-stream",
[".ra"] = "audio/x-pn-realaudio",
[".ram"] = "audio/x-pn-realaudio",
[".rar"] = "application/octet-stream",
[".ras"] = "image/x-cmu-raster",
[".rf"] = "image/vnd.rn-realflash",
[".rgb"] = "image/x-rgb",
[".rm"] = "application/vnd.rn-realmedia",
[".rmi"] = "audio/mid",
[".roff"] = "application/x-troff",
[".rpm"] = "audio/x-pn-realaudio-plugin",
[".rtf"] = "application/rtf",
[".rtx"] = "text/richtext",
[".scd"] = "application/x-msschedule",
[".sct"] = "text/scriptlet",
[".sea"] = "application/octet-stream",
[".setpay"] = "application/set-payment-initiation",
[".setreg"] = "application/set-registration-initiation",
[".sgml"] = "text/sgml",
[".sh"] = "application/x-sh",
[".shar"] = "application/x-shar",
[".sit"] = "application/x-stuffit",
[".sldm"] = "application/vnd.ms-powerpoint.slide.macroEnabled.12",
[".sldx"] = "application/vnd.openxmlformats-officedocument.presentationml.slide",
[".smd"] = "audio/x-smd",
[".smi"] = "application/octet-stream",
[".smx"] = "audio/x-smd",
[".smz"] = "audio/x-smd",
[".snd"] = "audio/basic",
[".snp"] = "application/octet-stream",
[".spc"] = "application/x-pkcs7-certificates",
[".spl"] = "application/futuresplash",
[".spx"] = "audio/ogg",
[".src"] = "application/x-wais-source",
[".ssm"] = "application/streamingmedia",
[".sst"] = "application/vnd.ms-pki.certstore",
[".stl"] = "application/vnd.ms-pki.stl",
[".sv4cpio"] = "application/x-sv4cpio",
[".sv4crc"] = "application/x-sv4crc",
[".svg"] = "image/svg+xml",
[".svgz"] = "image/svg+xml",
[".swf"] = "application/x-shockwave-flash",
[".t"] = "application/x-troff",
[".tar"] = "application/x-tar",
[".tcl"] = "application/x-tcl",
[".tex"] = "application/x-tex",
[".texi"] = "application/x-texinfo",
[".texinfo"] = "application/x-texinfo",
[".tgz"] = "application/x-compressed",
[".thmx"] = "application/vnd.ms-officetheme",
[".thn"] = "application/octet-stream",
[".tif"] = "image/tiff",
[".tiff"] = "image/tiff",
[".toc"] = "application/octet-stream",
[".tr"] = "application/x-troff",
[".trm"] = "application/x-msterminal",
[".ts"] = "video/vnd.dlna.mpeg-tts",
[".tsv"] = "text/tab-separated-values",
[".ttf"] = "application/octet-stream",
[".tts"] = "video/vnd.dlna.mpeg-tts",
[".txt"] = "text/plain",
[".u32"] = "application/octet-stream",
[".uls"] = "text/iuls",
[".ustar"] = "application/x-ustar",
[".vbs"] = "text/vbscript",
[".vcf"] = "text/x-vcard",
[".vcs"] = "text/plain",
[".vdx"] = "application/vnd.ms-visio.viewer",
[".vml"] = "text/xml",
[".vsd"] = "application/vnd.visio",
[".vss"] = "application/vnd.visio",
[".vst"] = "application/vnd.visio",
[".vsto"] = "application/x-ms-vsto",
[".vsw"] = "application/vnd.visio",
[".vsx"] = "application/vnd.visio",
[".vtx"] = "application/vnd.visio",
[".wav"] = "audio/wav",
[".wax"] = "audio/x-ms-wax",
[".wbmp"] = "image/vnd.wap.wbmp",
[".wcm"] = "application/vnd.ms-works",
[".wdb"] = "application/vnd.ms-works",
[".webm"] = "video/webm",
[".wks"] = "application/vnd.ms-works",
[".wm"] = "video/x-ms-wm",
[".wma"] = "audio/x-ms-wma",
[".wmd"] = "application/x-ms-wmd",
[".wmf"] = "application/x-msmetafile",
[".wml"] = "text/vnd.wap.wml",
[".wmlc"] = "application/vnd.wap.wmlc",
[".wmls"] = "text/vnd.wap.wmlscript",
[".wmlsc"] = "application/vnd.wap.wmlscriptc",
[".wmp"] = "video/x-ms-wmp",
[".wmv"] = "video/x-ms-wmv",
[".wmx"] = "video/x-ms-wmx",
[".wmz"] = "application/x-ms-wmz",
[".woff"] = "font/x-woff",
[".wps"] = "application/vnd.ms-works",
[".wri"] = "application/x-mswrite",
[".wrl"] = "x-world/x-vrml",
[".wrz"] = "x-world/x-vrml",
[".wsdl"] = "text/xml",
[".wtv"] = "video/x-ms-wtv",
[".wvx"] = "video/x-ms-wvx",
[".x"] = "application/directx",
[".xaf"] = "x-world/x-vrml",
[".xaml"] = "application/xaml+xml",
[".xap"] = "application/x-silverlight-app",
[".xbap"] = "application/x-ms-xbap",
[".xbm"] = "image/x-xbitmap",
[".xdr"] = "text/plain",
[".xht"] = "application/xhtml+xml",
[".xhtml"] = "application/xhtml+xml",
[".xla"] = "application/vnd.ms-excel",
[".xlam"] = "application/vnd.ms-excel.addin.macroEnabled.12",
[".xlc"] = "application/vnd.ms-excel",
[".xlm"] = "application/vnd.ms-excel",
[".xls"] = "application/vnd.ms-excel",
[".xlsb"] = "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
[".xlsm"] = "application/vnd.ms-excel.sheet.macroEnabled.12",
[".xlsx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
[".xlt"] = "application/vnd.ms-excel",
[".xltm"] = "application/vnd.ms-excel.template.macroEnabled.12",
[".xltx"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
[".xlw"] = "application/vnd.ms-excel",
[".xml"] = "text/xml",
[".xof"] = "x-world/x-vrml",
[".xpm"] = "image/x-xpixmap",
[".xps"] = "application/vnd.ms-xpsdocument",
[".xsd"] = "text/xml",
[".xsf"] = "text/xml",
[".xsl"] = "text/xml",
[".xslt"] = "text/xml",
[".xsn"] = "application/octet-stream",
[".xtp"] = "application/octet-stream",
[".xwd"] = "image/x-xwindowdump",
[".z"] = "application/x-compress",
[".zip"] = "application/x-zip-compressed",
};
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using KINECTmania.kinectProcessing;
using NAudio.Utils;
using NAudio.Wave;
namespace KINECTmania.GameLogic
{
/// <summary>
/// Manages the Game's state and provides Events for Notes being missed/hit
/// </summary>
class GameStateManager
{
private WaveOutEvent _waveOut;
private Thread _playThread;
public GameState State { get; private set; }
private Song CurrentSong { get; set; }
private ArrowHitPublisher Ahp { get; set; }
private List<Note> remainingNotes { get; set; }
public static long CurrentTime { get; set; }
private List<Note> toRemove = new List<Note>();
public GameStateManager()
{
State = GameState.MAIN_MENU;
CurrentSong = null;
Ahp = KinectDataInput.arrowPub;
Ahp.RaiseKinectEvent += AhpOnRaiseKinectEvent;
}
/// <summary>
/// Event handler for Kinect input
/// </summary>
/// <param name="sender"></param>
/// <param name="kinectArrowHitEventArgs">The arguments for which arrow has been hit</param>
private void AhpOnRaiseKinectEvent(object sender, KinectArrowHitEventArgs kinectArrowHitEventArgs)
{
Console.WriteLine("Checking event catched for note at " + kinectArrowHitEventArgs.Message + "; time: " + CurrentTime);
foreach (Note n in remainingNotes)
{
long startTime = n.StartTime();
if (startTime > CurrentTime - 200 && startTime < CurrentTime + 200 && n.Position().Equals(kinectArrowHitEventArgs.Message))
{
long delta = CurrentTime - startTime;
if (delta < 0)
{
delta = delta * -1;
}
if (delta < 33)
{
OnRaiseGameEvent(new GameEventArgs(n, Accuracy.MARVELOUS, 10000));
toRemove.Add(n);
return;
}
if (delta < 66)
{
OnRaiseGameEvent(new GameEventArgs(n, Accuracy.PERFECT, 6666));
toRemove.Add(n);
return;
}
if (delta < 100)
{
OnRaiseGameEvent(new GameEventArgs(n, Accuracy.GREAT, 3333));
toRemove.Add(n);
return;
}
if (delta < 133)
{
OnRaiseGameEvent(new GameEventArgs(n, Accuracy.GOOD, 500));
toRemove.Add(n);
return;
}
if (delta < 166)
{
OnRaiseGameEvent(new GameEventArgs(n, Accuracy.BAD, 0));
toRemove.Add(n);
return;
}
OnRaiseGameEvent(new GameEventArgs(n, Accuracy.BOO, 0));
toRemove.Add(n);
return;
}
}
}
/// <summary>
/// Event that triggers when a note has been missed or hit.
/// </summary>
public event GameEventHandler RaiseGameEvent;
protected virtual void OnRaiseGameEvent(GameEventArgs e)
{
RaiseGameEvent?.Invoke(this, e);
}
/// <summary>
/// Raises a dummy event of the first note being hit. For testing purposes
/// </summary>
public void RaiseDummyEvent()
{
AhpOnRaiseKinectEvent(this, new KinectArrowHitEventArgs(1));
}
/// <summary>
/// Load a Song into the GSM's memory and return it
/// </summary>
/// <param name="path">Path to the .kmsf file</param>
/// <returns>The Song parsed from the File</returns>
public Song LoadSong(String path)
{
CurrentSong = new Song(path);
if (!File.Exists(CurrentSong.SongFile))
{
String Location = CurrentSong.SongFile;
CurrentSong = null;
throw new SongFileNotFoundException("Could not find Song file. Please make sure " + Path.GetFullPath(Location) +
" exists.");
}
Console.WriteLine(Path.GetFullPath(CurrentSong.SongFile).ToString());
Mp3FileReader reader = new Mp3FileReader(Path.GetFullPath(CurrentSong.SongFile));
_waveOut = new WaveOutEvent();
_waveOut.Init(reader);
_waveOut.PlaybackStopped += WaveOutOnPlaybackStopped;
remainingNotes = new List<Note>(CurrentSong.Notes);
return CurrentSong;
}
/// <summary>
/// Handles the end of the Song being played back
/// </summary>
private void WaveOutOnPlaybackStopped(object sender, StoppedEventArgs stoppedEventArgs)
{
Console.WriteLine("Playback stopped. {0}", stoppedEventArgs.ToString());
_waveOut.Dispose();
State = GameState.SCORES;
}
/// <summary>
/// Starts the currently loaded Song
/// </summary>
public void Start()
{
if (State == GameState.IN_GAME || State == GameState.PAUSED)
{
throw new InvalidGameStateTransitionException("Please end a game before starting.");
}
if (CurrentSong == null)
{
throw new NoSongLoadedException("Please load a Song before starting!");
}
_playThread = new Thread(playSong);
_playThread.Start();
State = GameState.IN_GAME;
}
/// <summary>
/// Main loop that updates the currently elapsed time and fires the event for any missed notes
/// </summary>
private void playSong()
{
Console.WriteLine("In playSong");
_waveOut.Play();
long songStart = (long)_waveOut.GetPositionTimeSpan().TotalMilliseconds;
Console.WriteLine("Start time: " + songStart);
bool wasPaused = false;
Console.WriteLine("Remaining notes: " + remainingNotes.Count);
while (remainingNotes.Count > 0)
{
long elapsed = (long) _waveOut.GetPositionTimeSpan().TotalMilliseconds - songStart;
CurrentTime = elapsed;
if (State.Equals(GameState.PAUSED))
{
if (!wasPaused)
{
Console.WriteLine("Game paused");
wasPaused = true;
_waveOut.Pause();
}
continue;
}
if (wasPaused && State.Equals(GameState.IN_GAME))
{
Console.WriteLine("Was paused, resuming...");
_waveOut.Play();
wasPaused = false;
}
Note current;
while (remainingNotes.Any() && (current = remainingNotes.First()).StartTime() <= elapsed - 200)
{
Console.WriteLine("Missed note at " + current.Position());
OnRaiseGameEvent(new GameEventArgs(current, Accuracy.MISS, 0));
remainingNotes.Remove(current);
Console.WriteLine("Removed a note.");
if (remainingNotes.Count == 0)
{
break;
}
foreach (Note n in toRemove)
{
remainingNotes.Remove(n);
}
}
}
Console.WriteLine("After loop");
}
/// <summary>
/// Pauses the current song
/// </summary>
public void Pause()
{
switch (State)
{
case GameState.MAIN_MENU:
{
throw new InvalidGameStateTransitionException("Can not transition from main menu to paused.");
}
case GameState.PAUSED:
throw new InvalidGameStateTransitionException("Already paused");
case GameState.IN_GAME:
State = GameState.PAUSED;
break;
case GameState.LOADING_SONG:
throw new InvalidGameStateTransitionException("Can not pause while loading song.");
case GameState.OPTIONS:
throw new InvalidGameStateTransitionException("Can't pause in Options Menu.");
case GameState.SCORES:
throw new InvalidGameStateTransitionException("Can not pause on scores.");
case GameState.READY:
throw new InvalidGameStateTransitionException("Can not pause before starting.");
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Resumes a paused song
/// </summary>
public void Resume()
{
State = GameState.IN_GAME;
}
/// <summary>
/// Stops the playback of a song
/// </summary>
public void ToScores()
{
_waveOut.Stop();
}
}
/// <summary>
/// Available Game States
/// </summary>
public enum GameState
{
MAIN_MENU, PAUSED, IN_GAME, LOADING_SONG, READY, OPTIONS, SCORES
}
public class GameEventArgs : EventArgs
{
public GameEventArgs(Note n, Accuracy acc, int points)
{
Note = n;
Accuracy = acc;
Points = points;
}
public Note Note { get; private set; }
public Accuracy Accuracy { get; private set; }
public int Points { get; private set; }
}
public delegate void GameEventHandler(object sender, GameEventArgs e);
/// <summary>
/// The available Accuracys that Arrows/Notes can be hit with
/// </summary>
public enum Accuracy
{
MARVELOUS, PERFECT, GREAT, GOOD, BAD, BOO, MISS
}
// Auto-Generated Exceptions
[Serializable]
public class InvalidGameStateTransitionException : Exception
{
public InvalidGameStateTransitionException()
{
}
public InvalidGameStateTransitionException(string message) : base(message)
{
}
public InvalidGameStateTransitionException(string message, Exception innerException) : base(message, innerException)
{
}
protected InvalidGameStateTransitionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
[Serializable]
public class SongFileNotFoundException : Exception
{
public SongFileNotFoundException()
{
}
public SongFileNotFoundException(string message) : base(message)
{
}
public SongFileNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected SongFileNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
[Serializable]
public class NoSongLoadedException : Exception
{
public NoSongLoadedException()
{
}
public NoSongLoadedException(string message) : base(message)
{
}
public NoSongLoadedException(string message, Exception innerException) : base(message, innerException)
{
}
protected NoSongLoadedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
| |
// Copyright 2020 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
//
// 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 Castle.DynamicProxy;
using Google.VisualStudioFake.API.UI;
using Google.VisualStudioFake.Internal;
using Google.VisualStudioFake.Internal.ExecutionSyncPoint;
using Google.VisualStudioFake.Internal.Interop;
using Google.VisualStudioFake.Internal.Jobs;
using Google.VisualStudioFake.Internal.UI;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Threading;
using System;
using YetiCommon.CastleAspects;
namespace Google.VisualStudioFake.API
{
/// <summary>
/// Creates a VSFake object.
/// </summary>
/// <remarks>
/// Based on design found at (internal).
/// </remarks>
public class VSFakeCompRoot
{
/// <summary>
/// Defines how a VSFake is configured.
/// </summary>
public class Config
{
public VSFakeTimeoutSource Timeouts { get; set; } = new VSFakeTimeoutSource();
public string SamplesRoot { get; set; }
}
// Batch sizes Visual Studio uses in VariableInformationEnum.Next for expanding variables.
const int _watchWindowExpandBatchSize = 10;
readonly Config config;
readonly IDebugQueryTargetFactory debugQueryTargetFactory;
readonly JoinableTaskContext taskContext;
readonly NLog.ILogger logger;
JobQueue jobQueue;
IProjectAdapter projectAdapter;
ITargetAdapter targetAdapter;
ISessionDebugManager sessionDebugManager;
IDebugSession debugSession;
Decorator apiDecorator;
IDebugSessionContext debugSessionContext;
BreakpointsWindow breakpointsWindowInternal;
IBreakpointsWindow breakpointsWindow;
JobOrchestrator jobOrchestrator;
LaunchAndAttachFlow launchAndAttachFlow;
SyncPointInterceptor syncPointInterceptor;
Func<IDebugEngine2> createDebugEngine;
public VSFakeCompRoot(Config config, IDebugQueryTargetFactory debugQueryTargetFactory,
JoinableTaskContext taskContext, NLog.ILogger logger)
{
if (config.SamplesRoot == null)
{
throw new ArgumentNullException(nameof(config.SamplesRoot));
}
this.config = config;
this.debugQueryTargetFactory = debugQueryTargetFactory;
this.taskContext = taskContext;
this.logger = logger;
}
public IVSFake Create(Func<IDebugEngine2> createDebugEngine)
{
this.createDebugEngine = createDebugEngine;
var solutionExplorer = new SolutionExplorerFake();
GetProjectAdapter().ProjectLoaded += solutionExplorer.HandleProjectLoaded;
GetJobOrchestrator().DebugEvent += breakpointsWindowInternal.HandleBindResultEvent;
return GetAPIDecorator().Decorate<IVSFake>(
new VSFake(GetTargetAdapter(), GetProjectAdapter(), GetSessionDebugManager(),
solutionExplorer, GetDebugSession(), config.Timeouts));
}
public virtual IJobQueue GetJobQueue()
{
if (jobQueue == null)
{
jobQueue = new JobQueue();
}
return jobQueue;
}
public virtual ISessionDebugManager GetSessionDebugManager()
{
if (sessionDebugManager == null)
{
var jobExecutor = new JobExecutor();
sessionDebugManager = new SessionDebugManager(
jobExecutor, GetJobQueue(), GetLaunchAndAttachFlow(), GetDebugSession());
GetSyncPointInterceptor().SetSessionDebugManager(sessionDebugManager);
// Decorate after SetSessionDebugManager since the decorated sessionDebugManager
// calls the sync point interceptor, which calls sessionDebugManager, creating an
// infinite loop.
sessionDebugManager = GetAPIDecorator().Decorate(sessionDebugManager);
}
return sessionDebugManager;
}
public virtual IDebugSession GetDebugSession()
{
if (debugSession == null)
{
var variableExpanderFactory =
new VariableExpander.Factory(GetDebugSessionContext(),
_watchWindowExpandBatchSize);
var variableEntryFactory = new VariableEntry.Factory(GetJobQueue(),
GetDebugSessionContext(),
variableExpanderFactory);
variableExpanderFactory.SetVariableEntryFactory(variableEntryFactory);
var threadsWindow = new ThreadsWindow(GetDebugSessionContext(), GetJobQueue());
var callStackWindow = new CallStackWindow(GetDebugSessionContext(), GetJobQueue());
var watchWindow = new SyncWatchWindow(GetDebugSessionContext(),
variableEntryFactory);
var controlFlowView = GetAPIDecorator().Decorate<IControlFlowView>(
new ControlFlowView(GetDebugSessionContext()));
debugSession = new DebugSession(GetDebugSessionContext(), GetBreakpointsWindow(),
controlFlowView, threadsWindow, callStackWindow,
watchWindow);
}
return debugSession;
}
public virtual IProjectAdapter GetProjectAdapter()
{
if (projectAdapter == null)
{
projectAdapter = new ProjectAdapter(logger, config.SamplesRoot);
}
return projectAdapter;
}
public virtual ITargetAdapter GetTargetAdapter()
{
if (targetAdapter == null)
{
var debugQueryTarget = debugQueryTargetFactory.Create();
var debugProgramFactory = new DebugProgram.Factory();
var defaultPortFactory = new DefaultPort.Factory();
var processFactory = new Process.Factory();
var portNotifyFactory = new DebugPortNotify.Factory(
debugProgramFactory, defaultPortFactory, processFactory);
targetAdapter = new TargetAdapter(debugQueryTarget, portNotifyFactory,
defaultPortFactory, processFactory);
}
return targetAdapter;
}
public virtual Decorator GetAPIDecorator()
{
if (apiDecorator == null)
{
apiDecorator = new Decorator(new ProxyGenerator(), GetSyncPointInterceptor());
}
return apiDecorator;
}
public virtual IDebugSessionContext GetDebugSessionContext()
{
if (debugSessionContext == null)
{
debugSessionContext = new DebugSessionContext();
}
return debugSessionContext;
}
public virtual IBreakpointsWindow GetBreakpointsWindow()
{
if (breakpointsWindow == null)
{
breakpointsWindow = GetAPIDecorator()
.Decorate<IBreakpointsWindow>(GetBreakpointsWindowInternal());
}
return breakpointsWindow;
}
public virtual JobOrchestrator GetJobOrchestrator()
{
if (jobOrchestrator == null)
{
jobOrchestrator = new JobOrchestrator(GetDebugSessionContext(), GetJobQueue(),
new ProgramStoppedJob.Factory(
taskContext,
GetBreakpointsWindowInternal(),
GetJobQueue()),
new ProgramTerminatedJob.Factory(
taskContext));
}
return jobOrchestrator;
}
LaunchAndAttachFlow GetLaunchAndAttachFlow()
{
if (createDebugEngine == null)
{
throw new InvalidOperationException($"{createDebugEngine} has not been set.");
}
if (launchAndAttachFlow == null)
{
var callback = new EventCallbackFake(GetJobOrchestrator());
launchAndAttachFlow = new LaunchAndAttachFlow(
GetBreakpointsWindowInternal().BindPendingBreakpoints, createDebugEngine,
callback, GetDebugSessionContext(), GetProjectAdapter(), GetTargetAdapter(),
GetJobQueue(), taskContext, new ObserveAndNotifyJob.Factory(GetJobQueue()));
GetJobOrchestrator().DebugEvent += launchAndAttachFlow.HandleDebugProgramCreated;
}
return launchAndAttachFlow;
}
SyncPointInterceptor GetSyncPointInterceptor()
{
if (syncPointInterceptor == null)
{
syncPointInterceptor = new SyncPointInterceptor(config.Timeouts);
}
return syncPointInterceptor;
}
BreakpointsWindow GetBreakpointsWindowInternal()
{
if (breakpointsWindowInternal == null)
{
breakpointsWindowInternal =
new BreakpointsWindow(GetDebugSessionContext(), GetJobQueue(), taskContext);
}
return breakpointsWindowInternal;
}
}
}
| |
using System;
using DAQ.Environment;
using DAQ.HAL;
using DAQ.Pattern;
namespace ScanMaster.Acquire.Patterns
{
/// <summary>
/// A pattern that switches between rf systems at a given time.
/// </summary>
public class SuperPumpingPulsedRFScanPatternBuilder : PatternBuilder32
{
private const int FLASH_PULSE_LENGTH = 100;
private const int Q_PULSE_LENGTH = 100;
private const int DETECTOR_TRIGGER_LENGTH = 20;
int rfSwitchChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["rfSwitch"]).BitNumber;
int fmChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["fmSelect"]).BitNumber;
int attChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["attenuatorSelect"]).BitNumber;
int piChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["piFlip"]).BitNumber;
int scramblerChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["scramblerEnable"]).BitNumber;
int ampBlankingChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["rfAmpBlanking"]).BitNumber;
int mwEnableChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["mwEnable"]).BitNumber;
int mwSelectPumpChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["mwSelectPumpChannel"]).BitNumber;
int mwSelectTopProbeChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["mwSelectTopProbeChannel"]).BitNumber;
int mwSelectBottomProbeChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["mwSelectBottomProbeChannel"]).BitNumber;
int rfPumpSwitchChannel = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["pumprfSwitch"]).BitNumber;
public int ShotSequence( int startTime, int numberOfOnOffShots, int padShots, int flashlampPulseInterval,
int valvePulseLength, int valveToQ, int flashToQ, int delayToDetectorTrigger,
int rf1CentreTime, int rf1Length, int rf2CentreTime, int rf2Length, int piFlipTime,
int fmCentreTime, int fmLength, int attCentreTime, int attLength, int scramblerCentreTime,
int scramblerLength, int rf1BlankingCentreTime, int rf1BlankingLength,
int rf2BlankingCentreTime, int rf2BlankingLength, int pumprfCentreTime, int pumprfLength,
int pumpmwCentreTime, int pumpmwLength, int bottomProbemwCentreTime, int bottomProbemwLength,
int topProbemwCentreTime, int topProbemwLength, bool modulateOn)
{
int time = startTime;
// Disable rf
AddEdge(rfSwitchChannel, 0, false);
AddEdge(piChannel, 0, true);
for (int i = 0 ; i < numberOfOnOffShots ; i++ )
{
Shot( time, valvePulseLength, valveToQ, flashToQ, delayToDetectorTrigger,
rf1CentreTime, rf1Length, rf2CentreTime, rf2Length, piFlipTime, fmCentreTime, fmLength,
attCentreTime, attLength, scramblerCentreTime, scramblerLength, rf1BlankingCentreTime, rf1BlankingLength,
rf2BlankingCentreTime, rf2BlankingLength, pumprfCentreTime, pumprfLength, pumpmwCentreTime, pumpmwLength,
bottomProbemwCentreTime, bottomProbemwLength, topProbemwCentreTime, topProbemwLength, true);
time += flashlampPulseInterval;
// flip the "switch-scan" TTL line (if we need to)
if (modulateOn)
{
AddEdge(
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["ttlSwitch"]).BitNumber,
time,
true
);
}
for (int p = 0; p < padShots; p++)
{
FlashlampPulse(time, valveToQ, flashToQ);
time += flashlampPulseInterval;
}
if (modulateOn)
{
Shot(time, valvePulseLength, valveToQ, flashToQ, delayToDetectorTrigger,
rf1CentreTime, rf1Length, rf2CentreTime, rf2Length, piFlipTime, fmCentreTime, fmLength,
attCentreTime, attLength, scramblerCentreTime, scramblerLength, rf1BlankingCentreTime, rf1BlankingLength,
rf2BlankingCentreTime, rf2BlankingLength, pumprfCentreTime, pumprfLength, pumpmwCentreTime, pumpmwLength,
bottomProbemwCentreTime, bottomProbemwLength, topProbemwCentreTime, topProbemwLength, false);
}
else
{
Shot(time, valvePulseLength, valveToQ, flashToQ, delayToDetectorTrigger,
rf1CentreTime, rf1Length, rf2CentreTime, rf2Length, piFlipTime, fmCentreTime, fmLength,
attCentreTime, attLength, scramblerCentreTime, scramblerLength, rf1BlankingCentreTime, rf1BlankingLength,
rf2BlankingCentreTime, rf2BlankingLength, pumprfCentreTime, pumprfLength, pumpmwCentreTime, pumpmwLength,
bottomProbemwCentreTime, bottomProbemwLength, topProbemwCentreTime, topProbemwLength, true);
}
time += flashlampPulseInterval;
// flip the "switch-scan" TTL line (if we need to)
if (modulateOn)
{
AddEdge(
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["ttlSwitch"]).BitNumber,
time,
false
);
}
for (int p = 0; p < padShots; p++)
{
FlashlampPulse(time, valveToQ, flashToQ);
time += flashlampPulseInterval;
}
}
return time;
}
public int FlashlampPulse( int startTime, int valveToQ, int flashToQ )
{
return Pulse(startTime, valveToQ - flashToQ, FLASH_PULSE_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["flash"]).BitNumber);
}
public int Shot( int startTime, int valvePulseLength, int valveToQ, int flashToQ,
int delayToDetectorTrigger, int rf1CentreTime, int rf1Length, int rf2CentreTime, int rf2Length,
int piFlipTime, int fmCentreTime, int fmLength, int attCentreTime, int attLength,
int scramblerCentreTime, int scramblerLength, int rf1BlankingCentreTime , int rf1BlankingLength,
int rf2BlankingCentreTime, int rf2BlankingLength, int pumprfCentreTime, int pumprfLength,
int pumpmwCentreTime, int pumpmwLength, int bottomProbemwCentreTime, int bottomProbemwLength,
int topProbemwCentreTime, int topProbemwLength, bool modulated)
{
int time = 0;
int tempTime = 0;
// piFlip off
AddEdge(piChannel, startTime, false);
// valve pulse
tempTime = Pulse(startTime, 0, valvePulseLength,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["valve"]).BitNumber);
if (tempTime > time) time = tempTime;
// Flash pulse
tempTime = Pulse(startTime, valveToQ - flashToQ, FLASH_PULSE_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["flash"]).BitNumber);
if (tempTime > time) time = tempTime;
// Q pulse
tempTime = Pulse(startTime, valveToQ, Q_PULSE_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["q"]).BitNumber);
if (tempTime > time) time = tempTime;
// pulse pump rf
if (pumprfLength != 0)
{
tempTime = Pulse(startTime, valveToQ + pumprfCentreTime - (pumprfLength / 2), pumprfLength, rfPumpSwitchChannel);
if (tempTime > time) time = tempTime;
}
// enable microwaves for pumping
if (pumpmwLength != 0)
{
tempTime = Pulse(startTime, valveToQ + pumpmwCentreTime - (pumpmwLength / 2), pumpmwLength, mwEnableChannel);
if (tempTime > time) time = tempTime;
}
// throw microwave switch to pump region
if (pumpmwLength != 0)
{
tempTime = Pulse(startTime, valveToQ + pumpmwCentreTime - (pumpmwLength / 2), pumpmwLength, mwSelectPumpChannel);
if (tempTime > time) time = tempTime;
}
// pulse rf amp blanking for rf1
if (rf1BlankingLength != 0)
{
tempTime = Pulse(startTime, valveToQ + rf1BlankingCentreTime - (rf1BlankingLength / 2), rf1BlankingLength, ampBlankingChannel);
if (tempTime > time) time = tempTime;
}
// pulse rf1
if (rf1Length != 0)
{
tempTime = Pulse(startTime, valveToQ + rf1CentreTime - (rf1Length/2), rf1Length, rfSwitchChannel);
if (tempTime > time) time = tempTime;
}
// pulse rf amp blanking for rf2
if (rf2BlankingLength != 0)
{
tempTime = Pulse(startTime, valveToQ + rf2BlankingCentreTime - (rf2BlankingLength / 2), rf2BlankingLength, ampBlankingChannel);
if (tempTime > time) time = tempTime;
}
// pulse rf2
if (rf2Length != 0)
{
tempTime = Pulse(startTime, valveToQ + rf2CentreTime - (rf2Length/2), rf2Length, rfSwitchChannel);
if (tempTime > time) time = tempTime;
}
// pulse fm
tempTime = Pulse(startTime, valveToQ + fmCentreTime - (fmLength/2), fmLength, fmChannel);
if (tempTime > time) time = tempTime;
// pulse attenuators
tempTime = Pulse(startTime, valveToQ + attCentreTime - (attLength / 2), attLength, attChannel);
if (tempTime > time) time = tempTime;
// pulse scrambler
tempTime = Pulse(startTime, valveToQ + scramblerCentreTime - (scramblerLength / 2),
scramblerLength, scramblerChannel);
if (tempTime > time) time = tempTime;
// piFlip on
AddEdge(piChannel, startTime + valveToQ + piFlipTime, true);
// enable microwaves for bottom probe region
if (bottomProbemwLength != 0)
{
tempTime = Pulse(startTime, valveToQ + bottomProbemwCentreTime - (bottomProbemwLength / 2), bottomProbemwLength, mwEnableChannel);
if (tempTime > time) time = tempTime;
}
// throw microwave switch to bottom probe region
if (bottomProbemwLength != 0)
{
tempTime = Pulse(startTime, valveToQ + bottomProbemwCentreTime - (bottomProbemwLength / 2), bottomProbemwLength, mwSelectBottomProbeChannel);
if (tempTime > time) time = tempTime;
}
// enable microwaves for top probe region
if (topProbemwLength != 0)
{
tempTime = Pulse(startTime, valveToQ + topProbemwCentreTime - (topProbemwLength / 2), topProbemwLength, mwEnableChannel);
if (tempTime > time) time = tempTime;
}
// throw microwave switch to top region
if (topProbemwLength != 0)
{
tempTime = Pulse(startTime, valveToQ + topProbemwCentreTime - (topProbemwLength / 2), topProbemwLength, mwSelectTopProbeChannel);
if (tempTime > time) time = tempTime;
}
// Detector trigger
if (modulated)
{
tempTime = Pulse(startTime, delayToDetectorTrigger + valveToQ, DETECTOR_TRIGGER_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["detector"]).BitNumber);
if (tempTime > time) time = tempTime;
}
else
{
tempTime = Pulse(startTime, delayToDetectorTrigger + valveToQ, DETECTOR_TRIGGER_LENGTH,
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["detectorprime"]).BitNumber);
if (tempTime > time) time = tempTime;
}
return time;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Builders;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using PartsUnlimited.Models;
namespace PartsUnlimited.Models.Migrations
{
[ContextType(typeof(PartsUnlimitedContext))]
partial class PartsUnlimitedContextModelSnapshot : ModelSnapshot
{
public override IModel Model
{
get
{
var builder = new BasicModelBuilder()
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("PartsUnlimited.Models.ApplicationUser", b =>
{
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 2);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 3);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 10);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 11);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 12);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 13);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 14);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 15);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("PartsUnlimited.Models.CartItem", b =>
{
b.Property<string>("CartId")
.Annotation("OriginalValueIndex", 0);
b.Property<int>("CartItemId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<int>("Count")
.Annotation("OriginalValueIndex", 2);
b.Property<DateTime>("DateCreated")
.Annotation("OriginalValueIndex", 3);
b.Property<int>("ProductId")
.Annotation("OriginalValueIndex", 4);
b.Key("CartItemId");
});
builder.Entity("PartsUnlimited.Models.Category", b =>
{
b.Property<int>("CategoryId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("Description")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ImageUrl")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 3);
b.Key("CategoryId");
});
builder.Entity("PartsUnlimited.Models.Order", b =>
{
b.Property<string>("Address")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("City")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Country")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 4);
b.Property<DateTime>("OrderDate")
.Annotation("OriginalValueIndex", 5);
b.Property<int>("OrderId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 6)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("Phone")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("PostalCode")
.Annotation("OriginalValueIndex", 8);
b.Property<bool>("Processed")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("State")
.Annotation("OriginalValueIndex", 10);
b.Property<decimal>("Total")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("Username")
.Annotation("OriginalValueIndex", 12);
b.Key("OrderId");
});
builder.Entity("PartsUnlimited.Models.OrderDetail", b =>
{
b.Property<int>("OrderDetailId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<int>("OrderId")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("ProductId")
.Annotation("OriginalValueIndex", 2);
b.Property<int>("Quantity")
.Annotation("OriginalValueIndex", 3);
b.Property<decimal>("UnitPrice")
.Annotation("OriginalValueIndex", 4);
b.Key("OrderDetailId");
});
builder.Entity("PartsUnlimited.Models.Product", b =>
{
b.Property<int>("CategoryId")
.Annotation("OriginalValueIndex", 0);
b.Property<DateTime>("Created")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Description")
.Annotation("OriginalValueIndex", 2);
b.Property<int>("Inventory")
.Annotation("OriginalValueIndex", 3);
b.Property<int>("LeadTime")
.Annotation("OriginalValueIndex", 4);
b.Property<decimal>("Price")
.Annotation("OriginalValueIndex", 5);
b.Property<string>("ProductArtUrl")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("ProductDetails")
.Annotation("OriginalValueIndex", 7);
b.Property<int>("ProductId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 8)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<int>("RecommendationId")
.Annotation("OriginalValueIndex", 9);
b.Property<decimal>("SalePrice")
.Annotation("OriginalValueIndex", 10);
b.Property<string>("SkuNumber")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("Title")
.Annotation("OriginalValueIndex", 12);
b.Key("ProductId");
});
builder.Entity("PartsUnlimited.Models.Raincheck", b =>
{
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 0);
b.Property<int>("ProductId")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Quantity")
.Annotation("OriginalValueIndex", 2);
b.Property<int>("RaincheckId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 3)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<double>("SalePrice")
.Annotation("OriginalValueIndex", 4);
b.Property<int>("StoreId")
.Annotation("OriginalValueIndex", 5);
b.Key("RaincheckId");
});
builder.Entity("PartsUnlimited.Models.Store", b =>
{
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 0);
b.Property<int>("StoreId")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Key("StoreId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.ForeignKey("PartsUnlimited.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.ForeignKey("PartsUnlimited.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
b.ForeignKey("PartsUnlimited.Models.ApplicationUser", "UserId");
});
builder.Entity("PartsUnlimited.Models.CartItem", b =>
{
b.ForeignKey("PartsUnlimited.Models.Product", "ProductId");
});
builder.Entity("PartsUnlimited.Models.OrderDetail", b =>
{
b.ForeignKey("PartsUnlimited.Models.Order", "OrderId");
b.ForeignKey("PartsUnlimited.Models.Product", "ProductId");
});
builder.Entity("PartsUnlimited.Models.Product", b =>
{
b.ForeignKey("PartsUnlimited.Models.Category", "CategoryId");
});
builder.Entity("PartsUnlimited.Models.Raincheck", b =>
{
b.ForeignKey("PartsUnlimited.Models.Product", "ProductId");
b.ForeignKey("PartsUnlimited.Models.Store", "StoreId");
});
return builder.Model;
}
}
}
}
| |
#region PDFsharp Charting - A .NET charting library based on PDFsharp
//
// Authors:
// Niklas Schneider (mailto:[email protected])
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using PdfSharp.Drawing;
namespace PdfSharp.Charting.Renderers
{
/// <summary>
/// Represents an axis renderer used for charts of type Bar2D.
/// </summary>
internal class VerticalXAxisRenderer : XAxisRenderer
{
/// <summary>
/// Initializes a new instance of the VerticalXAxisRenderer class with the specified renderer parameters.
/// </summary>
internal VerticalXAxisRenderer(RendererParameters parms) : base(parms)
{
}
/// <summary>
/// Returns an initialized rendererInfo based on the X axis.
/// </summary>
internal override RendererInfo Init()
{
Chart chart = (Chart)this.rendererParms.DrawingItem;
AxisRendererInfo xari = new AxisRendererInfo();
xari.axis = chart.xAxis;
if (xari.axis != null)
{
ChartRendererInfo cri = (ChartRendererInfo)this.rendererParms.RendererInfo;
CalculateXAxisValues(xari);
InitXValues(xari);
InitAxisTitle(xari, cri.DefaultFont);
InitTickLabels(xari, cri.DefaultFont);
InitAxisLineFormat(xari);
InitGridlines(xari);
}
return xari;
}
/// <summary>
/// Calculates the space used for the X axis.
/// </summary>
internal override void Format()
{
AxisRendererInfo xari = ((ChartRendererInfo)this.rendererParms.RendererInfo).xAxisRendererInfo;
if (xari.axis != null)
{
AxisTitleRendererInfo atri = xari.axisTitleRendererInfo;
// Calculate space used for axis title.
XSize titleSize = new XSize(0, 0);
if (atri != null && atri.AxisTitleText != null && atri.AxisTitleText.Length > 0)
titleSize = this.rendererParms.Graphics.MeasureString(atri.AxisTitleText, atri.AxisTitleFont);
// Calculate space used for tick labels.
XSize size = new XSize(0, 0);
foreach (XSeries xs in xari.XValues)
{
foreach (XValue xv in xs)
{
XSize valueSize = this.rendererParms.Graphics.MeasureString(xv.Value, xari.TickLabelsFont);
size.Height += valueSize.Height;
size.Width = Math.Max(valueSize.Width, size.Width);
}
}
// Remember space for later drawing.
if (atri != null)
atri.AxisTitleSize = titleSize;
xari.TickLabelsHeight = size.Height;
xari.Height = size.Height;
xari.Width = titleSize.Width + size.Width + xari.MajorTickMarkWidth;
}
}
/// <summary>
/// Draws the horizontal X axis.
/// </summary>
internal override void Draw()
{
XGraphics gfx = this.rendererParms.Graphics;
ChartRendererInfo cri = (ChartRendererInfo)this.rendererParms.RendererInfo;
AxisRendererInfo xari = cri.xAxisRendererInfo;
double xMin = xari.MinimumScale;
double xMax = xari.MaximumScale;
double xMajorTick = xari.MajorTick;
double xMinorTick = xari.MinorTick;
double xMaxExtension = xari.MajorTick;
// Draw tick labels. Each tick label will be aligned centered.
int countTickLabels = (int)xMax;
double tickLabelStep = xari.Height / countTickLabels;
XPoint startPos = new XPoint(xari.X + xari.Width - xari.MajorTickMarkWidth, xari.Y + tickLabelStep / 2);
foreach (XSeries xs in xari.XValues)
{
for (int idx = countTickLabels - 1; idx >= 0; --idx)
{
XValue xv = xs[idx];
string tickLabel = xv.Value;
XSize size = gfx.MeasureString(tickLabel, xari.TickLabelsFont);
gfx.DrawString(tickLabel, xari.TickLabelsFont, xari.TickLabelsBrush, startPos.X - size.Width, startPos.Y + size.Height / 2);
startPos.Y += tickLabelStep;
}
}
// Draw axis.
// First draw tick marks, second draw axis.
double majorTickMarkStart = 0, majorTickMarkEnd = 0,
minorTickMarkStart = 0, minorTickMarkEnd = 0;
GetTickMarkPos(xari, ref majorTickMarkStart, ref majorTickMarkEnd, ref minorTickMarkStart, ref minorTickMarkEnd);
LineFormatRenderer lineFormatRenderer = new LineFormatRenderer(gfx, xari.LineFormat);
XPoint[] points = new XPoint[2];
// Minor ticks.
if (xari.MinorTickMark != TickMarkType.None)
{
int countMinorTickMarks = (int)(xMax / xMinorTick);
double minorTickMarkStep = xari.Height / countMinorTickMarks;
startPos.Y = xari.Y;
for (int x = 0; x <= countMinorTickMarks; x++)
{
points[0].X = minorTickMarkStart;
points[0].Y = startPos.Y + minorTickMarkStep * x;
points[1].X = minorTickMarkEnd;
points[1].Y = points[0].Y;
lineFormatRenderer.DrawLine(points[0], points[1]);
}
}
// Major ticks.
if (xari.MajorTickMark != TickMarkType.None)
{
int countMajorTickMarks = (int)(xMax / xMajorTick);
double majorTickMarkStep = xari.Height / countMajorTickMarks;
startPos.Y = xari.Y;
for (int x = 0; x <= countMajorTickMarks; x++)
{
points[0].X = majorTickMarkStart;
points[0].Y = startPos.Y + majorTickMarkStep * x;
points[1].X = majorTickMarkEnd;
points[1].Y = points[0].Y;
lineFormatRenderer.DrawLine(points[0], points[1]);
}
}
// Axis.
if (xari.LineFormat != null)
{
points[0].X = xari.X + xari.Width;
points[0].Y = xari.Y;
points[1].X = xari.X + xari.Width;
points[1].Y = xari.Y + xari.Height;
if (xari.MajorTickMark != TickMarkType.None)
{
points[0].Y -= xari.LineFormat.Width / 2;
points[1].Y += xari.LineFormat.Width / 2;
}
lineFormatRenderer.DrawLine(points[0], points[1]);
}
// Draw axis title.
AxisTitleRendererInfo atri = xari.axisTitleRendererInfo;
if (atri != null && atri.AxisTitleText != null && atri.AxisTitleText.Length > 0)
{
XRect rect = new XRect(xari.X, xari.Y + xari.Height / 2, atri.AxisTitleSize.Width, 0);
gfx.DrawString(atri.AxisTitleText, atri.AxisTitleFont, atri.AxisTitleBrush, rect);
}
}
/// <summary>
/// Calculates the X axis describing values like minimum/maximum scale, major/minor tick and
/// major/minor tick mark width.
/// </summary>
private void CalculateXAxisValues(AxisRendererInfo rendererInfo)
{
// Calculates the maximum number of data points over all series.
SeriesCollection seriesCollection = ((Chart)rendererInfo.axis.parent).seriesCollection;
int count = 0;
foreach (Series series in seriesCollection)
count = Math.Max(count, series.Count);
rendererInfo.MinimumScale = 0;
rendererInfo.MaximumScale = count; // At least 0
rendererInfo.MajorTick = 1;
rendererInfo.MinorTick = 0.5;
rendererInfo.MajorTickMarkWidth = DefaultMajorTickMarkWidth;
rendererInfo.MinorTickMarkWidth = DefaultMinorTickMarkWidth;
}
/// <summary>
/// Initializes the rendererInfo's xvalues. If not set by the user xvalues will be simply numbers
/// from minimum scale + 1 to maximum scale.
/// </summary>
private void InitXValues(AxisRendererInfo rendererInfo)
{
rendererInfo.XValues = ((Chart)rendererInfo.axis.parent).xValues;
if (rendererInfo.XValues == null)
{
rendererInfo.XValues = new XValues();
XSeries xs = rendererInfo.XValues.AddXSeries();
for (double i = rendererInfo.MinimumScale + 1; i <= rendererInfo.MaximumScale; ++i)
xs.Add(i.ToString());
}
}
/// <summary>
/// Calculates the starting and ending y position for the minor and major tick marks.
/// </summary>
private void GetTickMarkPos(AxisRendererInfo rendererInfo,
ref double majorTickMarkStart, ref double majorTickMarkEnd,
ref double minorTickMarkStart, ref double minorTickMarkEnd)
{
double majorTickMarkWidth = rendererInfo.MajorTickMarkWidth;
double minorTickMarkWidth = rendererInfo.MinorTickMarkWidth;
double x = rendererInfo.Rect.X + rendererInfo.Rect.Width;
switch (rendererInfo.MajorTickMark)
{
case TickMarkType.Inside:
majorTickMarkStart = x;
majorTickMarkEnd = x + majorTickMarkWidth;
break;
case TickMarkType.Outside:
majorTickMarkStart = x - majorTickMarkWidth;
majorTickMarkEnd = x;
break;
case TickMarkType.Cross:
majorTickMarkStart = x - majorTickMarkWidth;
majorTickMarkEnd = x + majorTickMarkWidth;
break;
case TickMarkType.None:
majorTickMarkStart = 0;
majorTickMarkEnd = 0;
break;
}
switch (rendererInfo.MinorTickMark)
{
case TickMarkType.Inside:
minorTickMarkStart = x;
minorTickMarkEnd = x + minorTickMarkWidth;
break;
case TickMarkType.Outside:
minorTickMarkStart = x - minorTickMarkWidth;
minorTickMarkEnd = x;
break;
case TickMarkType.Cross:
minorTickMarkStart = x - minorTickMarkWidth;
minorTickMarkEnd = x + minorTickMarkWidth;
break;
case TickMarkType.None:
minorTickMarkStart = 0;
minorTickMarkEnd = 0;
break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace CallbackReceiver.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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.ServiceModel.Channels;
using Microsoft.Xml;
namespace System.ServiceModel.Security
{
public class ScopedMessagePartSpecification
{
private MessagePartSpecification _channelParts;
private Dictionary<string, MessagePartSpecification> _actionParts;
private Dictionary<string, MessagePartSpecification> _readOnlyNormalizedActionParts;
private bool _isReadOnly;
public ScopedMessagePartSpecification()
{
_channelParts = new MessagePartSpecification();
_actionParts = new Dictionary<string, MessagePartSpecification>();
}
public ICollection<string> Actions
{
get
{
return _actionParts.Keys;
}
}
public MessagePartSpecification ChannelParts
{
get
{
return _channelParts;
}
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
public ScopedMessagePartSpecification(ScopedMessagePartSpecification other)
: this()
{
if (other == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));
_channelParts.Union(other._channelParts);
if (other._actionParts != null)
{
foreach (string action in other._actionParts.Keys)
{
MessagePartSpecification p = new MessagePartSpecification();
p.Union(other._actionParts[action]);
_actionParts[action] = p;
}
}
}
internal ScopedMessagePartSpecification(ScopedMessagePartSpecification other, bool newIncludeBody)
: this(other)
{
_channelParts.IsBodyIncluded = newIncludeBody;
foreach (string action in _actionParts.Keys)
_actionParts[action].IsBodyIncluded = newIncludeBody;
}
public void AddParts(MessagePartSpecification parts)
{
if (parts == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));
ThrowIfReadOnly();
_channelParts.Union(parts);
}
public void AddParts(MessagePartSpecification parts, string action)
{
if (action == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
if (parts == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("parts"));
ThrowIfReadOnly();
if (!_actionParts.ContainsKey(action))
_actionParts[action] = new MessagePartSpecification();
_actionParts[action].Union(parts);
}
internal void AddParts(MessagePartSpecification parts, XmlDictionaryString action)
{
if (action == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("action"));
AddParts(parts, action.Value);
}
internal bool IsEmpty()
{
bool result;
if (!_channelParts.IsEmpty())
{
result = false;
}
else
{
result = true;
foreach (string action in this.Actions)
{
MessagePartSpecification parts;
if (TryGetParts(action, true, out parts))
{
if (!parts.IsEmpty())
{
result = false;
break;
}
}
}
}
return result;
}
public bool TryGetParts(string action, bool excludeChannelScope, out MessagePartSpecification parts)
{
if (action == null)
action = MessageHeaders.WildcardAction;
parts = null;
if (_isReadOnly)
{
if (_readOnlyNormalizedActionParts.ContainsKey(action))
if (excludeChannelScope)
parts = _actionParts[action];
else
parts = _readOnlyNormalizedActionParts[action];
}
else if (_actionParts.ContainsKey(action))
{
MessagePartSpecification p = new MessagePartSpecification();
p.Union(_actionParts[action]);
if (!excludeChannelScope)
p.Union(_channelParts);
parts = p;
}
return parts != null;
}
internal void CopyTo(ScopedMessagePartSpecification target)
{
if (target == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("target");
}
target.ChannelParts.IsBodyIncluded = this.ChannelParts.IsBodyIncluded;
foreach (XmlQualifiedName headerType in ChannelParts.HeaderTypes)
{
if (!target._channelParts.IsHeaderIncluded(headerType.Name, headerType.Namespace))
{
target.ChannelParts.HeaderTypes.Add(headerType);
}
}
foreach (string action in _actionParts.Keys)
{
target.AddParts(_actionParts[action], action);
}
}
public bool TryGetParts(string action, out MessagePartSpecification parts)
{
return this.TryGetParts(action, false, out parts);
}
public void MakeReadOnly()
{
if (!_isReadOnly)
{
_readOnlyNormalizedActionParts = new Dictionary<string, MessagePartSpecification>();
foreach (string action in _actionParts.Keys)
{
MessagePartSpecification p = new MessagePartSpecification();
p.Union(_actionParts[action]);
p.Union(_channelParts);
p.MakeReadOnly();
_readOnlyNormalizedActionParts[action] = p;
}
_isReadOnly = true;
}
}
private void ThrowIfReadOnly()
{
if (_isReadOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ObjectIsReadOnly));
}
}
}
| |
//
// FormArea.cs
//
// Author:
// Tobias Schulz <[email protected]>
//
// Copyright (c) 2015 Tobias Schulz
//
// 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.Windows.Forms;
using System.Drawing;
using HandWriting;
using System.Collections.Generic;
namespace DesktopKeyboard
{
public sealed class GeoForms
{
readonly GeoFormCollection forms;
readonly CharacterCollection characters;
public IEnumerable<GeoForm> Forms { get { return forms; } }
public uint ChangeCounter { get; set; }
public Size Size { get; set; }
public GeoForms(Size size)
{
Size = size;
forms = new GeoFormCollection {
/*
new RectangleForm(name: "top border", x: new Range(min: 0.21, max: 0.79), y: new Range(min: 0.0, max: 0.20)),
new RectangleForm(name: "bottom border", x: new Range(min: 0.21, max: 0.79), y: new Range(min: 0.80, max: 1.0)),
new RectangleForm(name: "left border", x: new Range(min: 0.0, max: 0.20), y: new Range(min: 0.21, max: 0.79)),
new RectangleForm(name: "right border", x: new Range(min: 0.80, max: 1.0), y: new Range(min: 0.21, max: 0.79)),
new RectangleForm(name: "top left corner", x: new Range(min: 0.0, max: 0.20), y: new Range(min: 0.0, max: 0.20)),
new RectangleForm(name: "top right corner", x: new Range(min: 0.80, max: 1.0), y: new Range(min: 0.0, max: 0.20)),
new RectangleForm(name: "bottom left corner", x: new Range(min: 0.0, max: 0.20), y: new Range(min: 0.80, max: 1.0)),
new RectangleForm(name: "bottom right corner", x: new Range(min: 0.80, max: 1.0), y: new Range(min: 0.80, max: 1.0)),
new RectangleForm(name: "top left distanced corner", x: new Range(min: 0.22, max: 0.41), y: new Range(min: 0.22, max: 0.41)),
new RectangleForm(name: "top right distanced corner", x: new Range(min: 0.59, max: 0.78), y: new Range(min: 0.22, max: 0.41)),
new RectangleForm(name: "bottom left distanced corner", x: new Range(min: 0.22, max: 0.41), y: new Range(min: 0.59, max: 0.78)),
new RectangleForm(name: "bottom right distanced corner", x: new Range(min: 0.59, max: 0.78), y: new Range(min: 0.59, max: 0.78)),
new RectangleForm(name: "left to right bar 1/3", x: new Range(min: 0.0, max: 0.3), y: new Range(min: 0.42, max: 0.58)),
new RectangleForm(name: "left to right bar 2/3", x: new Range(min: 0.3, max: 0.7), y: new Range(min: 0.42, max: 0.58)),
new RectangleForm(name: "left to right bar 3/3", x: new Range(min: 0.7, max: 1.0), y: new Range(min: 0.42, max: 0.58)),
new RectangleForm(name: "top to bottom bar 1/3", x: new Range(min: 0.42, max: 0.58), y: new Range(min: 0.0, max: 0.3)),
new RectangleForm(name: "top to bottom bar 2/3", x: new Range(min: 0.42, max: 0.58), y: new Range(min: 0.3, max: 0.7)),
new RectangleForm(name: "top to bottom bar 3/3", x: new Range(min: 0.42, max: 0.58), y: new Range(min: 0.7, max: 1.0)),
*/
};
for (int a = 1; a <= 5; a++) {
for (int b = 1; b <= 5; b++) {
forms.Add(new RectangleForm(
name: "grid5 " + a + " " + b,
x: new Range(min: (a - 1) * 0.20, max: (a) * 0.20),
y: new Range(min: (b - 1) * 0.20, max: (b) * 0.20)
));
}
}
for (int a = 1; a <= 4; a++) {
for (int b = 1; b <= 4; b++) {
forms.Add(new RectangleForm(
name: "grid4 " + a + " " + b,
x: new Range(min: 0.10 + (a - 1) * 0.20, max: 0.10 + (a) * 0.20),
y: new Range(min: 0.10 + (b - 1) * 0.20, max: 0.10 + (b) * 0.20)
));
}
}
characters = new CharacterCollection(forms) {
new Character('A') { },
new Character('B') { },
new Character('C') { },
new Character('D') { },
new Character('E') { {
"grid5 1 1",
"grid5 2 1",
"grid5 3 1",
"grid5 4 1",
"grid5 5 1",
"grid5 1 2",
"grid5 1 3",
"grid5 2 3",
"grid5 3 3",
"grid5 4 3",
"grid5 5 3",
"grid5 1 4",
"grid5 1 5",
"grid5 2 5",
"grid5 3 5",
"grid5 4 5",
"grid5 5 5"
}
},
new Character('F') { {
"grid5 1 1",
"grid5 2 1",
"grid5 3 1",
"grid5 4 1",
"grid5 5 1",
"grid5 1 2",
"grid5 1 3",
"grid5 2 3",
"grid5 3 3",
"grid5 4 3",
"grid5 5 3",
"grid5 1 4",
"grid5 1 5"
}
},
new Character('G') { },
new Character('H') { },
new Character('I') { },
new Character('J') { },
new Character('K') { },
new Character('L') { },
new Character('M') { },
new Character('N') { },
new Character('O') { },
new Character('P') { },
new Character('Q') { },
new Character('R') { },
new Character('S') { },
new Character('T') { },
new Character('U') { },
new Character('V') { },
new Character('W') { },
new Character('X') { },
new Character('Y') { },
new Character('Z') { },
};
}
public int Count {
get {
int activated = 0;
foreach (GeoForm form in forms) {
if (form.IsActivated) {
activated++;
}
}
return activated;
}
}
public void Draw(Graphics g)
{
for (int layer = 0; layer < 100; layer++) {
foreach (GeoForm form in forms) {
form.Draw(g: g, size: Size, layer: layer);
}
}
}
public void AddPoint(Pixel pixel)
{
foreach (GeoForm form in forms) {
if (form.Contains(pixel: pixel, size: Size)) {
form.IsActivated = true;
}
}
}
public void GetResult(bool success, out string result)
{
result = null;
}
}
public abstract class GeoForm
{
public string Name { get; protected set; }
public bool IsActivated { get; set; }
public static readonly Brush DefaultBrush = new SolidBrush(Color.FromArgb(15, 0, 0, 0));
public static readonly Brush ActivatedBrush = new SolidBrush(Color.FromArgb(15, 255, 0, 0));
protected GeoForm(string name)
{
Name = name;
IsActivated = false;
}
public abstract void Draw(Graphics g, Size size, int layer);
public abstract bool Contains(Pixel pixel, Size size);
}
public sealed class RectangleForm : GeoForm
{
private Range X;
private Range Y;
public RectangleForm(string name, Range x, Range y)
: base(name: name)
{
X = x;
Y = y;
}
public override void Draw(Graphics g, Size size, int layer)
{
Brush brush = IsActivated ? ActivatedBrush : DefaultBrush;
if (layer == 10) {
int xMin = (int)(X.Min * size.Width);
int xMax = (int)(X.Max * size.Width);
int yMin = (int)(Y.Min * size.Height);
int yMax = (int)(Y.Max * size.Height);
g.FillRectangle(brush, xMin + 2, yMin + 2, xMax - xMin - 2, yMax - yMin - 2);
}
}
public override bool Contains(Pixel pixel, Size size)
{
int xMin = (int)(X.Min * size.Width);
int xMax = (int)(X.Max * size.Width);
int yMin = (int)(Y.Min * size.Height);
int yMax = (int)(Y.Max * size.Height);
Log.Debug("Contains: pixel:", pixel, ", x: ", xMin, "...", xMax, ", y: ", yMin, "...", yMax);
return xMin <= pixel.X && pixel.X <= xMax && yMin <= pixel.Y && pixel.Y <= yMax;
}
public override string ToString()
{
return string.Format("RectangleForm(\"{0}\";X={1};Y={2})", Name, X, Y);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Input;
using System.Diagnostics;
using System.Windows.Data;
using Microsoft.Win32;
using Mono.Cecil;
using Dependencies.ClrPh;
namespace Dependencies
{
/// <summary>
/// ImportContext : Describe an import module parsed from a PE.
/// Only used during the dependency tree building phase
/// </summary>
public struct ImportContext
{
// Import "identifier"
public string ModuleName;
// Return how the module was found (NOT_FOUND otherwise)
public ModuleSearchStrategy ModuleLocation;
// If found, set the filepath and parsed PE, otherwise it's null
public string PeFilePath;
public PE PeProperties;
// Some imports are from api sets
public bool IsApiSet;
public string ApiSetModuleName;
// module flag attributes
public ModuleFlag Flags;
}
/// <summary>
/// Dependency tree building behaviour.
/// A full recursive dependency tree can be memory intensive, therefore the
/// choice is left to the user to override the default behaviour.
/// </summary>
public class TreeBuildingBehaviour : IValueConverter
{
public enum DependencyTreeBehaviour
{
ChildOnly,
RecursiveOnlyOnDirectImports,
Recursive,
}
public static DependencyTreeBehaviour GetGlobalBehaviour()
{
return (DependencyTreeBehaviour) (new TreeBuildingBehaviour()).Convert(
Dependencies.Properties.Settings.Default.TreeBuildBehaviour,
null,// targetType
null,// parameter
null // System.Globalization.CultureInfo
);
}
#region TreeBuildingBehaviour.IValueConverter_contract
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string StrBehaviour = (string)value;
switch (StrBehaviour)
{
default:
case "ChildOnly":
return DependencyTreeBehaviour.ChildOnly;
case "RecursiveOnlyOnDirectImports":
return DependencyTreeBehaviour.RecursiveOnlyOnDirectImports;
case "Recursive":
return DependencyTreeBehaviour.Recursive;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DependencyTreeBehaviour Behaviour = (DependencyTreeBehaviour) value;
switch (Behaviour)
{
default:
case DependencyTreeBehaviour.ChildOnly:
return "ChildOnly";
case DependencyTreeBehaviour.RecursiveOnlyOnDirectImports:
return "RecursiveOnlyOnDirectImports";
case DependencyTreeBehaviour.Recursive:
return "Recursive";
}
}
#endregion TreeBuildingBehaviour.IValueConverter_contract
}
/// <summary>
/// Dependency tree building behaviour.
/// A full recursive dependency tree can be memory intensive, therefore the
/// choice is left to the user to override the default behaviour.
/// </summary>
public class BinaryCacheOption : IValueConverter
{
[TypeConverter(typeof(EnumToStringUsingDescription))]
public enum BinaryCacheOptionValue
{
[Description("No (faster, but locks dll until Dependencies is closed)")]
No = 0,
[Description("Yes (prevents file locking issues)")]
Yes = 1
}
public static BinaryCacheOptionValue GetGlobalBehaviour()
{
return (BinaryCacheOptionValue)(new BinaryCacheOption()).Convert(
Dependencies.Properties.Settings.Default.BinaryCacheOptionValue,
null,// targetType
null,// parameter
null // System.Globalization.CultureInfo
);
}
#region BinaryCacheOption.IValueConverter_contract
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool StrOption = (bool)value;
switch (StrOption)
{
default:
case true:
return BinaryCacheOptionValue.Yes;
case false:
return BinaryCacheOptionValue.No;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
BinaryCacheOptionValue Behaviour = (BinaryCacheOptionValue)(int)value;
switch (Behaviour)
{
default:
case BinaryCacheOptionValue.Yes:
return true;
case BinaryCacheOptionValue.No:
return false;
}
}
#endregion BinaryCacheOption.IValueConverter_contract
}
public class EnumToStringUsingDescription : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (sourceType.Equals(typeof(Enum)));
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType.Equals(typeof(String)));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (!destinationType.Equals(typeof(String)))
{
throw new ArgumentException("Can only convert to string.", "destinationType");
}
if (!value.GetType().BaseType.Equals(typeof(Enum)))
{
throw new ArgumentException("Can only convert an instance of enum.", "value");
}
string name = value.ToString();
object[] attrs =
value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attrs.Length > 0) ? ((DescriptionAttribute)attrs[0]).Description : name;
}
}
/// <summary>
/// User context of every dependency tree node.
/// </summary>
public struct DependencyNodeContext
{
public DependencyNodeContext(DependencyNodeContext other)
{
ModuleInfo = other.ModuleInfo;
IsDummy = other.IsDummy;
}
/// <summary>
/// We use a WeakReference to point towars a DisplayInfoModule
/// in order to reduce memory allocations.
/// </summary>
public WeakReference ModuleInfo;
/// <summary>
/// Depending on the dependency tree behaviour, we may have to
/// set up "dummy" nodes in order for the parent to display the ">" button.
/// Those dummy are usually destroyed when their parents is expandend and imports resolved.
/// </summary>
public bool IsDummy;
}
/// <summary>
/// Deprendency Tree custom node. It's DataContext is a DependencyNodeContext struct
/// </summary>
public class ModuleTreeViewItem : TreeViewItem, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ModuleTreeViewItem()
{
_importsVerified = false;
_Parent = null;
Dependencies.Properties.Settings.Default.PropertyChanged += this.ModuleTreeViewItem_PropertyChanged;
}
public ModuleTreeViewItem(ModuleTreeViewItem Parent)
{
_importsVerified = false;
_Parent = Parent;
Dependencies.Properties.Settings.Default.PropertyChanged += this.ModuleTreeViewItem_PropertyChanged;
}
public ModuleTreeViewItem(ModuleTreeViewItem Other, ModuleTreeViewItem Parent)
{
_importsVerified = false;
_Parent = Parent;
this.DataContext = new DependencyNodeContext( (DependencyNodeContext) Other.DataContext );
Dependencies.Properties.Settings.Default.PropertyChanged += this.ModuleTreeViewItem_PropertyChanged;
}
#region PropertyEventHandlers
public virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void ModuleTreeViewItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "FullPath")
{
this.Header = (object)GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
}
}
#endregion PropertyEventHandlers
#region Getters
public string GetTreeNodeHeaderName(bool FullPath)
{
return (((DependencyNodeContext)this.DataContext).ModuleInfo.Target as DisplayModuleInfo).ModuleName;
}
public string ModuleFilePath
{
get
{
return (((DependencyNodeContext)this.DataContext).ModuleInfo.Target as DisplayModuleInfo).Filepath;
}
}
public ModuleTreeViewItem ParentModule
{
get
{
return _Parent;
}
}
public ModuleFlag Flags
{
get
{
return ModuleInfo.Flags;
}
}
private bool _has_error;
public bool HasErrors
{
get
{
if (!_importsVerified)
{
_has_error = VerifyModuleImports();
_importsVerified = true;
// Update tooltip only once some basic checks are done
this.ToolTip = ModuleInfo.Status;
}
// propagate error for parent
if (_has_error)
{
ModuleTreeViewItem ParentModule = this.ParentModule;
if (ParentModule != null)
{
ParentModule.HasChildErrors = true;
}
}
return _has_error;
}
set
{
if (value == _has_error) return;
_has_error = value;
OnPropertyChanged("HasErrors");
}
}
public string Tooltip
{
get
{
return ModuleInfo.Status;
}
}
public bool HasChildErrors
{
get
{
return _has_child_errors;
}
set
{
if (value)
{
ModuleInfo.Flags |= ModuleFlag.ChildrenError;
}
else
{
ModuleInfo.Flags &= ~ModuleFlag.ChildrenError;
}
ToolTip = ModuleInfo.Status;
_has_child_errors = true;
OnPropertyChanged("HasChildErrors");
// propagate error for parent
ModuleTreeViewItem ParentModule = this.ParentModule;
if (ParentModule != null)
{
ParentModule.HasChildErrors = true;
}
}
}
public DisplayModuleInfo ModuleInfo
{
get
{
return (((DependencyNodeContext)this.DataContext).ModuleInfo.Target as DisplayModuleInfo);
}
}
private bool VerifyModuleImports()
{
// current module has issues
if ((Flags & (ModuleFlag.NotFound | ModuleFlag.MissingImports | ModuleFlag.ChildrenError)) != 0)
{
return true;
}
// no parent : it's probably the root item
ModuleTreeViewItem ParentModule = this.ParentModule;
if (ParentModule == null)
{
return false;
}
// Check we have any imports issues
foreach (PeImportDll DllImport in ParentModule.ModuleInfo.Imports)
{
if (DllImport.Name != ModuleInfo._Name)
continue;
List<Tuple<PeImport, bool>> resolvedImports = BinaryCache.LookupImports(DllImport, ModuleInfo.Filepath);
if (resolvedImports.Count == 0)
{
return true;
}
foreach (var Import in resolvedImports)
{
if (!Import.Item2)
{
return true;
}
}
}
return false;
}
#endregion Getters
#region Commands
public RelayCommand OpenPeviewerCommand
{
get
{
if (_OpenPeviewerCommand == null)
{
_OpenPeviewerCommand = new RelayCommand((param) => this.OpenPeviewer((object)param));
}
return _OpenPeviewerCommand;
}
}
public bool OpenPeviewer(object Context)
{
string programPath = Dependencies.Properties.Settings.Default.PeViewerPath;
Process PeviewerProcess = new Process();
if (Context == null)
{
return false;
}
if (!File.Exists(programPath))
{
System.Windows.MessageBox.Show(String.Format("{0:s} file could not be found !", programPath));
return false;
}
string Filepath = ModuleFilePath;
if (Filepath == null)
{
return false;
}
PeviewerProcess.StartInfo.FileName = String.Format("\"{0:s}\"", programPath);
PeviewerProcess.StartInfo.Arguments = String.Format("\"{0:s}\"", Filepath);
return PeviewerProcess.Start();
}
public RelayCommand OpenNewAppCommand
{
get
{
if (_OpenNewAppCommand == null)
{
_OpenNewAppCommand = new RelayCommand((param) =>
{
string Filepath = ModuleFilePath;
if (Filepath == null)
{
return;
}
Process OtherDependenciesProcess = new Process();
OtherDependenciesProcess.StartInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
OtherDependenciesProcess.StartInfo.Arguments = String.Format("\"{0:s}\"", Filepath);
OtherDependenciesProcess.Start();
});
}
return _OpenNewAppCommand;
}
}
#endregion // Commands
private RelayCommand _OpenPeviewerCommand;
private RelayCommand _OpenNewAppCommand;
private ModuleTreeViewItem _Parent;
private bool _importsVerified;
private bool _has_child_errors;
}
/// <summary>
/// Dependemcy tree analysis window for a given PE.
/// </summary>
public partial class DependencyWindow : TabItem
{
PE Pe;
public string RootFolder;
public string WorkingDirectory;
string Filename;
PhSymbolProvider SymPrv;
SxsEntries SxsEntriesCache;
ApiSetSchema ApiSetmapCache;
ModulesCache ProcessedModulesCache;
DisplayModuleInfo _SelectedModule;
bool _DisplayWarning;
public List<string> CustomSearchFolders;
#region PublicAPI
public DependencyWindow(String Filename, List<string> CustomSearchFolders = null)
{
InitializeComponent();
if (CustomSearchFolders != null)
{
this.CustomSearchFolders = CustomSearchFolders;
}
else
{
this.CustomSearchFolders = new List<string>();
}
this.Filename = Filename;
this.WorkingDirectory = Path.GetDirectoryName(this.Filename);
InitializeView();
}
public void InitializeView()
{
if (!NativeFile.Exists(this.Filename))
{
MessageBox.Show(
String.Format("{0:s} is not present on the disk", this.Filename),
"Invalid PE",
MessageBoxButton.OK
);
return;
}
this.Pe = (Application.Current as App).LoadBinary(this.Filename);
if (this.Pe == null || !this.Pe.LoadSuccessful)
{
MessageBox.Show(
String.Format("{0:s} is not a valid PE-COFF file", this.Filename),
"Invalid PE",
MessageBoxButton.OK
);
return;
}
this.SymPrv = new PhSymbolProvider();
this.RootFolder = Path.GetDirectoryName(this.Filename);
this.SxsEntriesCache = SxsManifest.GetSxsEntries(this.Pe);
this.ProcessedModulesCache = new ModulesCache();
this.ApiSetmapCache = Phlib.GetApiSetSchema();
this._SelectedModule = null;
this._DisplayWarning = false;
// TODO : Find a way to properly bind commands instead of using this hack
this.ModulesList.Items.Clear();
this.ModulesList.DoFindModuleInTreeCommand = DoFindModuleInTree;
this.ModulesList.ConfigureSearchOrderCommand = ConfigureSearchOrderCommand;
var RootFilename = Path.GetFileName(this.Filename);
var RootModule = new DisplayModuleInfo(RootFilename, this.Pe, ModuleSearchStrategy.ROOT);
this.ProcessedModulesCache.Add(new ModuleCacheKey(RootFilename, this.Filename), RootModule);
ModuleTreeViewItem treeNode = new ModuleTreeViewItem();
DependencyNodeContext childTreeInfoContext = new DependencyNodeContext()
{
ModuleInfo = new WeakReference(RootModule),
IsDummy = false
};
treeNode.DataContext = childTreeInfoContext;
treeNode.Header = treeNode.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
treeNode.IsExpanded = true;
this.DllTreeView.Items.Clear();
this.DllTreeView.Items.Add(treeNode);
// Recursively construct tree of dll imports
ConstructDependencyTree(treeNode, this.Pe);
}
#endregion PublicAPI
#region TreeConstruction
private ImportContext ResolveImport(PeImportDll DllImport)
{
ImportContext ImportModule = new ImportContext();
ImportModule.PeFilePath = null;
ImportModule.PeProperties = null;
ImportModule.ModuleName = DllImport.Name;
ImportModule.ApiSetModuleName = null;
ImportModule.Flags = 0;
if (DllImport.IsDelayLoad())
{
ImportModule.Flags |= ModuleFlag.DelayLoad;
}
Tuple<ModuleSearchStrategy, PE> ResolvedModule = BinaryCache.ResolveModule(
this.Pe,
DllImport.Name,
this.SxsEntriesCache,
this.CustomSearchFolders,
this.WorkingDirectory
);
ImportModule.ModuleLocation = ResolvedModule.Item1;
if (ImportModule.ModuleLocation != ModuleSearchStrategy.NOT_FOUND)
{
ImportModule.PeProperties = ResolvedModule.Item2;
if (ResolvedModule.Item2 != null)
{
ImportModule.PeFilePath = ResolvedModule.Item2.Filepath;
foreach (var Import in BinaryCache.LookupImports(DllImport, ImportModule.PeFilePath))
{
if (!Import.Item2)
{
ImportModule.Flags |= ModuleFlag.MissingImports;
break;
}
}
}
}
else
{
ImportModule.Flags |= ModuleFlag.NotFound;
}
// special case for apiset schema
ImportModule.IsApiSet = (ImportModule.ModuleLocation == ModuleSearchStrategy.ApiSetSchema);
if (ImportModule.IsApiSet)
{
ImportModule.Flags |= ModuleFlag.ApiSet;
ImportModule.ApiSetModuleName = BinaryCache.LookupApiSetLibrary(DllImport.Name);
if (DllImport.Name.StartsWith("ext-"))
{
ImportModule.Flags |= ModuleFlag.ApiSetExt;
}
}
return ImportModule;
}
private void TriggerWarningOnAppvIsvImports(string DllImportName)
{
if (String.Compare(DllImportName, "AppvIsvSubsystems32.dll", StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(DllImportName, "AppvIsvSubsystems64.dll", StringComparison.OrdinalIgnoreCase) == 0)
{
if (!this._DisplayWarning)
{
MessageBoxResult result = MessageBox.Show(
"This binary use the App-V containerization technology which fiddle with search directories and PATH env in ways Dependencies can't handle.\n\nFollowing results are probably not quite exact.",
"App-V ISV disclaimer"
);
this._DisplayWarning = true; // prevent the same warning window to popup several times
}
}
}
private void ProcessAppInitDlls(Dictionary<string, ImportContext> NewTreeContexts, PE AnalyzedPe, ImportContext ImportModule)
{
List<PeImportDll> PeImports = AnalyzedPe.GetImports();
// only user32 triggers appinit dlls
string User32Filepath = Path.Combine(FindPe.GetSystemPath(this.Pe), "user32.dll");
if (ImportModule.PeFilePath != User32Filepath)
{
return;
}
string AppInitRegistryKey =
(this.Pe.IsArm32Dll()) ?
"SOFTWARE\\WowAA32Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows" :
(this.Pe.IsWow64Dll()) ?
"SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows" :
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows";
// Opening registry values
RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
localKey = localKey.OpenSubKey(AppInitRegistryKey);
int LoadAppInitDlls = (int)localKey.GetValue("LoadAppInit_DLLs", 0);
string AppInitDlls = (string)localKey.GetValue("AppInit_DLLs", "");
if (LoadAppInitDlls == 0 || String.IsNullOrEmpty(AppInitDlls))
{
return;
}
// Extremely crude parser. TODO : Add support for quotes wrapped paths with spaces
foreach (var AppInitDll in AppInitDlls.Split(' '))
{
Debug.WriteLine("AppInit loading " + AppInitDll);
// Do not process twice the same imported module
if (null != PeImports.Find(module => module.Name == AppInitDll))
{
continue;
}
if (NewTreeContexts.ContainsKey(AppInitDll))
{
continue;
}
ImportContext AppInitImportModule = new ImportContext();
AppInitImportModule.PeFilePath = null;
AppInitImportModule.PeProperties = null;
AppInitImportModule.ModuleName = AppInitDll;
AppInitImportModule.ApiSetModuleName = null;
AppInitImportModule.Flags = 0;
AppInitImportModule.ModuleLocation = ModuleSearchStrategy.AppInitDLL;
Tuple<ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(
this.Pe,
AppInitDll,
this.SxsEntriesCache,
this.CustomSearchFolders,
this.WorkingDirectory
);
if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
{
AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
AppInitImportModule.PeFilePath = ResolvedAppInitModule.Item2.Filepath;
}
else
{
AppInitImportModule.Flags |= ModuleFlag.NotFound;
}
NewTreeContexts.Add(AppInitDll, AppInitImportModule);
}
}
private void ProcessClrImports(Dictionary<string, ImportContext> NewTreeContexts, PE AnalyzedPe, ImportContext ImportModule)
{
List<PeImportDll> PeImports = AnalyzedPe.GetImports();
// only mscorre triggers clr parsing
string User32Filepath = Path.Combine(FindPe.GetSystemPath(this.Pe), "mscoree.dll");
if (ImportModule.PeFilePath != User32Filepath)
{
return;
}
var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(RootFolder);
// Parse it via cecil
AssemblyDefinition PeAssembly = null;
try
{
PeAssembly = AssemblyDefinition.ReadAssembly(AnalyzedPe.Filepath);
}
catch (BadImageFormatException)
{
MessageBoxResult result = MessageBox.Show(
String.Format("Cecil could not correctly parse {0:s}, which can happens on .NET Core executables. CLR imports will be not shown", AnalyzedPe.Filepath),
"CLR parsing fail"
);
return;
}
foreach (var module in PeAssembly.Modules)
{
// Process CLR referenced assemblies
foreach (var assembly in module.AssemblyReferences)
{
AssemblyDefinition definition;
try
{
definition = resolver.Resolve(assembly);
}
catch (AssemblyResolutionException)
{
ImportContext AppInitImportModule = new ImportContext();
AppInitImportModule.PeFilePath = null;
AppInitImportModule.PeProperties = null;
AppInitImportModule.ModuleName = Path.GetFileName(assembly.Name);
AppInitImportModule.ApiSetModuleName = null;
AppInitImportModule.Flags = ModuleFlag.ClrReference;
AppInitImportModule.ModuleLocation = ModuleSearchStrategy.ClrAssembly;
AppInitImportModule.Flags |= ModuleFlag.NotFound;
if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
{
NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
}
continue;
}
foreach (var AssemblyModule in definition.Modules)
{
Debug.WriteLine("Referenced Assembling loading " + AssemblyModule.Name + " : " + AssemblyModule.FileName);
// Do not process twice the same imported module
if (null != PeImports.Find(mod => mod.Name == Path.GetFileName(AssemblyModule.FileName)))
{
continue;
}
ImportContext AppInitImportModule = new ImportContext();
AppInitImportModule.PeFilePath = null;
AppInitImportModule.PeProperties = null;
AppInitImportModule.ModuleName = Path.GetFileName(AssemblyModule.FileName);
AppInitImportModule.ApiSetModuleName = null;
AppInitImportModule.Flags = ModuleFlag.ClrReference;
AppInitImportModule.ModuleLocation = ModuleSearchStrategy.ClrAssembly;
Tuple<ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(
this.Pe,
AssemblyModule.FileName,
this.SxsEntriesCache,
this.CustomSearchFolders,
this.WorkingDirectory
);
if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
{
AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
AppInitImportModule.PeFilePath = ResolvedAppInitModule.Item2.Filepath;
}
else
{
AppInitImportModule.Flags |= ModuleFlag.NotFound;
}
if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
{
NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
}
}
}
// Process unmanaged dlls for native calls
foreach (var UnmanagedModule in module.ModuleReferences)
{
// some clr dll have a reference to an "empty" dll
if (UnmanagedModule.Name.Length == 0)
{
continue;
}
Debug.WriteLine("Referenced module loading " + UnmanagedModule.Name);
// Do not process twice the same imported module
if (null != PeImports.Find(m => m.Name == UnmanagedModule.Name))
{
continue;
}
ImportContext AppInitImportModule = new ImportContext();
AppInitImportModule.PeFilePath = null;
AppInitImportModule.PeProperties = null;
AppInitImportModule.ModuleName = UnmanagedModule.Name;
AppInitImportModule.ApiSetModuleName = null;
AppInitImportModule.Flags = ModuleFlag.ClrReference;
AppInitImportModule.ModuleLocation = ModuleSearchStrategy.ClrAssembly;
Tuple<ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(
this.Pe,
UnmanagedModule.Name,
this.SxsEntriesCache,
this.CustomSearchFolders,
this.WorkingDirectory
);
if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
{
AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
AppInitImportModule.PeFilePath = ResolvedAppInitModule.Item2.Filepath;
}
if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
{
NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
}
}
}
}
/// <summary>
/// Background processing of a single PE file.
/// It can be lengthy since there are disk access (and misses).
/// </summary>
/// <param name="NewTreeContexts"> This variable is passed as reference to be updated since this function is run in a separate thread. </param>
/// <param name="newPe"> Current PE file analyzed </param>
private void ProcessPe(Dictionary<string, ImportContext> NewTreeContexts, PE newPe)
{
List<PeImportDll> PeImports = newPe.GetImports();
foreach (PeImportDll DllImport in PeImports)
{
// Ignore already processed imports
if (NewTreeContexts.ContainsKey(DllImport.Name))
{
continue;
}
// Find Dll in "paths"
ImportContext ImportModule = ResolveImport(DllImport);
// add warning for appv isv applications
TriggerWarningOnAppvIsvImports(DllImport.Name);
NewTreeContexts.Add(DllImport.Name, ImportModule);
// AppInitDlls are triggered by user32.dll, so if the binary does not import user32.dll they are not loaded.
ProcessAppInitDlls(NewTreeContexts, newPe, ImportModule);
// if mscoree.dll is imported, it means the module is a C# assembly, and we can use Mono.Cecil to enumerate its references
ProcessClrImports(NewTreeContexts, newPe, ImportModule);
}
}
private class BacklogImport : Tuple<ModuleTreeViewItem, string>
{
public BacklogImport(ModuleTreeViewItem Node, string Filepath)
: base(Node, Filepath)
{
}
}
private void ConstructDependencyTree(ModuleTreeViewItem RootNode, string FilePath, int RecursionLevel = 0)
{
PE CurrentPE = (Application.Current as App).LoadBinary(FilePath);
if (null == CurrentPE)
{
return;
}
ConstructDependencyTree(RootNode, CurrentPE, RecursionLevel);
}
private void ConstructDependencyTree(ModuleTreeViewItem RootNode, PE CurrentPE, int RecursionLevel = 0)
{
// "Closured" variables (it 's a scope hack really).
Dictionary<string, ImportContext> NewTreeContexts = new Dictionary<string, ImportContext>();
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true; // useless here for now
bw.DoWork += (sender, e) => {
ProcessPe(NewTreeContexts, CurrentPE);
};
bw.RunWorkerCompleted += (sender, e) =>
{
TreeBuildingBehaviour.DependencyTreeBehaviour SettingTreeBehaviour = Dependencies.TreeBuildingBehaviour.GetGlobalBehaviour();
List<ModuleTreeViewItem> PeWithDummyEntries = new List<ModuleTreeViewItem>();
List<BacklogImport> PEProcessingBacklog = new List<BacklogImport>();
// Important !
//
// This handler is executed in the STA (Single Thread Application)
// which is authorized to manipulate UI elements. The BackgroundWorker is not.
//
foreach (ImportContext NewTreeContext in NewTreeContexts.Values)
{
ModuleTreeViewItem childTreeNode = new ModuleTreeViewItem(RootNode);
DependencyNodeContext childTreeNodeContext = new DependencyNodeContext();
childTreeNodeContext.IsDummy = false;
string ModuleName = NewTreeContext.ModuleName;
string ModuleFilePath = NewTreeContext.PeFilePath;
ModuleCacheKey ModuleKey = new ModuleCacheKey(NewTreeContext);
// Newly seen modules
if (!this.ProcessedModulesCache.ContainsKey(ModuleKey))
{
// Missing module "found"
if ((NewTreeContext.PeFilePath == null) || !NativeFile.Exists(NewTreeContext.PeFilePath))
{
if (NewTreeContext.IsApiSet)
{
this.ProcessedModulesCache[ModuleKey] = new ApiSetNotFoundModuleInfo(ModuleName, NewTreeContext.ApiSetModuleName);
}
else
{
this.ProcessedModulesCache[ModuleKey] = new NotFoundModuleInfo(ModuleName);
}
}
else
{
if (NewTreeContext.IsApiSet)
{
var ApiSetContractModule = new DisplayModuleInfo(NewTreeContext.ApiSetModuleName, NewTreeContext.PeProperties, NewTreeContext.ModuleLocation, NewTreeContext.Flags);
var NewModule = new ApiSetModuleInfo(NewTreeContext.ModuleName, ref ApiSetContractModule);
this.ProcessedModulesCache[ModuleKey] = NewModule;
if (SettingTreeBehaviour == TreeBuildingBehaviour.DependencyTreeBehaviour.Recursive)
{
PEProcessingBacklog.Add(new BacklogImport(childTreeNode, ApiSetContractModule.ModuleName));
}
}
else
{
var NewModule = new DisplayModuleInfo(NewTreeContext.ModuleName, NewTreeContext.PeProperties, NewTreeContext.ModuleLocation, NewTreeContext.Flags);
this.ProcessedModulesCache[ModuleKey] = NewModule;
switch(SettingTreeBehaviour)
{
case TreeBuildingBehaviour.DependencyTreeBehaviour.RecursiveOnlyOnDirectImports:
if ((NewTreeContext.Flags & ModuleFlag.DelayLoad) == 0)
{
PEProcessingBacklog.Add(new BacklogImport(childTreeNode, NewModule.ModuleName));
}
break;
case TreeBuildingBehaviour.DependencyTreeBehaviour.Recursive:
PEProcessingBacklog.Add(new BacklogImport(childTreeNode, NewModule.ModuleName));
break;
}
}
}
// add it to the module list
this.ModulesList.AddModule(this.ProcessedModulesCache[ModuleKey]);
}
// Since we uniquely process PE, for thoses who have already been "seen",
// we set a dummy entry in order to set the "[+]" icon next to the node.
// The dll dependencies are actually resolved on user double-click action
// We can't do the resolution in the same time as the tree construction since
// it's asynchronous (we would have to wait for all the background to finish and
// use another Async worker to resolve).
if ((NewTreeContext.PeProperties != null) && (NewTreeContext.PeProperties.GetImports().Count > 0))
{
ModuleTreeViewItem DummyEntry = new ModuleTreeViewItem();
DependencyNodeContext DummyContext = new DependencyNodeContext()
{
ModuleInfo = new WeakReference(new NotFoundModuleInfo("Dummy")),
IsDummy = true
};
DummyEntry.DataContext = DummyContext;
DummyEntry.Header = "@Dummy : if you see this header, it's a bug.";
DummyEntry.IsExpanded = false;
childTreeNode.Items.Add(DummyEntry);
childTreeNode.Expanded += ResolveDummyEntries;
}
// Add to tree view
childTreeNodeContext.ModuleInfo = new WeakReference(this.ProcessedModulesCache[ModuleKey]);
childTreeNode.DataContext = childTreeNodeContext;
childTreeNode.Header = childTreeNode.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
RootNode.Items.Add(childTreeNode);
}
// Process next batch of dll imports
if (SettingTreeBehaviour != TreeBuildingBehaviour.DependencyTreeBehaviour.ChildOnly)
{
foreach (var ImportNode in PEProcessingBacklog)
{
ConstructDependencyTree(ImportNode.Item1, ImportNode.Item2, RecursionLevel + 1); // warning : recursive call
}
}
};
bw.RunWorkerAsync();
}
/// <summary>
/// Resolve imports when the user expand the node.
/// </summary>
private void ResolveDummyEntries(object sender, RoutedEventArgs e)
{
ModuleTreeViewItem NeedDummyPeNode = e.OriginalSource as ModuleTreeViewItem;
if (NeedDummyPeNode.Items.Count == 0)
{
return;
}
ModuleTreeViewItem MaybeDummyNode = (ModuleTreeViewItem) NeedDummyPeNode.Items[0];
DependencyNodeContext Context = (DependencyNodeContext)MaybeDummyNode.DataContext;
//TODO: Improve resolution predicate
if (!Context.IsDummy)
{
return;
}
NeedDummyPeNode.Items.Clear();
string Filepath = NeedDummyPeNode.ModuleFilePath;
ConstructDependencyTree(NeedDummyPeNode, Filepath);
}
#endregion TreeConstruction
#region Commands
private void OnModuleViewSelectedItemChanged(object sender, RoutedEventArgs e)
{
DisplayModuleInfo SelectedModule = (sender as DependencyModuleList).SelectedItem as DisplayModuleInfo;
// Selected Pe has not been found on disk
if (SelectedModule == null)
return;
// Display module as root (since we can't know which parent it's attached to)
UpdateImportExportLists(SelectedModule, null);
}
private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (this.DllTreeView.SelectedItem == null)
{
UpdateImportExportLists(null, null);
return;
}
DependencyNodeContext childTreeContext = ((DependencyNodeContext)(this.DllTreeView.SelectedItem as ModuleTreeViewItem).DataContext);
DisplayModuleInfo SelectedModule = childTreeContext.ModuleInfo.Target as DisplayModuleInfo;
if (SelectedModule == null)
{
return;
}
// Selected Pe has not been found on disk : unvalidate current module
SelectedModule.HasErrors = !NativeFile.Exists(SelectedModule.Filepath);
if (SelectedModule.HasErrors)
{
// TODO : do a proper refresh instead of asking the user to do it
System.Windows.MessageBox.Show(String.Format("We could not find {0:s} file on the disk anymore, please fix this problem and refresh the window via F5", SelectedModule.Filepath));
}
// Root Item : no parent
ModuleTreeViewItem TreeRootItem = this.DllTreeView.Items[0] as ModuleTreeViewItem;
ModuleTreeViewItem SelectedItem = this.DllTreeView.SelectedItem as ModuleTreeViewItem;
if (SelectedItem == TreeRootItem)
{
// Selected Pe has not been found on disk : unvalidate current module
if (SelectedModule.HasErrors)
{
UpdateImportExportLists(null, null);
}
else
{
SelectedModule.HasErrors = false;
UpdateImportExportLists(SelectedModule, null);
}
return;
}
// Tree Item
DisplayModuleInfo parentModule = SelectedItem.ParentModule.ModuleInfo;
UpdateImportExportLists(SelectedModule, parentModule);
}
private void UpdateImportExportLists(DisplayModuleInfo SelectedModule, DisplayModuleInfo Parent)
{
if (SelectedModule == null)
{
this.ImportList.Items.Clear();
this.ExportList.Items.Clear();
}
else
{
if (Parent == null) // root module
{
this.ImportList.SetRootImports(SelectedModule.Imports, SymPrv, this);
}
else
{
// Imports from the same dll are not necessarly sequential (see: HDDGuru\RawCopy.exe)
var machingImports = Parent.Imports.FindAll(imp => imp.Name == SelectedModule._Name);
this.ImportList.SetImports(SelectedModule.Filepath, SelectedModule.Exports, machingImports, SymPrv, this);
}
this.ImportList.ResetAutoSortProperty();
this.ExportList.SetExports(SelectedModule.Exports, SymPrv);
this.ExportList.ResetAutoSortProperty();
}
}
public PE LoadImport(string ModuleName, DisplayModuleInfo CurrentModule = null, bool DelayLoad = false)
{
if (CurrentModule == null)
{
CurrentModule = this._SelectedModule;
}
Tuple<ModuleSearchStrategy, PE> ResolvedModule = BinaryCache.ResolveModule(
this.Pe,
ModuleName,
this.SxsEntriesCache,
this.CustomSearchFolders,
this.WorkingDirectory
);
string ModuleFilepath = (ResolvedModule.Item2 != null) ? ResolvedModule.Item2.Filepath : null;
// Not found module, returning PE without update module list
if (ModuleFilepath == null)
{
return ResolvedModule.Item2;
}
ModuleFlag ModuleFlags = ModuleFlag.NoFlag;
if (DelayLoad)
ModuleFlags |= ModuleFlag.DelayLoad;
if (ResolvedModule.Item1 == ModuleSearchStrategy.ApiSetSchema)
ModuleFlags |= ModuleFlag.ApiSet;
ModuleCacheKey ModuleKey = new ModuleCacheKey(ModuleName, ModuleFilepath, ModuleFlags);
if (!this.ProcessedModulesCache.ContainsKey(ModuleKey))
{
DisplayModuleInfo NewModule;
// apiset resolution are a bit trickier
if (ResolvedModule.Item1 == ModuleSearchStrategy.ApiSetSchema)
{
var ApiSetContractModule = new DisplayModuleInfo(
BinaryCache.LookupApiSetLibrary(ModuleName),
ResolvedModule.Item2,
ResolvedModule.Item1,
ModuleFlags
);
NewModule = new ApiSetModuleInfo(ModuleName, ref ApiSetContractModule);
}
else
{
NewModule = new DisplayModuleInfo(
ModuleName,
ResolvedModule.Item2,
ResolvedModule.Item1,
ModuleFlags
);
}
this.ProcessedModulesCache[ModuleKey] = NewModule;
// add it to the module list
this.ModulesList.AddModule(this.ProcessedModulesCache[ModuleKey]);
}
return ResolvedModule.Item2;
}
/// <summary>
/// Reentrant version of Collapse/Expand Node
/// </summary>
/// <param name="Item"></param>
/// <param name="ExpandNode"></param>
private void CollapseOrExpandAllNodes(ModuleTreeViewItem Item, bool ExpandNode)
{
Item.IsExpanded = ExpandNode;
foreach(ModuleTreeViewItem ChildItem in Item.Items)
{
CollapseOrExpandAllNodes(ChildItem, ExpandNode);
}
}
private void ExpandAllNodes_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Expanding all nodes tends to slow down the application (massive allocations for node DataContext)
// TODO : Reduce memory pressure by storing tree nodes data context in a HashSet and find an async trick
// to improve the command responsiveness.
System.Windows.Controls.TreeView TreeNode = sender as System.Windows.Controls.TreeView;
CollapseOrExpandAllNodes((TreeNode.Items[0] as ModuleTreeViewItem), true);
}
private void CollapseAllNodes_Executed(object sender, ExecutedRoutedEventArgs e)
{
System.Windows.Controls.TreeView TreeNode = sender as System.Windows.Controls.TreeView;
CollapseOrExpandAllNodes((TreeNode.Items[0] as ModuleTreeViewItem), false);
}
private void DoFindModuleInList_Executed(object sender, ExecutedRoutedEventArgs e)
{
ModuleTreeViewItem Source = e.Source as ModuleTreeViewItem;
String SelectedModuleName = Source.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
foreach (DisplayModuleInfo item in this.ModulesList.Items)
{
if (item.ModuleName == SelectedModuleName)
{
this.ModulesList.SelectedItem = item;
this.ModulesList.ScrollIntoView(item);
return;
}
}
}
private void ExpandAllParentNode(ModuleTreeViewItem Item)
{
if (Item != null)
{
ExpandAllParentNode(Item.Parent as ModuleTreeViewItem);
Item.IsExpanded = true;
}
}
/// <summary>
/// Reentrant version of Collapse/Expand Node
/// </summary>
/// <param name="Item"></param>
/// <param name="ExpandNode"></param>
private ModuleTreeViewItem FindModuleInTree(ModuleTreeViewItem Item, DisplayModuleInfo Module, bool Highlight=false)
{
if (Item.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath) == Module.ModuleName)
{
if (Highlight)
{
ExpandAllParentNode(Item.Parent as ModuleTreeViewItem);
Item.IsSelected = true;
Item.BringIntoView();
Item.Focus();
}
return Item;
}
// BFS style search -> return the first matching node with the lowest "depth"
foreach (ModuleTreeViewItem ChildItem in Item.Items)
{
if(ChildItem.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath) == Module.ModuleName)
{
if (Highlight)
{
ExpandAllParentNode(Item);
ChildItem.IsSelected = true;
ChildItem.BringIntoView();
ChildItem.Focus();
}
return Item;
}
}
foreach (ModuleTreeViewItem ChildItem in Item.Items)
{
ModuleTreeViewItem matchingItem = FindModuleInTree(ChildItem, Module, Highlight);
// early exit as soon as we find a matching node
if (matchingItem != null)
return matchingItem;
}
return null;
}
public RelayCommand DoFindModuleInTree
{
get
{
return new RelayCommand((param) =>
{
DisplayModuleInfo SelectedModule = (param as DisplayModuleInfo);
ModuleTreeViewItem TreeRootItem = this.DllTreeView.Items[0] as ModuleTreeViewItem;
FindModuleInTree(TreeRootItem, SelectedModule, true);
});
}
}
public RelayCommand ConfigureSearchOrderCommand
{
get
{
return new RelayCommand((param) =>
{
ModuleSearchOrder modalWindow = new ModuleSearchOrder(ProcessedModulesCache);
modalWindow.ShowDialog();
});
}
}
#endregion // Commands
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit 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.Collections.Generic;
using MindTouch.Dream;
namespace MindTouch.Web {
/// <summary>
/// Provides a hierarchical <see cref="DreamCookie"/> container.
/// </summary>
public class DreamCookieJar {
//--- Fields ---
private List<DreamCookie> _cookies;
private Dictionary<string, DreamCookieJar> _jars;
//--- Properties ---
/// <summary>
/// Total cookies in the jar.
/// </summary>
public int Count {
get {
int result = 0;
if(_jars != null) {
foreach(DreamCookieJar jar in _jars.Values) {
result += jar.Count;
}
}
if(_cookies != null) {
result += _cookies.Count;
}
return result;
}
}
/// <summary>
/// <see langword="True"/> if there are no cookies in the jar.
/// </summary>
public bool IsEmpty {
get {
return ((_jars == null) || (_jars.Count == 0)) && ((_cookies == null) || (_cookies.Count == 0));
}
}
//--- Methods ---
/// <summary>
/// Clear all cookies from the jar.
/// </summary>
public void Clear() {
_cookies = null;
_jars = null;
}
/// <summary>
/// Update the jar with a cookie.
/// </summary>
/// <param name="cookie">Cookie to store.</param>
/// <param name="uri">Uri this cookie applies to.</param>
public void Update(DreamCookie cookie, XUri uri) {
List<DreamCookie> list = new List<DreamCookie>();
list.Add(cookie);
Update(list, uri);
}
/// <summary>
/// Update the jar with a collection cookies.
/// </summary>
/// <param name="collection">List of cookies to store.</param>
/// <param name="uri">Uri cookies apply to.</param>
public void Update(List<DreamCookie> collection, XUri uri) {
if(collection == null) {
throw new ArgumentNullException("collection");
}
// process all cookies
foreach(DreamCookie c in collection) {
DreamCookie cookie = c;
if(!string.IsNullOrEmpty(cookie.Name)) {
string[] segments = null;
if(uri != null) {
// set default domain if needed
if(string.IsNullOrEmpty(cookie.Domain)) {
cookie = cookie.WithHostPort(uri.HostPort);
} else if(!StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, uri.HostPort)) {
// domain doesn't match, ignore cookie
continue;
}
// set default path if needed
if(string.IsNullOrEmpty(cookie.Path)) {
cookie = cookie.WithPath(uri.Path);
segments = uri.Segments;
} else {
segments = cookie.Uri == null ? new string[0] : cookie.Uri.Segments;
if(!uri.PathStartsWith(segments)) {
// path doesn't match ignore cookie
continue;
}
}
}
if(!string.IsNullOrEmpty(cookie.Path) && !string.IsNullOrEmpty(cookie.Domain)) {
if(segments == null) {
segments = cookie.Uri == null ? new string[0] : cookie.Uri.Segments;
}
if(cookie.Expired) {
Delete(cookie, segments, 0);
} else {
Insert(cookie, segments, 0);
}
}
}
}
}
/// <summary>
/// Retrieve all cookies that apply to a Uri.
/// </summary>
/// <param name="uri">Uri to match.</param>
/// <returns>List of cookies.</returns>
public List<DreamCookie> Fetch(XUri uri) {
if(uri == null) {
throw new ArgumentNullException("uri");
}
List<DreamCookie> result = new List<DreamCookie>();
Fetch(uri, 0, result);
XUri localUri = uri.AsLocalUri();
if(localUri != uri) {
Fetch(localUri, 0, result);
}
return result;
}
private void Insert(DreamCookie updatedCookie, string[] segments, int depth) {
// find leaf node
if(depth < segments.Length) {
if(_jars == null) {
_jars = new Dictionary<string, DreamCookieJar>(StringComparer.OrdinalIgnoreCase);
}
DreamCookieJar subjar;
if(!_jars.TryGetValue(segments[depth], out subjar)) {
subjar = new DreamCookieJar();
_jars.Add(segments[depth], subjar);
}
subjar.Insert(updatedCookie, segments, depth + 1);
} else {
if(_cookies == null) {
_cookies = new List<DreamCookie>();
}
List<DreamCookie> expired = new List<DreamCookie>();
for(int i = 0; i < _cookies.Count; ++i) {
DreamCookie cookie = _cookies[i];
// check if cookie is expired; if so, remove it
if(cookie.Expired) {
expired.Add(cookie);
continue;
}
// TODO (steveb): we need to add support for '.' prefixes on the domain name
// check if cookie matches the expired cookie
if(StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, updatedCookie.Domain) && StringUtil.EqualsInvariantIgnoreCase(cookie.Name, updatedCookie.Name) && (cookie.Secure == updatedCookie.Secure)) {
_cookies[i] = updatedCookie;
return;
}
}
foreach(DreamCookie cookie in expired) {
_cookies.Remove(cookie);
}
_cookies.Add(updatedCookie);
}
}
private void Delete(DreamCookie expiredCookie, string[] segments, int depth) {
// find leaf node
if(depth < segments.Length) {
if(_jars != null) {
DreamCookieJar subjar;
if(_jars.TryGetValue(segments[depth], out subjar)) {
subjar.Delete(expiredCookie, segments, depth + 1);
if(subjar.IsEmpty) {
_jars.Remove(segments[depth]);
}
}
}
} else if(_cookies != null) {
List<DreamCookie> expired = new List<DreamCookie>();
foreach(DreamCookie cookie in _cookies) {
// check if cookie is expired; if so, remove it
if(cookie.Expired) {
expired.Add(cookie);
continue;
}
// TODO (steveb): we need to add support for '.' prefixes on the domain name
// check if cookie matches the expired cookie
if(StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, expiredCookie.Domain) && StringUtil.EqualsInvariantIgnoreCase(cookie.Name, expiredCookie.Name) && (cookie.Secure == expiredCookie.Secure)) {
expired.Add(cookie);
continue;
}
}
foreach(DreamCookie cookie in expired) {
_cookies.Remove(cookie);
}
}
}
private void Fetch(XUri uri, int depth, List<DreamCookie> result) {
// if available, fetch cookies from deeper in the path
if((depth < uri.Segments.Length) && (_jars != null)) {
DreamCookieJar subjar;
if(_jars.TryGetValue(uri.Segments[depth], out subjar)) {
subjar.Fetch(uri, depth + 1, result);
}
}
// collect all cookies that are valid and apply to this uri
if(_cookies != null) {
List<DreamCookie> expired = new List<DreamCookie>();
foreach(DreamCookie cookie in _cookies) {
// check if cookie is expired; if so, remove it
if(cookie.Expired) {
expired.Add(cookie);
continue;
}
// TODO (steveb): we need to add support for '.' prefixes on the domain name
// check if cookie matches the host and uri
if(StringUtil.EqualsInvariantIgnoreCase(cookie.Domain, uri.HostPort) && (!cookie.Secure || (cookie.Secure && StringUtil.EqualsInvariantIgnoreCase(uri.Scheme, "https")))) {
result.Add(cookie);
}
}
foreach(DreamCookie cookie in expired) {
_cookies.Remove(cookie);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
namespace System.Xml
{
// Represents a collection of attributes that can be accessed by name or index.
public sealed class XmlAttributeCollection : XmlNamedNodeMap, ICollection
{
internal XmlAttributeCollection(XmlNode parent) : base(parent)
{
}
// Gets the attribute with the specified index.
[System.Runtime.CompilerServices.IndexerName("ItemOf")]
public XmlAttribute this[int i]
{
get
{
try
{
return (XmlAttribute)nodes[i];
}
catch (ArgumentOutOfRangeException)
{
throw new IndexOutOfRangeException(SR.Xdom_IndexOutOfRange);
}
}
}
// Gets the attribute with the specified name.
[System.Runtime.CompilerServices.IndexerName("ItemOf")]
public XmlAttribute this[string name]
{
get
{
int hash = XmlName.GetHashCode(name);
for (int i = 0; i < nodes.Count; i++)
{
XmlAttribute node = (XmlAttribute)nodes[i];
if (hash == node.LocalNameHash
&& name == node.Name)
{
return node;
}
}
return null;
}
}
// Gets the attribute with the specified LocalName and NamespaceUri.
[System.Runtime.CompilerServices.IndexerName("ItemOf")]
public XmlAttribute this[string localName, string namespaceURI]
{
get
{
int hash = XmlName.GetHashCode(localName);
for (int i = 0; i < nodes.Count; i++)
{
XmlAttribute node = (XmlAttribute)nodes[i];
if (hash == node.LocalNameHash
&& localName == node.LocalName
&& namespaceURI == node.NamespaceURI)
{
return node;
}
}
return null;
}
}
internal int FindNodeOffset(XmlAttribute node)
{
for (int i = 0; i < nodes.Count; i++)
{
XmlAttribute tmp = (XmlAttribute)nodes[i];
if (tmp.LocalNameHash == node.LocalNameHash
&& tmp.Name == node.Name
&& tmp.NamespaceURI == node.NamespaceURI)
{
return i;
}
}
return -1;
}
internal int FindNodeOffsetNS(XmlAttribute node)
{
for (int i = 0; i < nodes.Count; i++)
{
XmlAttribute tmp = (XmlAttribute)nodes[i];
if (tmp.LocalNameHash == node.LocalNameHash
&& tmp.LocalName == node.LocalName
&& tmp.NamespaceURI == node.NamespaceURI)
{
return i;
}
}
return -1;
}
// Adds a XmlNode using its Name property
public override XmlNode SetNamedItem(XmlNode node)
{
if (node == null)
return null;
if (!(node is XmlAttribute))
throw new ArgumentException(SR.Xdom_AttrCol_Object);
int offset = FindNodeOffset(node.LocalName, node.NamespaceURI);
if (offset == -1)
{
return InternalAppendAttribute((XmlAttribute)node);
}
else
{
XmlNode oldNode = base.RemoveNodeAt(offset);
InsertNodeAt(offset, node);
return oldNode;
}
}
// Inserts the specified node as the first node in the collection.
public XmlAttribute Prepend(XmlAttribute node)
{
if (node.OwnerDocument != null && node.OwnerDocument != parent.OwnerDocument)
throw new ArgumentException(SR.Xdom_NamedNode_Context);
if (node.OwnerElement != null)
Detach(node);
RemoveDuplicateAttribute(node);
InsertNodeAt(0, node);
return node;
}
// Inserts the specified node as the last node in the collection.
public XmlAttribute Append(XmlAttribute node)
{
XmlDocument doc = node.OwnerDocument;
if (doc == null || doc.IsLoading == false)
{
if (doc != null && doc != parent.OwnerDocument)
{
throw new ArgumentException(SR.Xdom_NamedNode_Context);
}
if (node.OwnerElement != null)
{
Detach(node);
}
AddNode(node);
}
else
{
base.AddNodeForLoad(node, doc);
InsertParentIntoElementIdAttrMap(node);
}
return node;
}
// Inserts the specified attribute immediately before the specified reference attribute.
public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode)
{
if (newNode == refNode)
return newNode;
if (refNode == null)
return Append(newNode);
if (refNode.OwnerElement != parent)
throw new ArgumentException(SR.Xdom_AttrCol_Insert);
if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument)
throw new ArgumentException(SR.Xdom_NamedNode_Context);
if (newNode.OwnerElement != null)
Detach(newNode);
int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI);
Debug.Assert(offset != -1); // the if statement above guarantees that the ref node is in the collection
int dupoff = RemoveDuplicateAttribute(newNode);
if (dupoff >= 0 && dupoff < offset)
offset--;
InsertNodeAt(offset, newNode);
return newNode;
}
// Inserts the specified attribute immediately after the specified reference attribute.
public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode)
{
if (newNode == refNode)
return newNode;
if (refNode == null)
return Prepend(newNode);
if (refNode.OwnerElement != parent)
throw new ArgumentException(SR.Xdom_AttrCol_Insert);
if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument)
throw new ArgumentException(SR.Xdom_NamedNode_Context);
if (newNode.OwnerElement != null)
Detach(newNode);
int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI);
Debug.Assert(offset != -1); // the if statement above guarantees that the ref node is in the collection
int dupoff = RemoveDuplicateAttribute(newNode);
if (dupoff >= 0 && dupoff <= offset)
offset--;
InsertNodeAt(offset + 1, newNode);
return newNode;
}
// Removes the specified attribute node from the map.
public XmlAttribute Remove(XmlAttribute node)
{
int cNodes = nodes.Count;
for (int offset = 0; offset < cNodes; offset++)
{
if (nodes[offset] == node)
{
RemoveNodeAt(offset);
return node;
}
}
return null;
}
// Removes the attribute node with the specified index from the map.
public XmlAttribute RemoveAt(int i)
{
if (i < 0 || i >= Count)
return null;
return (XmlAttribute)RemoveNodeAt(i);
}
// Removes all attributes from the map.
public void RemoveAll()
{
int n = Count;
while (n > 0)
{
n--;
RemoveAt(n);
}
}
void ICollection.CopyTo(Array array, int index)
{
for (int i = 0, max = Count; i < max; i++, index++)
{
array.SetValue(nodes[i], index);
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return this; }
}
int ICollection.Count
{
get { return base.Count; }
}
public void CopyTo(XmlAttribute[] array, int index)
{
for (int i = 0, max = Count; i < max; i++, index++)
array[index] = (XmlAttribute)(((XmlNode)nodes[i]).CloneNode(true));
}
internal override XmlNode AddNode(XmlNode node)
{
//should be sure by now that the node doesn't have the same name with an existing node in the collection
RemoveDuplicateAttribute((XmlAttribute)node);
XmlNode retNode = base.AddNode(node);
Debug.Assert(retNode is XmlAttribute);
InsertParentIntoElementIdAttrMap((XmlAttribute)node);
return retNode;
}
internal override XmlNode InsertNodeAt(int i, XmlNode node)
{
XmlNode retNode = base.InsertNodeAt(i, node);
InsertParentIntoElementIdAttrMap((XmlAttribute)node);
return retNode;
}
internal override XmlNode RemoveNodeAt(int i)
{
//remove the node without checking replacement
XmlNode retNode = base.RemoveNodeAt(i);
Debug.Assert(retNode is XmlAttribute);
RemoveParentFromElementIdAttrMap((XmlAttribute)retNode);
// after remove the attribute, we need to check if a default attribute node should be created and inserted into the tree
XmlAttribute defattr = parent.OwnerDocument.GetDefaultAttribute((XmlElement)parent, retNode.Prefix, retNode.LocalName, retNode.NamespaceURI);
if (defattr != null)
InsertNodeAt(i, defattr);
return retNode;
}
internal void Detach(XmlAttribute attr)
{
attr.OwnerElement.Attributes.Remove(attr);
}
//insert the parent element node into the map
internal void InsertParentIntoElementIdAttrMap(XmlAttribute attr)
{
XmlElement parentElem = parent as XmlElement;
if (parentElem != null)
{
if (parent.OwnerDocument == null)
return;
XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName);
if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName)
{
parent.OwnerDocument.AddElementWithId(attr.Value, parentElem); //add the element into the hashtable
}
}
}
//remove the parent element node from the map when the ID attribute is removed
internal void RemoveParentFromElementIdAttrMap(XmlAttribute attr)
{
XmlElement parentElem = parent as XmlElement;
if (parentElem != null)
{
if (parent.OwnerDocument == null)
return;
XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName);
if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName)
{
parent.OwnerDocument.RemoveElementWithId(attr.Value, parentElem); //remove the element from the hashtable
}
}
}
//the function checks if there is already node with the same name existing in the collection
// if so, remove it because the new one will be inserted to replace this one (could be in different position though )
// by the calling function later
internal int RemoveDuplicateAttribute(XmlAttribute attr)
{
int ind = FindNodeOffset(attr.LocalName, attr.NamespaceURI);
if (ind != -1)
{
XmlAttribute at = (XmlAttribute)nodes[ind];
base.RemoveNodeAt(ind);
RemoveParentFromElementIdAttrMap(at);
}
return ind;
}
internal bool PrepareParentInElementIdAttrMap(string attrPrefix, string attrLocalName)
{
XmlElement parentElem = parent as XmlElement;
Debug.Assert(parentElem != null);
XmlDocument doc = parent.OwnerDocument;
Debug.Assert(doc != null);
//The returned attrname if not null is the name with namespaceURI being set to string.Empty
//Because DTD doesn't support namespaceURI so all comparisons are based on no namespaceURI (string.Empty);
XmlName attrname = doc.GetIDInfoByElement(parentElem.XmlName);
if (attrname != null && attrname.Prefix == attrPrefix && attrname.LocalName == attrLocalName)
{
return true;
}
return false;
}
internal void ResetParentInElementIdAttrMap(string oldVal, string newVal)
{
XmlElement parentElem = parent as XmlElement;
Debug.Assert(parentElem != null);
XmlDocument doc = parent.OwnerDocument;
Debug.Assert(doc != null);
doc.RemoveElementWithId(oldVal, parentElem); //add the element into the hashtable
doc.AddElementWithId(newVal, parentElem);
}
// WARNING:
// For performance reasons, this function does not check
// for xml attributes within the collection with the same full name.
// This means that any caller of this function must be sure that
// a duplicate attribute does not exist.
internal XmlAttribute InternalAppendAttribute(XmlAttribute node)
{
// a duplicate node better not exist
Debug.Assert(-1 == FindNodeOffset(node));
XmlNode retNode = base.AddNode(node);
Debug.Assert(retNode is XmlAttribute);
InsertParentIntoElementIdAttrMap((XmlAttribute)node);
return (XmlAttribute)retNode;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Diagnostics;
namespace System.Xml
{
internal class XmlElementList : XmlNodeList
{
private string _asterisk;
private int _changeCount; //recording the total number that the dom tree has been changed ( insertion and deletetion )
//the member vars below are saved for further reconstruction
private string _name; //only one of 2 string groups will be initialized depends on which constructor is called.
private string _localName;
private string _namespaceURI;
private XmlNode _rootNode;
// the memeber vars belwo serves the optimization of accessing of the elements in the list
private int _curInd; // -1 means the starting point for a new search round
private XmlNode _curElem; // if sets to rootNode, means the starting point for a new search round
private bool _empty; // whether the list is empty
private bool _atomized; //whether the localname and namespaceuri are aomized
private int _matchCount; // cached list count. -1 means it needs reconstruction
private WeakReference _listener; // XmlElementListListener
private XmlElementList(XmlNode parent)
{
Debug.Assert(parent != null);
Debug.Assert(parent.NodeType == XmlNodeType.Element || parent.NodeType == XmlNodeType.Document);
_rootNode = parent;
Debug.Assert(parent.Document != null);
_curInd = -1;
_curElem = _rootNode;
_changeCount = 0;
_empty = false;
_atomized = true;
_matchCount = -1;
// This can be a regular reference, but it would cause some kind of loop inside the GC
_listener = new WeakReference(new XmlElementListListener(parent.Document, this));
}
~XmlElementList()
{
Dispose(false);
}
internal void ConcurrencyCheck(XmlNodeChangedEventArgs args)
{
if (_atomized == false)
{
XmlNameTable nameTable = _rootNode.Document.NameTable;
_localName = nameTable.Add(_localName);
_namespaceURI = nameTable.Add(_namespaceURI);
_atomized = true;
}
if (IsMatch(args.Node))
{
_changeCount++;
_curInd = -1;
_curElem = _rootNode;
if (args.Action == XmlNodeChangedAction.Insert)
_empty = false;
}
_matchCount = -1;
}
internal XmlElementList(XmlNode parent, string name) : this(parent)
{
Debug.Assert(parent.Document != null);
XmlNameTable nt = parent.Document.NameTable;
Debug.Assert(nt != null);
_asterisk = nt.Add("*");
_name = nt.Add(name);
_localName = null;
_namespaceURI = null;
}
internal XmlElementList(XmlNode parent, string localName, string namespaceURI) : this(parent)
{
Debug.Assert(parent.Document != null);
XmlNameTable nt = parent.Document.NameTable;
Debug.Assert(nt != null);
_asterisk = nt.Add("*");
_localName = nt.Get(localName);
_namespaceURI = nt.Get(namespaceURI);
if ((_localName == null) || (_namespaceURI == null))
{
_empty = true;
_atomized = false;
_localName = localName;
_namespaceURI = namespaceURI;
}
_name = null;
}
internal int ChangeCount
{
get { return _changeCount; }
}
// return the next element node that is in PreOrder
private XmlNode NextElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
//For preorder walking, first try its child
XmlNode retNode = curNode.FirstChild;
if (retNode == null)
{
//if no child, the next node forward will the be the NextSibling of the first ancestor which has NextSibling
//so, first while-loop find out such an ancestor (until no more ancestor or the ancestor is the rootNode
retNode = curNode;
while (retNode != null
&& retNode != _rootNode
&& retNode.NextSibling == null)
{
retNode = retNode.ParentNode;
}
//then if such ancestor exists, set the retNode to its NextSibling
if (retNode != null && retNode != _rootNode)
retNode = retNode.NextSibling;
}
if (retNode == _rootNode)
//if reach the rootNode, consider having walked through the whole tree and no more element after the curNode
retNode = null;
return retNode;
}
// return the previous element node that is in PreOrder
private XmlNode PrevElemInPreOrder(XmlNode curNode)
{
Debug.Assert(curNode != null);
//For preorder walking, the previous node will be the right-most node in the tree of PreviousSibling of the curNode
XmlNode retNode = curNode.PreviousSibling;
// so if the PreviousSibling is not null, going through the tree down to find the right-most node
while (retNode != null)
{
if (retNode.LastChild == null)
break;
retNode = retNode.LastChild;
}
// if no PreviousSibling, the previous node will be the curNode's parentNode
if (retNode == null)
retNode = curNode.ParentNode;
// if the final retNode is rootNode, consider having walked through the tree and no more previous node
if (retNode == _rootNode)
retNode = null;
return retNode;
}
// if the current node a matching element node
private bool IsMatch(XmlNode curNode)
{
if (curNode.NodeType == XmlNodeType.Element)
{
if (_name != null)
{
if (Ref.Equal(_name, _asterisk) || Ref.Equal(curNode.Name, _name))
return true;
}
else
{
if (
(Ref.Equal(_localName, _asterisk) || Ref.Equal(curNode.LocalName, _localName)) &&
(Ref.Equal(_namespaceURI, _asterisk) || curNode.NamespaceURI == _namespaceURI)
)
{
return true;
}
}
}
return false;
}
private XmlNode GetMatchingNode(XmlNode n, bool bNext)
{
Debug.Assert(n != null);
XmlNode node = n;
do
{
if (bNext)
node = NextElemInPreOrder(node);
else
node = PrevElemInPreOrder(node);
} while (node != null && !IsMatch(node));
return node;
}
private XmlNode GetNthMatchingNode(XmlNode n, bool bNext, int nCount)
{
Debug.Assert(n != null);
XmlNode node = n;
for (int ind = 0; ind < nCount; ind++)
{
node = GetMatchingNode(node, bNext);
if (node == null)
return null;
}
return node;
}
//the function is for the enumerator to find out the next available matching element node
public XmlNode GetNextNode(XmlNode n)
{
if (_empty == true)
return null;
XmlNode node = (n == null) ? _rootNode : n;
return GetMatchingNode(node, true);
}
public override XmlNode Item(int index)
{
if (_rootNode == null || index < 0)
return null;
if (_empty == true)
return null;
if (_curInd == index)
return _curElem;
int nDiff = index - _curInd;
bool bForward = (nDiff > 0);
if (nDiff < 0)
nDiff = -nDiff;
XmlNode node;
if ((node = GetNthMatchingNode(_curElem, bForward, nDiff)) != null)
{
_curInd = index;
_curElem = node;
return _curElem;
}
return null;
}
public override int Count
{
get
{
if (_empty == true)
return 0;
if (_matchCount < 0)
{
int currMatchCount = 0;
int currChangeCount = _changeCount;
XmlNode node = _rootNode;
while ((node = GetMatchingNode(node, true)) != null)
{
currMatchCount++;
}
if (currChangeCount != _changeCount)
{
return currMatchCount;
}
_matchCount = currMatchCount;
}
return _matchCount;
}
}
public override IEnumerator GetEnumerator()
{
if (_empty == true)
return new XmlEmptyElementListEnumerator(this); ;
return new XmlElementListEnumerator(this);
}
protected override void PrivateDisposeNodeList()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_listener != null)
{
XmlElementListListener listener = (XmlElementListListener)_listener.Target;
if (listener != null)
{
listener.Unregister();
}
_listener = null;
}
}
}
internal class XmlElementListEnumerator : IEnumerator
{
private XmlElementList _list;
private XmlNode _curElem;
private int _changeCount; //save the total number that the dom tree has been changed ( insertion and deletetion ) when this enumerator is created
public XmlElementListEnumerator(XmlElementList list)
{
_list = list;
_curElem = null;
_changeCount = list.ChangeCount;
}
public bool MoveNext()
{
if (_list.ChangeCount != _changeCount)
{
//the number mismatch, there is new change(s) happened since last MoveNext() is called.
throw new InvalidOperationException(SR.Xdom_Enum_ElementList);
}
else
{
_curElem = _list.GetNextNode(_curElem);
}
return _curElem != null;
}
public void Reset()
{
_curElem = null;
//reset the number of changes to be synced with current dom tree as well
_changeCount = _list.ChangeCount;
}
public object Current
{
get { return _curElem; }
}
}
internal class XmlEmptyElementListEnumerator : IEnumerator
{
public XmlEmptyElementListEnumerator(XmlElementList list)
{
}
public bool MoveNext()
{
return false;
}
public void Reset()
{
}
public object Current
{
get { return null; }
}
}
internal class XmlElementListListener
{
private WeakReference _elemList;
private XmlDocument _doc;
private XmlNodeChangedEventHandler _nodeChangeHandler = null;
internal XmlElementListListener(XmlDocument doc, XmlElementList elemList)
{
_doc = doc;
_elemList = new WeakReference(elemList);
_nodeChangeHandler = new XmlNodeChangedEventHandler(this.OnListChanged);
doc.NodeInserted += _nodeChangeHandler;
doc.NodeRemoved += _nodeChangeHandler;
}
private void OnListChanged(object sender, XmlNodeChangedEventArgs args)
{
lock (this)
{
if (_elemList != null)
{
XmlElementList el = (XmlElementList)_elemList.Target;
if (null != el)
{
el.ConcurrencyCheck(args);
}
else
{
_doc.NodeInserted -= _nodeChangeHandler;
_doc.NodeRemoved -= _nodeChangeHandler;
_elemList = null;
}
}
}
}
// This method is called from the finalizer of XmlElementList
internal void Unregister()
{
lock (this)
{
if (_elemList != null)
{
_doc.NodeInserted -= _nodeChangeHandler;
_doc.NodeRemoved -= _nodeChangeHandler;
_elemList = null;
}
}
}
}
}
| |
/*
* GifReader.cs - Implementation of the "DotGNU.Images.GifReader" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software, you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program, if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace DotGNU.Images
{
using System;
using System.IO;
internal sealed class GifReader
{
// Load a GIF image from the specified stream. The first 4 bytes
// have already been read and discarded. We always load GIF's
// as 8bpp because that makes it easier to handle decompression.
// GIF's with lower bit depths will be expanded appropriately.
public static void Load(Stream stream, Image image)
{
byte[] buffer = new byte [1024];
int logicalWidth, logicalHeight;
int flags, bitCount, numColors, tag;
int[] palette;
int transparentPixel;
int imageWidth, imageHeight;
Frame frame;
// Read the rest of the GIF header and validate it.
if(stream.Read(buffer, 0, 9) != 9)
{
throw new FormatException();
}
if((buffer[0] != (byte)'7' && buffer[0] != (byte)'9') ||
buffer[1] != (byte)'a')
{
throw new FormatException();
}
logicalWidth = Utils.ReadUInt16(buffer, 2);
logicalHeight = Utils.ReadUInt16(buffer, 4);
flags = buffer[6];
// buffer[7] is the background index, which we ignore.
// buffer[8] is the aspect ratio, which we ignore.
if(logicalWidth == 0 || logicalHeight == 0)
{
throw new FormatException();
}
// Set the global image information.
bitCount = (flags & 0x07) + 1;
numColors = (1 << bitCount);
image.Width = logicalWidth;
image.Height = logicalHeight;
image.PixelFormat = PixelFormat.Format8bppIndexed;
image.LoadFormat = Image.Gif;
// Read the global color table, if present.
if((flags & 0x80) != 0)
{
image.Palette = ReadGifPalette(stream, buffer, numColors);
}
// Process the image and extension blocks in the image.
transparentPixel = -1;
while(stream.Read(buffer, 0, 1) == 1)
{
tag = buffer[0];
if(tag == 0x2C)
{
// Read the image descriptor.
if(stream.Read(buffer, 0, 9) != 9)
{
throw new FormatException();
}
imageWidth = Utils.ReadUInt16(buffer, 4);
imageHeight = Utils.ReadUInt16(buffer, 6);
flags = buffer[8];
if(imageWidth == 0 || imageHeight == 0)
{
throw new FormatException();
}
frame = image.AddFrame(imageWidth, imageHeight,
image.PixelFormat);
frame.TransparentPixel = transparentPixel;
frame.OffsetX = Utils.ReadUInt16(buffer, 0);
frame.OffsetY = Utils.ReadUInt16(buffer, 2);
transparentPixel = -1;
// Read the local color table, if any.
if((flags & 0x80) != 0)
{
tag = (1 << ((flags & 0x07) + 1));
frame.Palette = ReadGifPalette
(stream, buffer, tag);
}
// Decompress the image into the frame.
Decompress(stream, buffer, frame, (flags & 0x40) != 0);
}
else if(tag == 0x21)
{
// Process an extension.
if(stream.Read(buffer, 0, 1) != 1)
{
throw new FormatException();
}
if(buffer[0] == (byte)0xF9)
{
// Graphic control extension sub-block.
if(stream.Read(buffer, 0, 1) != 1)
{
throw new FormatException();
}
tag = buffer[0];
if(stream.Read(buffer, 0, tag) != tag)
{
throw new FormatException();
}
if(tag >= 4)
{
if((buffer[0] & 0x01) != 0)
{
transparentPixel = buffer[3];
}
else
{
transparentPixel = -1;
}
}
}
// Skip the remaining extension sub-blocks.
SkipSubBlocks(stream, buffer);
}
else if(tag == 0x3B)
{
// End of the GIF file.
break;
}
else
{
// Invalid GIF file.
throw new FormatException();
}
}
}
// Read a palette from a GIF file.
private static int[] ReadGifPalette(Stream stream, byte[] buffer, int num)
{
int index;
int[] palette = new int [256];
if(stream.Read(buffer, 0, num * 3) != num * 3)
{
throw new FormatException();
}
for(index = 0; index < num && index < 256; ++index)
{
palette[index] =
(buffer[index * 3] << 16) |
(buffer[index * 3 + 1] << 8) |
(buffer[index * 3 + 2]);
}
return palette;
}
// Skip data sub blocks at the current position in a GIF file.
private static void SkipSubBlocks(Stream stream, byte[] buffer)
{
int size;
while(stream.Read(buffer, 0, 1) == 1)
{
size = buffer[0];
if(size == 0)
{
// End of the sub-block list.
return;
}
if(stream.Read(buffer, 0, size) != size)
{
throw new FormatException();
}
}
throw new FormatException();
}
// Helper class for reading codes from an LZW stream.
private class GifCodeHelper
{
// Internal state.
private Stream stream;
private byte[] buffer;
private int origCodeSize;
internal int codeSize;
private int codeMask;
internal int codeMax;
private int posn, len;
private int last, numBits;
// Constructor.
public GifCodeHelper(Stream stream, byte[] buffer, int codeSize)
{
this.stream = stream;
this.buffer = buffer;
this.origCodeSize = codeSize;
this.codeSize = codeSize;
this.codeMask = (1 << codeSize) - 1;
this.codeMax = (1 << codeSize);
this.posn = 0;
this.len = 0;
this.last = 0;
this.numBits = 0;
}
// Get the next code from the input stream.
public int GetCode()
{
// Read sufficient bits to make up a code value.
while(numBits < codeSize)
{
if(posn < len)
{
last |= (buffer[posn++] << numBits);
numBits += 8;
}
else
{
if(stream.Read(buffer, 0, 1) != 1)
{
throw new FormatException();
}
len = buffer[0];
if(len == 0)
{
// This is the end of the code stream.
return -1;
}
posn = 0;
if(stream.Read(buffer, 0, len) != len)
{
throw new FormatException();
}
}
}
// Extract the code and return it.
int code = last & codeMask;
last >>= codeSize;
numBits -= codeSize;
return code;
}
// Increase the code size.
public void IncreaseCodeSize()
{
++codeSize;
codeMask = (1 << codeSize) - 1;
codeMax = (1 << codeSize);
}
// Reset the code size to the original.
public void ResetCodeSize()
{
codeSize = origCodeSize;
codeMask = (1 << codeSize) - 1;
codeMax = (1 << codeSize);
}
}; // class GifCodeHelper
// Decompress the bytes corresponding to a GIF image.
private static void Decompress
(Stream stream, byte[] buffer, Frame frame, bool interlaced)
{
int minCodeSize, code;
int clearCode, endCode;
int nextCode, oldCode;
GifCodeHelper helper;
ushort[] prefix = new ushort [4096];
byte[] suffix = new byte [4096];
ushort[] length = new ushort [4096];
int offset, x, y, width, height;
int stride, lineChange, temp;
byte[] data;
byte[] stringbuf = new byte [4096];
int stringLen, tempCode, pass;
byte lastSuffix;
// Read the minimum code size and validate it.
if(stream.Read(buffer, 0, 1) != 1)
{
throw new FormatException();
}
minCodeSize = buffer[0];
if(minCodeSize < 2)
{
minCodeSize = 2;
}
else if(minCodeSize > 11)
{
minCodeSize = 11;
}
// Create a code helper.
helper = new GifCodeHelper(stream, buffer, minCodeSize + 1);
// Set the clear and end codes.
clearCode = (1 << minCodeSize);
endCode = clearCode + 1;
nextCode = endCode;
// Initialize the table.
for(code = 0; code < clearCode; ++code)
{
prefix[code] = (ushort)49428;
suffix[code] = (byte)code;
length[code] = (ushort)1;
}
// Initialize the image output parameters.
x = 0;
y = 0;
width = frame.Width;
height = frame.Height;
data = frame.Data;
pass = 0;
lineChange = (interlaced ? 8 : 1);
stride = frame.Stride;
// Process the codes in the input stream.
code = clearCode;
for(;;)
{
oldCode = code;
if((code = helper.GetCode()) == -1)
{
// We've run out of data blocks.
break;
}
else if(code == clearCode)
{
// Clear the code table and restart.
helper.ResetCodeSize();
nextCode = endCode;
continue;
}
else if(code == endCode)
{
// End of the GIF input stream: skip remaining blocks.
SkipSubBlocks(stream, buffer);
break;
}
else
{
// Sanity check for out of range codes.
if(code > nextCode && nextCode != 0)
{
code = 0;
}
// Update the next code in the table.
prefix[nextCode] = (ushort)oldCode;
length[nextCode] = (ushort)(length[oldCode] + 1);
// Form the full string for this code.
stringLen = length[code];
tempCode = code;
do
{
lastSuffix = suffix[tempCode];
--stringLen;
stringbuf[stringLen] = lastSuffix;
tempCode = prefix[tempCode];
}
while(stringLen > 0);
suffix[nextCode] = lastSuffix;
stringLen = length[code];
if(code == nextCode)
{
stringbuf[stringLen - 1] = lastSuffix;
}
// Copy the string into the actual image.
offset = 0;
while(stringLen > 0)
{
temp = width - x;
if(temp > stringLen)
{
temp = stringLen;
}
Array.Copy(stringbuf, offset, data,
y * stride + x, temp);
x += temp;
offset += temp;
stringLen -= temp;
if(x >= width)
{
x = 0;
y += lineChange;
while(y >= height && interlaced)
{
// Move on to the next interlace pass.
++pass;
if(pass == 1)
{
y = 4;
lineChange = 8;
}
else if(pass == 2)
{
y = 2;
lineChange = 4;
}
else if(pass == 3)
{
y = 1;
lineChange = 2;
}
else
{
break;
}
}
if(y >= height)
{
// Shouldn't happen - just in case.
y = 0;
}
}
}
// Set the suffix for the next code.
suffix[nextCode] = (byte)lastSuffix;
// Move on to the next code.
if(nextCode != clearCode)
{
++nextCode;
if(nextCode == helper.codeMax)
{
helper.IncreaseCodeSize();
if(helper.codeSize > 12)
{
helper.ResetCodeSize();
nextCode = clearCode;
}
}
}
}
}
}
}; // class GifReader
}; // namespace DotGNU.Images
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VisualLocalizer.Commands;
using VisualLocalizer.Translate;
using System.Globalization;
using VisualLocalizer.Settings;
using VisualLocalizer.Components;
using VisualLocalizer.Commands.Translate;
namespace VisualLocalizer.Gui {
/// <summary>
/// Dialog displayed during "Global translate" command. Enables user to select ResX files for translation and source and target languages.
/// </summary>
internal partial class GlobalTranslateForm : Form {
/// <summary>
/// List of ResX files, each having field declaring whether this file should be translated or not
/// </summary>
public List<GlobalTranslateProjectItem> ResxTargetList { get; private set; }
/// <summary>
/// Translation provider
/// </summary>
public TRANSLATE_PROVIDER Provider { get; private set; }
/// <summary>
/// Source and target language
/// </summary>
public SettingsObject.LanguagePair LanguagePair { get; private set; }
/// <summary>
/// List of cultures in the comboboxes
/// </summary>
private CultureInfo[] displayedCultures;
/// <summary>
/// Creates new instance
/// </summary>
/// <param name="resxTargetList">List of ResX file, all checked by default</param>
public GlobalTranslateForm(List<GlobalTranslateProjectItem> resxTargetList) {
if (resxTargetList == null) throw new ArgumentNullException("resxTargetList");
InitializeComponent();
this.Icon = VSPackage._400;
this.ResxTargetList = resxTargetList;
// initialize providers combobox
foreach (TRANSLATE_PROVIDER prov in Enum.GetValues(typeof(TRANSLATE_PROVIDER))) {
if (prov == TRANSLATE_PROVIDER.BING) {
if (!string.IsNullOrEmpty(SettingsObject.Instance.BingAppId)) providerBox.Items.Add(new ProviderItem(prov));
} else {
providerBox.Items.Add(new ProviderItem(prov));
}
}
providerBox.SelectedIndex = 0;
// add languages
displayedCultures = CultureInfo.GetCultures(CultureTypes.FrameworkCultures);
souceLanguageBox.Items.Add("(auto)"); // adds auto-detection option to list of source languages
foreach (var culture in displayedCultures) {
souceLanguageBox.Items.Add(culture.DisplayName);
targetLanguageBox.Items.Add(culture.DisplayName);
}
// add existing language pairs
foreach (var pair in SettingsObject.Instance.LanguagePairs) {
languagePairsBox.Items.Add(pair);
}
// add ResX files
foreach (var item in resxTargetList) {
resxListBox.Items.Add(item);
resxListBox.SetItemEnabled(resxListBox.Items.Count - 1, !item.Readonly); // readonly files are disabled
if (!item.Readonly) {
resxListBox.SetItemChecked(resxListBox.Items.Count - 1, true); // not-readonly files are checked by default
item.Checked = true;
}
}
useSavedPairBox.Checked = false;
useSavedPairBox.Checked = true;
useNewPairBox.Checked = true;
useNewPairBox.Checked = false;
}
/// <summary>
/// Updates check state of the resource file and updates enabled state of the translate button
/// </summary>
private void ResxListBox_SelectedValueChanged(object sender, EventArgs e) {
GlobalTranslateProjectItem item = (GlobalTranslateProjectItem)resxListBox.SelectedItem;
item.Checked = resxListBox.CheckedIndices.Contains(resxListBox.SelectedIndex);
translateButton.Enabled = resxListBox.CheckedIndices.Count > 0;
}
private bool ignoreNextCheckEvent = false;
/// <summary>
/// Called when "use new language pair" checkbox is checked. Enables/disables respective controls.
/// </summary>
private void UseNewPairBox_CheckedChanged(object sender, EventArgs e) {
label2.Enabled = useNewPairBox.Checked;
label3.Enabled = useNewPairBox.Checked;
souceLanguageBox.Enabled = useNewPairBox.Checked;
targetLanguageBox.Enabled = useNewPairBox.Checked;
addLanguagePairBox.Enabled = useNewPairBox.Checked;
if (ignoreNextCheckEvent) return;
ignoreNextCheckEvent = true; // to prevent infinite cycle
useSavedPairBox.Checked = !useNewPairBox.Checked;
ignoreNextCheckEvent = false;
}
/// <summary>
/// Called when "use existing language pair" checkbox is checked. Enables/disables respective controls.
/// </summary>
private void UseSavedPairBox_CheckedChanged(object sender, EventArgs e) {
label4.Enabled = useSavedPairBox.Checked;
languagePairsBox.Enabled = useSavedPairBox.Checked;
if (ignoreNextCheckEvent) return;
ignoreNextCheckEvent = true; // to prevent infinite cycle
useNewPairBox.Checked = !useSavedPairBox.Checked;
ignoreNextCheckEvent = false;
}
/// <summary>
/// Provider combobox value changed
/// </summary>
private void ProviderBox_SelectedIndexChanged(object sender, EventArgs e) {
Provider = ((ProviderItem)providerBox.SelectedItem).Provider;
}
/// <summary>
/// Selected language pair changed
/// </summary>
private void LanguagePairsBox_SelectedIndexChanged(object sender, EventArgs e) {
LanguagePair = (SettingsObject.LanguagePair)languagePairsBox.SelectedItem;
}
/// <summary>
/// Initializes the language pair and saves it if requested
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GlobalTranslateForm_FormClosing(object sender, FormClosingEventArgs e) {
if (DialogResult == DialogResult.OK) {
try {
if (useSavedPairBox.Checked) { // user selected "use existing language pair", but didn't specify the language pair
if (LanguagePair == null) throw new Exception("Saved language pair must be specified.");
}
if (useNewPairBox.Checked) { // user selected "use new language pair"
if (souceLanguageBox.SelectedIndex == -1 || targetLanguageBox.SelectedIndex == -1)
throw new Exception("Both source and target language must be specified.");
string srcLanguage = null, targetLanguage = null;
if (souceLanguageBox.SelectedIndex == 0) { // "auto" option selected
srcLanguage = string.Empty;
} else {
srcLanguage = displayedCultures[souceLanguageBox.SelectedIndex - 1].TwoLetterISOLanguageName;
}
targetLanguage = displayedCultures[targetLanguageBox.SelectedIndex].TwoLetterISOLanguageName;
// create new language pair from specified languages
LanguagePair = new SettingsObject.LanguagePair() { FromLanguage = srcLanguage, ToLanguage = targetLanguage };
// if user specified to remember the pair and such pair does not exist, save it
if (addLanguagePairBox.Checked && !SettingsObject.Instance.LanguagePairs.Contains(LanguagePair)) {
SettingsObject.Instance.LanguagePairs.Add(LanguagePair);
SettingsObject.Instance.NotifyPropertyChanged(CHANGE_CATEGORY.EDITOR);
}
}
} catch (Exception ex) {
e.Cancel = true;
VLOutputWindow.VisualLocalizerPane.WriteException(ex);
VisualLocalizer.Library.Components.MessageBox.ShowException(ex);
}
}
}
/// <summary>
/// Item in the list of translation providers
/// </summary>
private class ProviderItem {
public TRANSLATE_PROVIDER Provider;
public ProviderItem(TRANSLATE_PROVIDER prov) {
this.Provider = prov;
}
public override string ToString() {
return Provider.ToHumanForm();
}
}
}
}
| |
// /*
// SharpNative - C# to D Transpiler
// (C) 2014 Irio Systems
// */
#region Imports
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
#endregion
namespace SharpNative.Compiler
{
internal static class WriteAssignmentExpression
{
public static void Go(OutputWriter writer, AssignmentExpressionSyntax expression)
{
if (expression.OperatorToken.IsKind(SyntaxKind.AsKeyword))
{
var typeinfo = TypeProcessor.GetTypeInfo(expression.Right);
var isPtr = typeinfo.Type != null && typeinfo.Type.IsValueType ? "" : "";
writer.Write("cast( ");
writer.Write(TypeProcessor.ConvertType(expression.Right) + isPtr);
writer.Write(" )(");
Core.Write(writer, expression.Left);
writer.Write(")");
}
else if (expression.OperatorToken.IsKind(SyntaxKind.IsKeyword)) // isCast
{
var leftSymbolType = TypeProcessor.GetTypeInfo(expression.Left);
var rightSymbolType = TypeProcessor.GetTypeInfo(expression.Right);
if (leftSymbolType.Type.IsValueType)
{
writer.Write("IsCast!(Boxed!(");
writer.Write(TypeProcessor.ConvertType(expression.Right));
writer.Write("))");
writer.Write("(");
Core.Write(writer, expression.Left);
writer.Write(")");
// writer.Write("(cast(BOX!(");
// writer.Write(TypeProcessor.ConvertType(expression.Right));
// writer.Write(" ) )(Boxed!( " + TypeProcessor.ConvertType(leftSymbolType.Type));
// writer.Write(" )(");
// Core.Write(writer, expression.Left);
// writer.Write(")) is! null)");
//Todo improve this ... though its silly to do this in the first place
// writer.Write("(cast(BOX!(");
// writer.Write(TypeProcessor.ConvertType(expression.Right));
// writer.Write("))(Boxed!(" + TypeProcessor.ConvertType(leftSymbolType.Type));
// writer.Write(")(");
// Core.Write(writer, expression.Left);
// writer.Write(")) is! null)");
}
else if (rightSymbolType.Type.IsValueType)
{
writer.Write("IsCast!(Boxed!(");
writer.Write(TypeProcessor.ConvertType(expression.Right));
writer.Write("))");
writer.Write("(");
Core.Write(writer, expression.Left);
writer.Write(")");
// writer.Write("(cast(Boxed!( ");
// writer.Write(TypeProcessor.ConvertType(expression.Right));
// writer.Write(" ) )(");
// Core.Write(writer, expression.Left);
// writer.Write(") is! null)");
}
else
{
var typeinfo = TypeProcessor.GetTypeInfo(expression.Right);
var isPtr = typeinfo.Type != null && typeinfo.Type.IsValueType ? "" : "";
writer.Write("(IsCast!(");
writer.Write(TypeProcessor.ConvertType(expression.Right) + isPtr);
writer.Write(")(");
Core.Write(writer, expression.Left);
writer.Write("))");
}
}
else if (expression.OperatorToken.IsKind(SyntaxKind.QuestionQuestionToken))
{
writer.Write("((");
Core.Write(writer, expression.Left);
writer.Write(")!is null?(");
Core.Write(writer, expression.Left);
writer.Write("):(");
Core.Write(writer, expression.Right);
writer.Write("))");
}
else
{
// if (expression.Left is ElementAccessExpressionSyntax && IsAssignmentToken((SyntaxKind) expression.OperatorToken.RawKind))
// {
// var subExpr = expression.Left.As<ElementAccessExpressionSyntax>();
// var typeStr = TypeProcessor.GenericTypeName(TypeProcessor.GetTypeInfo(subExpr.Expression).Type);
//
//
//
// }
Action<ExpressionSyntax> write = e =>
{
var type = TypeProcessor.GetTypeInfo(e);
//Check for enums being converted to strings by string concatenation
var typeSymbol = type.Type ?? type.ConvertedType;
if (expression.OperatorToken.RawKind == (decimal) SyntaxKind.PlusToken &&
typeSymbol.TypeKind == TypeKind.Enum)
{
writer.Write(typeSymbol.ContainingNamespace.FullNameWithDot());
writer.Write(WriteType.TypeName(typeSymbol.As<INamedTypeSymbol>()));
writer.Write(".ToString(");
Core.Write(writer, e);
writer.Write(")");
}
else if (expression.OperatorToken.RawKind == (decimal) SyntaxKind.PlusToken &&
(typeSymbol.Name == "Nullable" && typeSymbol.ContainingNamespace.FullName() == "System" &&
typeSymbol.As<INamedTypeSymbol>().TypeArguments.Single().TypeKind == TypeKind.Enum))
{
var enumType = typeSymbol.As<INamedTypeSymbol>().TypeArguments.Single();
writer.Write(enumType.ContainingNamespace.FullNameWithDot());
writer.Write(WriteType.TypeName(enumType.As<INamedTypeSymbol>()));
writer.Write(".ToString(");
Core.Write(writer, e);
writer.Write(")");
}
else
Core.Write(writer, e);
};
var symbolInfoLeft = TypeProcessor.GetSymbolInfo(expression.Left);
var symbolInfoRight = TypeProcessor.GetSymbolInfo(expression.Right);
var leftExpressionType = TypeProcessor.GetTypeInfo(expression.Left);
var rightExpressionType = TypeProcessor.GetTypeInfo(expression.Right);
var boxLeft = leftExpressionType.Type != null &&
(leftExpressionType.Type.IsValueType && (leftExpressionType.ConvertedType.IsReferenceType));
var derefLeft = false;
// rightExpressionType.ConvertedType != null && rightExpressionType.ConvertedType.IsReferenceType;
var boxRight = rightExpressionType.ConvertedType != null &&
(rightExpressionType.Type != null && (rightExpressionType.Type.IsValueType &&
(rightExpressionType.ConvertedType.IsReferenceType)));
var derefRight = rightExpressionType.ConvertedType != null &&
(leftExpressionType.ConvertedType != null &&
!leftExpressionType.ConvertedType.IsReferenceType &&
rightExpressionType.ConvertedType.IsReferenceType);
var nullAssignment = expression.Right.ToFullString().Trim() == "null";
//Property calls will be fixed in a preprocessor step ... i.e. just call them
// var propertyLeft = symbolInfoLeft.Symbol != null && symbolInfoLeft.Symbol.Kind == SymbolKind.Property;
// var propertyRight = symbolInfoRight.Symbol != null && symbolInfoRight.Symbol.Kind == SymbolKind.Property;
if (nullAssignment)
{
Core.Write(writer, expression.Left);
writer.Write(" = ");
writer.Write("null");
return;
}
//Do we have an implicit converter, if so, use it
if (leftExpressionType.Type != rightExpressionType.Type)
{
// if (boxLeft)
{
bool useType = true;
//We should start with exact converters and then move to more generic convertors i.e. base class or integers which are implicitly convertible
var correctConverter = leftExpressionType.Type.GetImplicitCoversionOp(leftExpressionType.Type,
rightExpressionType.Type);
// initializerType.Type.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType);
if (correctConverter == null)
{
useType = false;
correctConverter =
rightExpressionType.Type.GetImplicitCoversionOp(leftExpressionType.Type,
rightExpressionType.Type);
//.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.Type && h.Parameters[0].Type == initializerType.ConvertedType);
}
if (correctConverter != null)
{
Core.Write(writer, expression.Left);
writer.Write(" = ");
if (useType)
{
writer.Write(TypeProcessor.ConvertType(leftExpressionType.Type) + "." + "op_Implicit_" +
TypeProcessor.ConvertType(correctConverter.ReturnType));
}
else
{
writer.Write(TypeProcessor.ConvertType(rightExpressionType.Type) + "." + "op_Implicit_" +
TypeProcessor.ConvertType(correctConverter.ReturnType));
}
writer.Write("(");
Core.Write(writer, expression.Right);
writer.Write(")");
return;
}
}
// if (shouldBox)
// {
// bool useType = true;
// var correctConverter =
// initializerType.Type.GetCoversionOp(initializerType.ConvertedType, initializerType.Type);//.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.ConvertedType && h.Parameters[0].Type == initializerType.Type);
//
// if (correctConverter == null)
// {
// useType = false;
// correctConverter =
// initializerType.ConvertedType.GetCoversionOp(initializerType.ConvertedType,
// initializerType.Type);
// //.GetMembers("op_Implicit").OfType<IMethodSymbol>().FirstOrDefault(h => h.ReturnType == initializerType.ConvertedType && h.Parameters[0].Type == initializerType.Type);
// }
//
// if (correctConverter != null)
// {
// if (useType)
// writer.Write(TypeProcessor.ConvertType(initializerType.Type) + "." + "op_Implicit(");
// else
// {
// writer.Write(TypeProcessor.ConvertType(initializerType.ConvertedType) + "." + "op_Implicit(");
//
// }
// Core.Write(writer, value);
// writer.Write(")");
// return;
// }
// }
}
if (expression.OperatorToken.CSharpKind() == SyntaxKind.PlusEqualsToken ||
expression.OperatorToken.CSharpKind() == SyntaxKind.MinusEqualsToken)
{
var isname = expression.Right is NameSyntax;
var nameexpression = expression.Right as NameSyntax;
var ismemberexpression = expression.Right is MemberAccessExpressionSyntax ||
(isname &&
TypeProcessor.GetSymbolInfo(expression.Right as NameSyntax).Symbol.Kind ==
SymbolKind.Method);
var isdelegateassignment = ismemberexpression &&
rightExpressionType.ConvertedType.TypeKind == TypeKind.Delegate;
var memberaccessexpression = expression.Right as MemberAccessExpressionSyntax;
var isstaticdelegate = isdelegateassignment &&
((memberaccessexpression != null &&
TypeProcessor.GetSymbolInfo(memberaccessexpression).Symbol.IsStatic) ||
(isname && TypeProcessor.GetSymbolInfo(nameexpression).Symbol.IsStatic));
if (isdelegateassignment)
{
write(expression.Left);
writer.Write(expression.OperatorToken.ToString());
var createNew = !(expression.Right is ObjectCreationExpressionSyntax);
var typeString = TypeProcessor.ConvertType(rightExpressionType.ConvertedType);
if (createNew)
{
if (rightExpressionType.ConvertedType.TypeKind == TypeKind.TypeParameter)
writer.Write(" __TypeNew!(" + typeString + ")(");
else
writer.Write("new " + typeString + "(");
}
var isStatic = isstaticdelegate;
if (isStatic)
writer.Write("__ToDelegate(");
writer.Write("&");
write(expression.Right);
//Core.Write (writer, expression.Right);
if (isStatic)
writer.Write(")");
if (createNew)
writer.Write(")");
return;
}
}
if (leftExpressionType.Type == null || rightExpressionType.Type == null)
{
// seems we have a null here obj==null or null==obj
if ((rightExpressionType.Type != null && rightExpressionType.Type.IsValueType) ||
(leftExpressionType.Type != null && leftExpressionType.Type.IsValueType))
{
writer.Write("/*value type cannot be null*/");
write(expression.Left);
switch (expression.OperatorToken.CSharpKind())
{
case SyntaxKind.EqualsEqualsToken:
writer.Write("!=");
break;
case SyntaxKind.NotEqualsExpression:
writer.Write("==");
break;
default:
writer.Write(expression.OperatorToken.ToString());
break;
}
write(expression.Right);
}
else
{
write(expression.Left);
if (expression.OperatorToken.CSharpKind() == SyntaxKind.EqualsEqualsToken)
writer.Write(" is ");
else if (expression.OperatorToken.CSharpKind() == SyntaxKind.ExclamationEqualsToken)
writer.Write(" !is ");
else
writer.Write(expression.OperatorToken.ToString());
write(expression.Right);
}
}
else
// if (symbolInfoLeft.Symbol != null && (symbolInfoLeft.Symbol.Kind == SymbolKind.Property && expression.OperatorToken.ValueText == "=")) //Assignment of property
// {
//
// write(expression.Left);
// writer.Write("(");
// write(expression.Right);
// writer.Write(")");
// }
// else
{
// writer.Write(derefLeft ? "*(" : "");
writer.Write(boxLeft ? "BOX!(" + TypeProcessor.ConvertType(leftExpressionType.Type) + ")(" : "");
write(expression.Left);
writer.Write(boxLeft ? ")" : "");
// writer.Write(derefLeft ? ")" : "");
writer.Write(expression.OperatorToken.ToString());
// writer.Write(derefRight ? "(" : "");
writer.Write(boxRight ? "BOX!(" + TypeProcessor.ConvertType(rightExpressionType.Type) + ")(" : "");
write(expression.Right);
writer.Write(boxRight ? ")" : "");
// writer.Write(derefRight ? ")" : "");
}
}
}
//TODO: Add full list here ...
private static readonly string[] OverloadableOperators =
{
"+", "-", "!", "~", "++", "--", //true, false
//These unary operators can be overloaded.
"+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>",
//These binary operators can be overloaded.
"==", "!=", "<", ">", "<=", ">=",
//The comparison operators can be overloaded
"&&", "||"
};
private static bool CouldBeNullString(SemanticModel model, ExpressionSyntax e)
{
while (true)
{
if (model.GetConstantValue(e).HasValue)
return false; //constants are never null
//For in-line conditions, just recurse on both results.
var cond = e as ConditionalExpressionSyntax;
if (cond != null)
return CouldBeNullString(model, cond.WhenTrue) || CouldBeNullString(model, cond.WhenFalse);
var paren = e as ParenthesizedExpressionSyntax;
if (paren != null)
{
e = paren.Expression;
continue;
}
var invoke = e as InvocationExpressionSyntax;
if (invoke == null)
return true;
var methodSymbol = ModelExtensions.GetSymbolInfo(model, invoke).Symbol;
//Hard-code some well-known functions as an optimization
if (methodSymbol.Name == "HtmlEncode" && methodSymbol.ContainingNamespace.FullName() == "System.Web")
return false;
return methodSymbol.Name != "ToString";
}
}
private static bool IsException(ITypeSymbol typeSymbol)
{
while (true)
{
if (typeSymbol.Name == "Exception" && typeSymbol.ContainingNamespace.FullName() == "System")
return true;
if (typeSymbol.BaseType == null)
return false;
typeSymbol = typeSymbol.BaseType;
}
}
private static bool IsAssignmentToken(SyntaxKind syntaxKind)
{
switch (syntaxKind)
{
case SyntaxKind.EqualsToken:
case SyntaxKind.PlusEqualsToken:
case SyntaxKind.MinusEqualsToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.AsteriskEqualsToken:
return true;
default:
return false;
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Data.Common
{
partial class DbConnectionOptions
{
#if DEBUG
/*private const string ConnectionStringPatternV1 =
"[\\s;]*"
+"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)"
+ "\\s*=(?!=)\\s*"
+"(?<value>("
+ "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")"
+ "|"
+ "(" + "'" + "([^']|'')*" + "'" + ")"
+ "|"
+ "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")"
+ "))"
+ "[\\s;]*"
;*/
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
+ "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
+ "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private const string ConnectionStringPatternOdbc = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}])+)" // allow any visible character for keyname except '='
+ "\\s*=\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\\{([^\\}\u0000]|\\}\\})*\\})" // quoted string, starts with { and ends with }
+ "|"
+ "((?![\\{\\s])" // unquoted value must not start with { or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ ")" // although the spec does not allow {}
// embedded within a value, the retail code does.
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static readonly Regex s_connectionStringRegexOdbc = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null
private const string ConnectionStringQuoteValuePattern = "^[^\"'=;\\s\\p{Cc}]*$"; // generally do not quote the value if it matches the pattern
private const string ConnectionStringQuoteOdbcValuePattern = "^\\{([^\\}\u0000]|\\}\\})*\\}$"; // do not quote odbc value if it matches this pattern
internal const string DataDirectory = "|datadirectory|";
private static readonly Regex s_connectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern, RegexOptions.Compiled);
private static readonly Regex s_connectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern, RegexOptions.Compiled);
private static readonly Regex s_connectionStringQuoteValueRegex = new Regex(ConnectionStringQuoteValuePattern, RegexOptions.Compiled);
private static readonly Regex s_connectionStringQuoteOdbcValueRegex = new Regex(ConnectionStringQuoteOdbcValuePattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
// connection string common keywords
private static class KEY
{
internal const string Integrated_Security = "integrated security";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string User_ID = "user id";
}
// known connection string common synonyms
private static class SYNONYM
{
internal const string Pwd = "pwd";
internal const string UID = "uid";
}
private readonly string _usersConnectionString;
private readonly Dictionary<string, string> _parsetable;
internal readonly NameValuePair _keyChain;
internal readonly bool _hasPasswordKeyword;
public string UsersConnectionString(bool hidePassword) =>
UsersConnectionString(hidePassword, false);
private string UsersConnectionString(bool hidePassword, bool forceHidePassword)
{
string connectionString = _usersConnectionString;
if (_hasPasswordKeyword && (forceHidePassword || (hidePassword && !HasPersistablePassword)))
{
ReplacePasswordPwd(out connectionString, false);
}
return connectionString ?? string.Empty;
}
internal bool HasPersistablePassword => _hasPasswordKeyword ?
ConvertValueToBoolean(KEY.Persist_Security_Info, false) :
true; // no password means persistable password so we don't have to munge
public bool ConvertValueToBoolean(string keyName, bool defaultValue)
{
string value;
return _parsetable.TryGetValue(keyName, out value) ?
ConvertValueToBooleanInternal(keyName, value) :
defaultValue;
}
internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue)
{
if (CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else
{
string tmp = stringValue.Trim(); // Remove leading & trailing whitespace.
if (CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else
{
throw ADP.InvalidConnectionOptionValue(keyName);
}
}
}
private static bool CompareInsensitiveInvariant(string strvalue, string strconst) =>
(0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst));
[System.Diagnostics.Conditional("DEBUG")]
static partial void DebugTraceKeyValuePair(string keyname, string keyvalue, Dictionary<string, string> synonyms);
private static string GetKeyName(StringBuilder buffer)
{
int count = buffer.Length;
while ((0 < count) && char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture);
}
private static string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
{
int count = buffer.Length;
int index = 0;
if (trimWhitespace)
{
while ((index < count) && char.IsWhiteSpace(buffer[index]))
{
index++; // leading whitespace
}
while ((0 < count) && char.IsWhiteSpace(buffer[count - 1]))
{
count--; // trailing whitespace
}
}
return buffer.ToString(index, count - index);
}
// transition states used for parsing
private enum ParserState
{
NothingYet = 1, //start point
Key,
KeyEqual,
KeyEnd,
UnquotedValue,
DoubleQuoteValue,
DoubleQuoteValueQuote,
SingleQuoteValue,
SingleQuoteValueQuote,
BraceQuoteValue,
BraceQuoteValueQuote,
QuotedValueEnd,
NullTermination,
};
internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue)
{
int startposition = currentPosition;
buffer.Length = 0;
keyname = null;
keyvalue = null;
char currentChar = '\0';
ParserState parserState = ParserState.NothingYet;
int length = connectionString.Length;
for (; currentPosition < length; ++currentPosition)
{
currentChar = connectionString[currentPosition];
switch (parserState)
{
case ParserState.NothingYet: // [\\s;]*
if ((';' == currentChar) || char.IsWhiteSpace(currentChar))
{
continue;
}
if ('\0' == currentChar)
{ parserState = ParserState.NullTermination; continue; }
if (char.IsControl(currentChar))
{ throw ADP.ConnectionStringSyntax(startposition); }
startposition = currentPosition;
if ('=' != currentChar)
{
parserState = ParserState.Key;
break;
}
else
{
parserState = ParserState.KeyEqual;
continue;
}
case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
if ('=' == currentChar)
{ parserState = ParserState.KeyEqual; continue; }
if (char.IsWhiteSpace(currentChar))
{ break; }
if (char.IsControl(currentChar))
{ throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.KeyEqual: // \\s*=(?!=)\\s*
if (!useOdbcRules && '=' == currentChar)
{ parserState = ParserState.Key; break; }
keyname = GetKeyName(buffer);
if (string.IsNullOrEmpty(keyname))
{ throw ADP.ConnectionStringSyntax(startposition); }
buffer.Length = 0;
parserState = ParserState.KeyEnd;
goto case ParserState.KeyEnd;
case ParserState.KeyEnd:
if (char.IsWhiteSpace(currentChar))
{ continue; }
if (useOdbcRules)
{
if ('{' == currentChar)
{ parserState = ParserState.BraceQuoteValue; break; }
}
else
{
if ('\'' == currentChar)
{ parserState = ParserState.SingleQuoteValue; continue; }
if ('"' == currentChar)
{ parserState = ParserState.DoubleQuoteValue; continue; }
}
if (';' == currentChar)
{ goto ParserExit; }
if ('\0' == currentChar)
{ goto ParserExit; }
if (char.IsControl(currentChar))
{ throw ADP.ConnectionStringSyntax(startposition); }
parserState = ParserState.UnquotedValue;
break;
case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
if (char.IsWhiteSpace(currentChar))
{ break; }
if (char.IsControl(currentChar) || ';' == currentChar)
{ goto ParserExit; }
break;
case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")"
if ('"' == currentChar)
{ parserState = ParserState.DoubleQuoteValueQuote; continue; }
if ('\0' == currentChar)
{ throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.DoubleQuoteValueQuote:
if ('"' == currentChar)
{ parserState = ParserState.DoubleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')"
if ('\'' == currentChar)
{ parserState = ParserState.SingleQuoteValueQuote; continue; }
if ('\0' == currentChar)
{ throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.SingleQuoteValueQuote:
if ('\'' == currentChar)
{ parserState = ParserState.SingleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})"
if ('}' == currentChar)
{ parserState = ParserState.BraceQuoteValueQuote; break; }
if ('\0' == currentChar)
{ throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.BraceQuoteValueQuote:
if ('}' == currentChar)
{ parserState = ParserState.BraceQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.QuotedValueEnd:
if (char.IsWhiteSpace(currentChar))
{ continue; }
if (';' == currentChar)
{ goto ParserExit; }
if ('\0' == currentChar)
{ parserState = ParserState.NullTermination; continue; }
throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote
case ParserState.NullTermination: // [\\s;\u0000]*
if ('\0' == currentChar)
{ continue; }
if (char.IsWhiteSpace(currentChar))
{ continue; }
throw ADP.ConnectionStringSyntax(currentPosition);
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
}
buffer.Append(currentChar);
}
ParserExit:
switch (parserState)
{
case ParserState.Key:
case ParserState.DoubleQuoteValue:
case ParserState.SingleQuoteValue:
case ParserState.BraceQuoteValue:
// keyword not found/unbalanced double/single quote
throw ADP.ConnectionStringSyntax(startposition);
case ParserState.KeyEqual:
// equal sign at end of line
keyname = GetKeyName(buffer);
if (string.IsNullOrEmpty(keyname))
{ throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.UnquotedValue:
// unquoted value at end of line
keyvalue = GetKeyValue(buffer, true);
char tmpChar = keyvalue[keyvalue.Length - 1];
if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar)))
{
throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc
}
break;
case ParserState.DoubleQuoteValueQuote:
case ParserState.SingleQuoteValueQuote:
case ParserState.BraceQuoteValueQuote:
case ParserState.QuotedValueEnd:
// quoted value at end of line
keyvalue = GetKeyValue(buffer, false);
break;
case ParserState.NothingYet:
case ParserState.KeyEnd:
case ParserState.NullTermination:
// do nothing
break;
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
}
if ((';' == currentChar) && (currentPosition < connectionString.Length))
{
currentPosition++;
}
return currentPosition;
}
private static bool IsValueValidInternal(string keyvalue)
{
if (null != keyvalue)
{
#if DEBUG
bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue);
Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex");
#endif
return (-1 == keyvalue.IndexOf('\u0000'));
}
return true;
}
private static bool IsKeyNameValid(string keyname)
{
if (null != keyname)
{
#if DEBUG
bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname);
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
#endif
return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
}
return false;
}
#if DEBUG
private static Dictionary<string, string> SplitConnectionString(string connectionString, Dictionary<string, string> synonyms, bool firstKey)
{
var parsetable = new Dictionary<string, string>();
Regex parser = (firstKey ? s_connectionStringRegexOdbc : s_connectionStringRegex);
const int KeyIndex = 1, ValueIndex = 2;
Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");
if (null != connectionString)
{
Match match = parser.Match(connectionString);
if (!match.Success || (match.Length != connectionString.Length))
{
throw ADP.ConnectionStringSyntax(match.Length);
}
int indexValue = 0;
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach (Capture keypair in match.Groups[KeyIndex].Captures)
{
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture);
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length)
{
if (!firstKey)
{
switch (keyvalue[0])
{
case '\"':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
break;
case '\'':
keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
break;
default:
break;
}
}
}
else
{
keyvalue = null;
}
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
string synonym;
string realkeyname = null != synonyms ?
(synonyms.TryGetValue(keyname, out synonym) ? synonym : null) : keyname;
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.ContainsKey(realkeyname))
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
}
}
return parsetable;
}
private static void ParseComparison(Dictionary<string, string> parsetable, string connectionString, Dictionary<string, string> synonyms, bool firstKey, Exception e)
{
try
{
var parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey);
foreach (var entry in parsedvalues)
{
string keyname = entry.Key;
string value1 = entry.Value;
string value2;
bool parsetableContainsKey = parsetable.TryGetValue(keyname, out value2);
Debug.Assert(parsetableContainsKey, $"{nameof(ParseInternal)} code vs. regex mismatch keyname <{keyname}>");
Debug.Assert(value1 == value2, $"{nameof(ParseInternal)} code vs. regex mismatch keyvalue <{value1}> <{value2}>");
}
}
catch (ArgumentException f)
{
if (null != e)
{
string msg1 = e.Message;
string msg2 = f.Message;
const string KeywordNotSupportedMessagePrefix = "Keyword not supported:";
const string WrongFormatMessagePrefix = "Format of the initialization string";
bool isEquivalent = (msg1 == msg2);
if (!isEquivalent)
{
// We also accept cases were Regex parser (debug only) reports "wrong format" and
// retail parsing code reports format exception in different location or "keyword not supported"
if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal))
{
isEquivalent = true;
}
}
}
Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">");
}
else
{
Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
}
e = null;
}
if (null != e)
{
Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
}
}
#endif
private static NameValuePair ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms, bool firstKey)
{
Debug.Assert(null != connectionString, "null connectionstring");
StringBuilder buffer = new StringBuilder();
NameValuePair localKeychain = null, keychain = null;
#if DEBUG
try
{
#endif
int nextStartPosition = 0;
int endPosition = connectionString.Length;
while (nextStartPosition < endPosition)
{
int startPosition = nextStartPosition;
string keyname, keyvalue;
nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
if (string.IsNullOrEmpty(keyname))
{
// if (nextStartPosition != endPosition) { throw; }
break;
}
#if DEBUG
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
string synonym;
string realkeyname = null != synonyms ?
(synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
keyname;
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.ContainsKey(realkeyname))
{
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
if (null != localKeychain)
{
localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
else if (buildChain)
{ // first time only - don't contain modified chain from UDL file
keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
}
#if DEBUG
}
catch (ArgumentException e)
{
ParseComparison(parsetable, connectionString, synonyms, firstKey, e);
throw;
}
ParseComparison(parsetable, connectionString, synonyms, firstKey, null);
#endif
return keychain;
}
internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword)
{
bool expanded = false;
int copyPosition = 0;
NameValuePair head = null, tail = null, next = null;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for (NameValuePair current = _keyChain; null != current; current = current.Next)
{
if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name))
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
if (fakePassword)
{
next = new NameValuePair(current.Name, current.Value, current.Length);
}
}
else if (fakePassword)
{
// replace user password/pwd value with *
const string equalstar = "=*;";
builder.Append(current.Name).Append(equalstar);
next = new NameValuePair(current.Name, "*", current.Name.Length + equalstar.Length);
expanded = true;
}
else
{
// drop the password/pwd completely in returning for user
expanded = true;
}
if (fakePassword)
{
if (null != tail)
{
tail = tail.Next = next;
}
else
{
tail = head = next;
}
}
copyPosition += current.Length;
}
Debug.Assert(expanded, "password/pwd was not removed");
constr = builder.ToString();
return head;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using BitbucketSharp.Controllers;
using RestSharp;
using RestSharp.Deserializers;
using BitbucketSharp.Models;
using RestSharp.Contrib;
using System.Threading.Tasks;
using RestSharp.Serializers;
namespace BitbucketSharp
{
public class Client
{
public const string ApiUrl = "https://bitbucket.org/api/1.0/";
public const string ApiUrl2 = "https://bitbucket.org/api/2.0/";
public static string Url = "https://bitbucket.org";
private readonly RestClient _client;
/// <summary>
/// The username we are logging as as.
/// Instead of passing in the account's username everywhere we'll just set it once here.
/// </summary>
public string Username { get; set; }
/// <summary>
/// The user account
/// </summary>
public AccountController Account
{
get { return new AccountController(this); }
}
/// <summary>
/// The users on Bitbucket
/// </summary>
public UsersController Users
{
get { return new UsersController(this); }
}
/// <summary>
/// The repositories on Bitbucket
/// </summary>
public RepositoriesController Repositories
{
get { return new RepositoriesController(this); }
}
/// <summary>
/// Gets the teams.
/// </summary>
public TeamsController Teams
{
get { return new TeamsController(this); }
}
/// <summary>
/// Gets or sets the timeout.
/// </summary>
/// <value>
/// The timeout.
/// </value>
public int Timeout
{
get { return _client.Timeout; }
set { _client.Timeout = value; }
}
/// <summary>
/// Gets or sets the retries for No Content errors
/// </summary>
public uint Retries { get; set; }
/// <summary>
/// Constructor
/// </summary>
private Client()
{
Retries = 3;
_client = new RestClient() { FollowRedirects = true, Timeout = 1000 * 30 };
}
/// <summary>
/// Constructs the client using oauth identifiers
/// </summary>
/// <param name="consumerKey"></param>
/// <param name="consumerSecret"></param>
/// <param name="oauth_token"></param>
/// <param name="oauth_token_secret"></param>
public Client(string consumerKey, string consumerSecret, string oauth_token, string oauth_token_secret)
: this()
{
_client.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauth_token, oauth_token_secret);
}
/// <summary>
/// Constructs the client using username / password
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
public Client(string username, string password)
: this()
{
_client.Authenticator = new HttpBasicAuthenticator(username, password);
Username = username;
}
/// <summary>
/// Create a Client object and request the user's info to validate credentials
/// </summary>
/// <param name="username">The username</param>
/// <param name="password">The password</param>
/// <returns></returns>
public static Client BasicLogin(string username, string password, out UsersModel userInfo)
{
var client = new Client(username, password);
userInfo = client.Account.GetInfo();
client.Username = userInfo.User.Username;
return client;
}
/// <summary>
/// Create a Client object and request the user's info to validate credentials
/// </summary>
public static Client BearerLogin(string token, out UsersModel userInfo)
{
var client = new Client();
client._client.Authenticator = new BeaererAuthentication(token);
userInfo = client.Account.GetInfo(true);
client.Username = userInfo.User.Username;
return client;
}
private class BeaererAuthentication : IAuthenticator
{
private readonly string _token;
public BeaererAuthentication(string token)
{
_token = token;
}
public void Authenticate(IRestClient client, IRestRequest request)
{
request.AddHeader("Authorization", "Bearer " + _token);
}
}
/// <summary>
/// Create a Client object with OAuth crednetials and a request the user's info to validate credentials
/// </summary>
/// <param name="consumerKey"></param>
/// <param name="consumerSecret"></param>
/// <param name="oauth_token"></param>
/// <param name="oauth_token_secret"></param>
/// <param name="userInfo"></param>
/// <returns></returns>
public static Client OAuthLogin(string consumerKey, string consumerSecret, string oauth_token, string oauth_token_secret, out UsersModel userInfo)
{
var client = new Client(consumerKey, consumerSecret, oauth_token, oauth_token_secret);
userInfo = client.Account.GetInfo();
client.Username = userInfo.User.Username;
return client;
}
/// <summary>
/// Run through the OAuth login process to obtain an auth token and secret. Then login using that information and request the user's
/// info to validate credentials
/// </summary>
/// <param name="consumerKey"></param>
/// <param name="consumerSecret"></param>
/// <param name="redirectAction"></param>
/// <param name="oauth_token"></param>
/// <param name="oauth_token_secret"></param>
/// <param name="userInfo"></param>
/// <returns></returns>
public static Client OAuthLogin(string consumerKey, string consumerSecret, Func<Uri, string> redirectAction, out string oauth_token, out string oauth_token_secret, out UsersModel userInfo)
{
var client = new RestClient(ApiUrl);
client.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
var request = new RestRequest("oauth/request_token", Method.POST);
var response = client.Execute(request);
var qs = HttpUtility.ParseQueryString(response.Content);
oauth_token = qs["oauth_token"];
oauth_token_secret = qs["oauth_token_secret"];
request = new RestRequest("oauth/authenticate");
request.AddParameter("oauth_token", oauth_token);
var uri = new Uri(client.BuildUri(request).ToString());
var verifier = redirectAction(uri);
request = new RestRequest("oauth/access_token", Method.POST);
client.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForAccessToken(
consumerKey, consumerSecret, oauth_token, oauth_token_secret, verifier
);
response = client.Execute(request);
qs = HttpUtility.ParseQueryString(response.Content);
oauth_token = qs["oauth_token"];
oauth_token_secret = qs["oauth_token_secret"];
return OAuthLogin(consumerKey, consumerSecret, oauth_token, oauth_token_secret, out userInfo);
}
public static OAuthResponse RefreshToken(string clientId, string clientSecret, string refreshToken)
{
var client = new RestClient();
client.Authenticator = new HttpBasicAuthenticator(clientId, clientSecret);
var request = new RestRequest("https://bitbucket.org/site/oauth2/access_token", Method.POST);
request.AddParameter("grant_type", "refresh_token");
request.AddParameter("refresh_token", refreshToken);
var response = client.Execute<OAuthResponse>(request);
return response.Data;
}
public static OAuthResponse GetAuthorizationCode(string clientId, string clientSecret, string code)
{
var client = new RestClient() { Authenticator = new HttpBasicAuthenticator(clientId, clientSecret) };
var request = new RestRequest("https://bitbucket.org/site/oauth2/access_token", Method.POST);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", code);
return client.Execute<OAuthResponse>(request).Data;
}
/// <summary>
/// Makes a 'GET' request to the server using a URI
/// </summary>
/// <typeparam name="T">The type of object the response should be deserialized ot</typeparam>
/// <param name="uri">The URI to request information from</param>
/// <param name="forceCacheInvalidation"></param>
/// <returns>An object with response data</returns>
public T Get<T>(String uri, bool forceCacheInvalidation = false, string baseUri = ApiUrl) where T : class
{
return Request<T>(uri, baseUri: baseUri);
}
/// <summary>
/// Makes a 'PUT' request to the server
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="data"></param>
/// <returns></returns>
public T Put<T>(string uri, Dictionary<string, string> data = null, string baseUri = ApiUrl)
{
return Request<T>(uri, Method.PUT, data, baseUri);
}
/// <summary>
/// Makes a 'PUT' request to the server
/// </summary>
/// <param name="uri"></param>
/// <param name="data"></param>
public void Put(string uri, Dictionary<string, string> data = null, string baseUri = ApiUrl)
{
Request(uri, Method.PUT, data, baseUri);
}
/// <summary>
/// Makes a 'POST' request to the server
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="data"></param>
/// <returns></returns>
public T Post<T>(string uri, Dictionary<string, string> data, string baseUri = ApiUrl)
{
return Request<T>(uri, Method.POST, data, baseUri);
}
/// <summary>
/// Makes a 'POST' request to the server without a response
/// </summary>
/// <param name="uri"></param>
/// <param name="data"></param>
/// <returns></returns>
public void Post(string uri, Dictionary<string, string> data, string baseUri = ApiUrl)
{
Request(uri, Method.POST, data, baseUri);
}
/// <summary>
/// Makes a 'DELETE' request to the server
/// </summary>
/// <param name="uri"></param>
public void Delete(string uri, string baseUri = ApiUrl)
{
Request(uri, Method.DELETE, baseUri: baseUri);
}
/// <summary>
/// Makes a request to the server expecting a response
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uri"></param>
/// <param name="data"></param>
/// <param name="method"></param>
/// <returns></returns>
public T Request<T>(string uri, Method method = Method.GET, Dictionary<string, string> data = null, string baseUri = ApiUrl)
{
var response = ExecuteRequest(new Uri(new Uri(baseUri), uri), method, data);
var d = new JsonDeserializer();
return d.Deserialize<T>(response);
}
/// <summary>
/// Dummy thing.. for now
/// </summary>
/// <param name="uri">URI.</param>
/// <param name="method">Method.</param>
/// <param name="data">Data.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T Request2<T>(string uri, Method method = Method.GET, Dictionary<string, string> data = null)
{
var response = ExecuteRequest(new Uri(uri), method, data);
var d = new JsonDeserializer();
return d.Deserialize<T>(response);
}
/// <summary>
/// Makes a request to the server but does not expect a response.
/// </summary>
/// <param name="uri"></param>
/// <param name="method"></param>
/// <param name="data"></param>
public void Request(string uri, Method method = Method.GET, Dictionary<string, string> data = null, string baseUri = ApiUrl)
{
ExecuteRequest(new Uri(new Uri(baseUri), uri), method, data);
}
/// <summary>
/// Executes a request to the server
/// </summary>
/// <param name="uri"></param>
/// <param name="method"></param>
/// <param name="data"></param>
/// <returns></returns>
internal IRestResponse ExecuteRequest(Uri uri, Method method, Dictionary<string, string> data)
{
if (uri == null)
throw new ArgumentNullException("uri");
var request = new RestRequest(method);
request.Resource = uri.AbsoluteUri;
if (data != null)
foreach (var hd in data)
request.AddParameter(hd.Key, hd.Value);
//Puts without any data must be marked as having no content!
if (method == Method.PUT && data == null)
request.AddHeader("Content-Length", "0");
for (var i = 0; i < Retries + 1; i++)
{
IRestResponse response = _client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
//A special case for deletes
if (request.Method == Method.DELETE && response.StatusCode == HttpStatusCode.NoContent)
{
//Do nothing. This is a special case...
}
else if (response.StatusCode == 0)
{
continue;
}
else
{
if (!string.IsNullOrEmpty(response.Content))
{
var errorResponse = new JsonDeserializer().Deserialize<ErrorResponse>(response);
var message = errorResponse?.Error?.Message;
throw StatusCodeException.FactoryCreate(response.StatusCode, message);
}
throw StatusCodeException.FactoryCreate(response.StatusCode);
}
}
//Return the response
return response;
}
throw new InvalidOperationException("Unable to execute request. No connection available!");
}
/// <summary>
/// Executes a request to the server
/// </summary>
internal IRestResponse ExecuteRequest(IRestRequest request)
{
var response = _client.Execute(request);
if (response.ErrorException != null)
throw response.ErrorException;
return response;
}
}
public class OAuthResponse
{
public string AccessToken { get; set; }
public string Scopes { get; set; }
public string RefreshToken { get; set; }
}
public class ErrorResponse
{
public ErrorDetails Error { get; set ;}
}
public class ErrorDetails
{
public string Message { get; set; }
public string Detail { get; set; }
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
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.Area120.Tables.V1Alpha1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTablesServiceClientTest
{
[xunit::FactAttribute]
public void GetTableRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
Table expectedResponse = new Table
{
TableName = TableName.FromTable("[TABLE]"),
DisplayName = "display_name137f65c2",
Columns =
{
new ColumnDescription(),
},
};
mockGrpcClient.Setup(x => x.GetTable(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Table response = client.GetTable(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTableRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
Table expectedResponse = new Table
{
TableName = TableName.FromTable("[TABLE]"),
DisplayName = "display_name137f65c2",
Columns =
{
new ColumnDescription(),
},
};
mockGrpcClient.Setup(x => x.GetTableAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Table>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Table responseCallSettings = await client.GetTableAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Table responseCancellationToken = await client.GetTableAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTable()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
Table expectedResponse = new Table
{
TableName = TableName.FromTable("[TABLE]"),
DisplayName = "display_name137f65c2",
Columns =
{
new ColumnDescription(),
},
};
mockGrpcClient.Setup(x => x.GetTable(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Table response = client.GetTable(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTableAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
Table expectedResponse = new Table
{
TableName = TableName.FromTable("[TABLE]"),
DisplayName = "display_name137f65c2",
Columns =
{
new ColumnDescription(),
},
};
mockGrpcClient.Setup(x => x.GetTableAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Table>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Table responseCallSettings = await client.GetTableAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Table responseCancellationToken = await client.GetTableAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTableResourceNames()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
Table expectedResponse = new Table
{
TableName = TableName.FromTable("[TABLE]"),
DisplayName = "display_name137f65c2",
Columns =
{
new ColumnDescription(),
},
};
mockGrpcClient.Setup(x => x.GetTable(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Table response = client.GetTable(request.TableName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTableResourceNamesAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
Table expectedResponse = new Table
{
TableName = TableName.FromTable("[TABLE]"),
DisplayName = "display_name137f65c2",
Columns =
{
new ColumnDescription(),
},
};
mockGrpcClient.Setup(x => x.GetTableAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Table>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Table responseCallSettings = await client.GetTableAsync(request.TableName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Table responseCancellationToken = await client.GetTableAsync(request.TableName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkspaceRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
Workspace expectedResponse = new Workspace
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
DisplayName = "display_name137f65c2",
Tables = { new Table(), },
};
mockGrpcClient.Setup(x => x.GetWorkspace(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Workspace response = client.GetWorkspace(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkspaceRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
Workspace expectedResponse = new Workspace
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
DisplayName = "display_name137f65c2",
Tables = { new Table(), },
};
mockGrpcClient.Setup(x => x.GetWorkspaceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workspace>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Workspace responseCallSettings = await client.GetWorkspaceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workspace responseCancellationToken = await client.GetWorkspaceAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkspace()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
Workspace expectedResponse = new Workspace
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
DisplayName = "display_name137f65c2",
Tables = { new Table(), },
};
mockGrpcClient.Setup(x => x.GetWorkspace(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Workspace response = client.GetWorkspace(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkspaceAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
Workspace expectedResponse = new Workspace
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
DisplayName = "display_name137f65c2",
Tables = { new Table(), },
};
mockGrpcClient.Setup(x => x.GetWorkspaceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workspace>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Workspace responseCallSettings = await client.GetWorkspaceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workspace responseCancellationToken = await client.GetWorkspaceAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkspaceResourceNames()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
Workspace expectedResponse = new Workspace
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
DisplayName = "display_name137f65c2",
Tables = { new Table(), },
};
mockGrpcClient.Setup(x => x.GetWorkspace(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Workspace response = client.GetWorkspace(request.WorkspaceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkspaceResourceNamesAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
Workspace expectedResponse = new Workspace
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
DisplayName = "display_name137f65c2",
Tables = { new Table(), },
};
mockGrpcClient.Setup(x => x.GetWorkspaceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workspace>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Workspace responseCallSettings = await client.GetWorkspaceAsync(request.WorkspaceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workspace responseCancellationToken = await client.GetWorkspaceAsync(request.WorkspaceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRowRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
View = View.ColumnIdView,
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.GetRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.GetRow(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRowRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
View = View.ColumnIdView,
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.GetRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.GetRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.GetRowAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRow()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.GetRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.GetRow(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRowAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.GetRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.GetRowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.GetRowAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRowResourceNames()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.GetRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.GetRow(request.RowName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRowResourceNamesAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.GetRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.GetRowAsync(request.RowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.GetRowAsync(request.RowName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateRowRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
CreateRowRequest request = new CreateRowRequest
{
Parent = "parent7858e4d0",
Row = new Row(),
View = View.ColumnIdView,
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.CreateRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.CreateRow(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateRowRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
CreateRowRequest request = new CreateRowRequest
{
Parent = "parent7858e4d0",
Row = new Row(),
View = View.ColumnIdView,
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.CreateRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.CreateRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.CreateRowAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateRow()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
CreateRowRequest request = new CreateRowRequest
{
Parent = "parent7858e4d0",
Row = new Row(),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.CreateRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.CreateRow(request.Parent, request.Row);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateRowAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
CreateRowRequest request = new CreateRowRequest
{
Parent = "parent7858e4d0",
Row = new Row(),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.CreateRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.CreateRowAsync(request.Parent, request.Row, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.CreateRowAsync(request.Parent, request.Row, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchCreateRowsRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
BatchCreateRowsRequest request = new BatchCreateRowsRequest
{
Parent = "parent7858e4d0",
Requests =
{
new CreateRowRequest(),
},
};
BatchCreateRowsResponse expectedResponse = new BatchCreateRowsResponse { Rows = { new Row(), }, };
mockGrpcClient.Setup(x => x.BatchCreateRows(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
BatchCreateRowsResponse response = client.BatchCreateRows(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchCreateRowsRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
BatchCreateRowsRequest request = new BatchCreateRowsRequest
{
Parent = "parent7858e4d0",
Requests =
{
new CreateRowRequest(),
},
};
BatchCreateRowsResponse expectedResponse = new BatchCreateRowsResponse { Rows = { new Row(), }, };
mockGrpcClient.Setup(x => x.BatchCreateRowsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchCreateRowsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
BatchCreateRowsResponse responseCallSettings = await client.BatchCreateRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BatchCreateRowsResponse responseCancellationToken = await client.BatchCreateRowsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateRowRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new wkt::FieldMask(),
View = View.ColumnIdView,
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.UpdateRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.UpdateRow(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateRowRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new wkt::FieldMask(),
View = View.ColumnIdView,
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.UpdateRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.UpdateRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.UpdateRowAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateRow()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new wkt::FieldMask(),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.UpdateRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row response = client.UpdateRow(request.Row, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateRowAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new wkt::FieldMask(),
};
Row expectedResponse = new Row
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
Values =
{
{
"key8a0b6e3c",
new wkt::Value()
},
},
};
mockGrpcClient.Setup(x => x.UpdateRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Row>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
Row responseCallSettings = await client.UpdateRowAsync(request.Row, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Row responseCancellationToken = await client.UpdateRowAsync(request.Row, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchUpdateRowsRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
BatchUpdateRowsRequest request = new BatchUpdateRowsRequest
{
Parent = "parent7858e4d0",
Requests =
{
new UpdateRowRequest(),
},
};
BatchUpdateRowsResponse expectedResponse = new BatchUpdateRowsResponse { Rows = { new Row(), }, };
mockGrpcClient.Setup(x => x.BatchUpdateRows(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
BatchUpdateRowsResponse response = client.BatchUpdateRows(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchUpdateRowsRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
BatchUpdateRowsRequest request = new BatchUpdateRowsRequest
{
Parent = "parent7858e4d0",
Requests =
{
new UpdateRowRequest(),
},
};
BatchUpdateRowsResponse expectedResponse = new BatchUpdateRowsResponse { Rows = { new Row(), }, };
mockGrpcClient.Setup(x => x.BatchUpdateRowsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchUpdateRowsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
BatchUpdateRowsResponse responseCallSettings = await client.BatchUpdateRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
BatchUpdateRowsResponse responseCancellationToken = await client.BatchUpdateRowsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteRowRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteRow(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteRowRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteRowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteRowAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteRow()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteRow(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteRowAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteRowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteRowAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteRowResourceNames()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteRow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteRow(request.RowName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteRowResourceNamesAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteRowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteRowAsync(request.RowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteRowAsync(request.RowName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchDeleteRowsRequestObject()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
BatchDeleteRowsRequest request = new BatchDeleteRowsRequest
{
ParentAsTableName = TableName.FromTable("[TABLE]"),
RowNames =
{
RowName.FromTableRow("[TABLE]", "[ROW]"),
},
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteRows(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
client.BatchDeleteRows(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchDeleteRowsRequestObjectAsync()
{
moq::Mock<TablesService.TablesServiceClient> mockGrpcClient = new moq::Mock<TablesService.TablesServiceClient>(moq::MockBehavior.Strict);
BatchDeleteRowsRequest request = new BatchDeleteRowsRequest
{
ParentAsTableName = TableName.FromTable("[TABLE]"),
RowNames =
{
RowName.FromTableRow("[TABLE]", "[ROW]"),
},
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteRowsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TablesServiceClient client = new TablesServiceClientImpl(mockGrpcClient.Object, null);
await client.BatchDeleteRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.BatchDeleteRowsAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
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.Globalization;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using OrganizationServiceContextExtensions = Microsoft.Xrm.Portal.Cms.OrganizationServiceContextExtensions;
namespace Adxstudio.Xrm.Web
{
/// <summary>
/// A <see cref="SiteMapProvider"/> for navigating 'adx_blog' <see cref="Entity"/> hierarchies.
/// </summary>
/// <remarks>
/// Configuration format.
/// <code>
/// <![CDATA[
/// <configuration>
///
/// <system.web>
/// <siteMap enabled="true">
/// <providers>
/// <add
/// name="Blogs"
/// type="Adxstudio.Xrm.Web.BlogSiteMapProvider"
/// securityTrimmingEnabled="true"
/// portalName="Xrm" [Microsoft.Xrm.Portal.Configuration.PortalContextElement]
/// />
/// </providers>
/// </siteMap>
/// </system.web>
///
/// </configuration>
/// ]]>
/// </code>
/// </remarks>
/// <seealso cref="PortalContextElement"/>
/// <seealso cref="PortalCrmConfigurationManager"/>
/// <seealso cref="CrmConfigurationManager"/>
public class BlogSiteMapProvider : CrmSiteMapProviderBase, ISolutionDependent
{
public IEnumerable<string> RequiredSolutions
{
get { return new[] { "MicrosoftBlogs" }; }
}
public const string AggregationArchiveSiteMarkerName = "Blog Archive";
private const string AuthorArchiveNodeAttributeKey = "Adxstudio.Xrm.Blogs.Archive.Author";
private const string MonthArchiveNodeAttributeKey = "Adxstudio.Xrm.Blogs.Archive.Month";
private const string TagArchiveNodeAttributeKey = "Adxstudio.Xrm.Blogs.Archive.Tag";
private static readonly Regex AuthorArchivePathRegex = new Regex(@"^.*/(?<blog>[^/]+)/author/(?<author>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex MonthArchivePathRegex = new Regex(@"^.*/(?<blog>[^/]+)/(?<year>\d{4})/(?<month>\d{2})/$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex PathRegex = new Regex("^(.*/)(?<right>[^/]+)/$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex TagArchivePathRegex = new Regex(@"^.*/(?<blog>[^/]+)/tags/(?<tag>[^/]+)$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex WebFilePathRegex = new Regex("^(?<post>.*/)(?<file>[^/]+)$", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.RightToLeft);
public override SiteMapNode FindSiteMapNode(string rawUrl)
{
TraceInfo("FindSiteMapNode({0})", rawUrl);
var portal = PortalContext;
var serviceContext = portal.ServiceContext;
var website = portal.Website.ToEntityReference();
var applicationPath = ApplicationPath.Parse(rawUrl);
var path = new UrlBuilder(applicationPath.PartialPath).Path;
CrmSiteMapNode node;
if (TryGetAuthorArchiveNode(serviceContext, website, path, out node)
|| TryGetMonthArchiveNode(serviceContext, website, path, out node))
{
return ReturnNodeIfAccessible(node, GetAccessDeniedNode);
}
if (TryGetBlogPostNodeById(serviceContext, website, path, out node)
|| TryGetBlogNodeByPartialUrl(serviceContext, website, path, out node)
|| TryGetBlogPostNodeByPartialUrl(serviceContext, website, path, out node))
{
return node;
}
if (TryGetTagArchiveNode(serviceContext, website, path, out node)
|| TryGetWebFileNode(serviceContext, website, path, out node))
{
return ReturnNodeIfAccessible(node, GetAccessDeniedNode);
}
return null;
}
public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
{
TraceInfo("GetChildNodes({0})", node.Key);
var children = new SiteMapNodeCollection();
var entityNode = node as CrmSiteMapNode;
if (entityNode == null || !entityNode.HasCrmEntityName("adx_webpage"))
{
return children;
}
var portal = PortalContext;
var context = portal.ServiceContext;
var website = portal.Website;
var entity = context.MergeClone(entityNode.Entity);
var blogs = FindBlogs(context, website, entity);
foreach (var blog in blogs)
{
var blogNode = GetBlogNode(context, blog);
if (ChildNodeValidator.Validate(context, blogNode))
{
children.Add(blogNode);
}
}
return children;
}
public override SiteMapNode GetParentNode(SiteMapNode node)
{
var entityNode = node as CrmSiteMapNode;
if (entityNode == null)
{
return null;
}
var portal = PortalContext;
var serviceContext = portal.ServiceContext;
var entity = serviceContext.MergeClone(entityNode.Entity);
if (entityNode.HasCrmEntityName("adx_blog"))
{
DateTime monthArchiveDate;
var authorArchive = entityNode[AuthorArchiveNodeAttributeKey];
var tagArchive = entityNode[TagArchiveNodeAttributeKey];
if (TryGetMonthArchiveNodeAttribute(node, out monthArchiveDate) || !string.IsNullOrEmpty(authorArchive) || !string.IsNullOrEmpty(tagArchive))
{
var blogNode = GetBlogNode(serviceContext, entity);
return NodeValidator.Validate(serviceContext, blogNode) ? blogNode : null;
}
var page = entity.GetRelatedEntity(serviceContext, "adx_webpage_blog");
return page == null ? null : SiteMap.Provider.FindSiteMapNode(serviceContext.GetUrl(page));
}
if (entityNode.HasCrmEntityName("adx_blogpost"))
{
var blog = entity.GetRelatedEntity(serviceContext, "adx_blog_blogpost");
if (blog == null)
{
return null;
}
var blogNode = GetBlogNode(serviceContext, blog);
return NodeValidator.Validate(serviceContext, blogNode) ? blogNode : null;
}
if (entityNode.HasCrmEntityName("adx_webfile"))
{
var blogPost = entity.GetRelatedEntity(serviceContext, "adx_blogpost_webfile");
if (blogPost == null)
{
return null;
}
var blogPostNode = GetBlogPostNode(serviceContext, blogPost);
return NodeValidator.Validate(serviceContext, blogPostNode) ? blogPostNode : null;
}
if (entityNode.HasCrmEntityName("adx_webpage") && node["IsAggregationArchiveNode"] == "true")
{
return SiteMap.Provider.FindSiteMapNode(serviceContext.GetUrl(entity));
}
return null;
}
protected virtual IEnumerable<Entity> FindBlogs(OrganizationServiceContext context, Entity website, Entity webpage)
{
var blogsInCurrentWebsite = context.CreateQuery("adx_blog")
.Where(b => b.GetAttributeValue<EntityReference>("adx_websiteid") == website.ToEntityReference()).ToArray();
// Since blogs can only be children of language-root web pages, if the given web page is not a root, then use its root for query instead.
EntityReference rootWebPage = webpage.ToEntityReference();
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled && !webpage.GetAttributeValue<bool>("adx_isroot"))
{
rootWebPage = webpage.GetAttributeValue<EntityReference>("adx_rootwebpageid");
}
var blogs = blogsInCurrentWebsite
.Where(e => Equals(e.GetAttributeValue<EntityReference>("adx_parentpageid"), rootWebPage))
.OrderBy(e => e.GetAttributeValue<string>("adx_name"));
// Only find blogs that match the current language.
var blogsInCurrentLanguage = contextLanguageInfo.IsCrmMultiLanguageEnabled
? blogs.Where(blog => blog.GetAttributeValue<EntityReference>("adx_websitelanguageid") == null || blog.GetAttributeValue<EntityReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EntityReference.Id)
: blogs;
return blogsInCurrentLanguage;
}
protected CrmSiteMapNode GetBlogNode(OrganizationServiceContext serviceContext, Entity entity)
{
entity.AssertEntityName("adx_blog");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var blog = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetBlog(serviceContext, website, entity.Id);
if (blog == null)
{
return null;
}
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, blog);
var pageTemplate = blog.GetRelatedEntity(serviceContext, "adx_pagetemplate_blog_home");
// apply a detached clone of the entity since the SiteMapNode is out of the scope of the current OrganizationServiceContext
var blogClone = blog.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
url,
url,
blog.GetAttributeValue<string>("adx_name"),
blog.GetAttributeValue<string>("adx_summary"),
GetRewriteUrl(pageTemplate, out webTemplateId),
blog.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
blogClone);
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected string GetBlogArchiveRewriteUrl(OrganizationServiceContext serviceContext, Entity entity, out string webTemplateId)
{
entity.AssertEntityName("adx_blog");
var pageTemplate = entity.GetRelatedEntity(serviceContext, "adx_pagetemplate_blog_archive");
return GetRewriteUrl(pageTemplate, out webTemplateId);
}
protected CrmSiteMapNode GetBlogAuthorArchiveNode(OrganizationServiceContext serviceContext, Entity entity, Guid authorId)
{
entity.AssertEntityName("adx_blog");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var blog = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetBlog(serviceContext, website, entity.Id);
if (blog == null)
{
return null;
}
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, blog);
var authorUrl = "{0}{1}author/{2}/".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", authorId);
var blogClone = blog.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
authorUrl,
authorUrl,
GetBlogAuthorName(serviceContext, authorId),
blog.GetAttributeValue<string>("adx_summary"),
GetBlogArchiveRewriteUrl(serviceContext, entity, out webTemplateId),
blog.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
blogClone);
node[AuthorArchiveNodeAttributeKey] = authorId.ToString();
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected CrmSiteMapNode GetBlogMonthArchiveNode(OrganizationServiceContext serviceContext, Entity entity, DateTime month)
{
entity.AssertEntityName("adx_blog");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var blog = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetBlog(serviceContext, website, entity.Id);
if (blog == null)
{
return null;
}
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, blog);
var archiveUrl = "{0}{1}{2:yyyy}/{2:MM}/".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", month);
var blogClone = blog.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
archiveUrl,
archiveUrl,
month.ToString("y", CultureInfo.CurrentCulture),
blog.GetAttributeValue<string>("adx_summary"),
GetBlogArchiveRewriteUrl(serviceContext, entity, out webTemplateId),
blog.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
blogClone);
node[MonthArchiveNodeAttributeKey] = month.ToString("o", CultureInfo.InvariantCulture);
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected CrmSiteMapNode GetBlogTagArchiveNode(OrganizationServiceContext serviceContext, Entity entity, string tagSlug)
{
entity.AssertEntityName("adx_blog");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var blog = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetBlog(serviceContext, website, entity.Id);
if (blog == null)
{
return null;
}
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, blog);
var tagUrl = "{0}{1}{2}".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", tagSlug);
var tag = HttpUtility.UrlDecode(tagSlug).Trim();
var blogClone = blog.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
tagUrl,
tagUrl,
tag,
blog.GetAttributeValue<string>("adx_summary"),
GetBlogArchiveRewriteUrl(serviceContext, entity, out webTemplateId),
blog.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
blogClone);
node[TagArchiveNodeAttributeKey] = tag;
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected CrmSiteMapNode GetBlogAggregationAuthorArchiveNode(OrganizationServiceContext serviceContext, Entity entity, Guid authorId)
{
entity.AssertEntityName("adx_webpage");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var page = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetPage(serviceContext, website, entity.Id);
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, page);
var archiveUrl = "{0}{1}author/{2}/".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", authorId);
var pageTemplate = page.GetRelatedEntity(serviceContext, "adx_pagetemplate_webpage");
var pageClone = page.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
archiveUrl,
archiveUrl,
GetBlogAuthorName(serviceContext, authorId),
page.GetAttributeValue<string>("adx_summary"),
GetRewriteUrl(pageTemplate, out webTemplateId),
page.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
pageClone);
node[AuthorArchiveNodeAttributeKey] = authorId.ToString();
node["IsAggregationArchiveNode"] = "true";
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected CrmSiteMapNode GetBlogAggregationMonthArchiveNode(OrganizationServiceContext serviceContext, Entity entity, DateTime month)
{
entity.AssertEntityName("adx_webpage");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var page = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetPage(serviceContext, website, entity.Id);
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, page);
var archiveUrl = "{0}{1}{2:yyyy}/{2:MM}/".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", month);
var pageTemplate = page.GetRelatedEntity(serviceContext, "adx_pagetemplate_webpage");
var pageClone = page.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
archiveUrl,
archiveUrl,
month.ToString("y", CultureInfo.CurrentCulture),
page.GetAttributeValue<string>("adx_summary"),
GetRewriteUrl(pageTemplate, out webTemplateId),
page.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
pageClone);
node[MonthArchiveNodeAttributeKey] = month.ToString("o", CultureInfo.InvariantCulture);
node["IsAggregationArchiveNode"] = "true";
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected CrmSiteMapNode GetBlogAggregationTagArchiveNode(OrganizationServiceContext serviceContext, Entity entity, string tagSlug)
{
entity.AssertEntityName("adx_webpage");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var page = serviceContext.IsAttached(entity) && Equals(entity.GetAttributeValue<EntityReference>("adx_websiteid"), website)
? entity
: GetPage(serviceContext, website, entity.Id);
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, page);
var tagUrl = "{0}{1}{2}".FormatWith(url, url.EndsWith("/") ? string.Empty : "/", tagSlug);
var tag = HttpUtility.UrlDecode(tagSlug).Trim();
var pageTemplate = page.GetRelatedEntity(serviceContext, "adx_pagetemplate_webpage");
var pageClone = page.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
tagUrl,
tagUrl,
tag,
page.GetAttributeValue<string>("adx_summary"),
GetRewriteUrl(pageTemplate, out webTemplateId),
page.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
pageClone);
node[TagArchiveNodeAttributeKey] = tag;
node["IsAggregationArchiveNode"] = "true";
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected CrmSiteMapNode GetBlogPostNode(OrganizationServiceContext serviceContext, Entity entity)
{
entity.AssertEntityName("adx_blogpost");
var portal = PortalContext;
var website = portal.Website.ToEntityReference();
var post = serviceContext.IsAttached(entity)
? entity
: GetBlogPost(serviceContext, entity.Id);
if (post == null || post.GetAttributeValue<EntityReference>("adx_blogid") == null)
{
return null;
}
var pageTemplateQuery = from p in serviceContext.CreateQuery("adx_pagetemplate")
join b in serviceContext.CreateQuery("adx_blog") on p.GetAttributeValue<Guid>("adx_pagetemplateid") equals b.GetAttributeValue<EntityReference>("adx_blogpostpagetemplateid").Id
where b.GetAttributeValue<EntityReference>("adx_blogpostpagetemplateid") != null && b.GetAttributeValue<Guid>("adx_blogid") == post.GetAttributeValue<EntityReference>("adx_blogid").Id
where p.GetAttributeValue<EntityReference>("adx_websiteid") == website
select p;
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, post);
var pageTemplate = pageTemplateQuery.FirstOrDefault();
var postClone = post.Clone(false);
string webTemplateId;
var node = new CrmSiteMapNode(
this,
url,
url,
post.GetAttributeValue<string>("adx_name"),
post.GetAttributeValue<string>("adx_summary"),
GetRewriteUrl(pageTemplate, out webTemplateId),
post.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
postClone);
if (webTemplateId != null)
{
node["adx_webtemplateid"] = webTemplateId;
}
return node;
}
protected override SiteMapNode GetRootNodeCore()
{
TraceInfo("GetRootNodeCore()");
return null;
}
protected override CrmSiteMapNode GetNode(OrganizationServiceContext context, Entity entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
var entityName = entity.LogicalName;
if (entityName == "adx_blog")
{
return GetBlogNode(context, entity);
}
if (entityName == "adx_blogpost")
{
return GetBlogPostNode(context, entity);
}
throw new ArgumentException("Entity {0} ({1}) is not of a type supported by this provider.".FormatWith(entity.Id, entity.GetType().FullName), "entity");
}
protected virtual bool EntityHasPath(OrganizationServiceContext context, Entity entity, string path)
{
var entityPath = OrganizationServiceContextExtensions.GetApplicationPath(context, entity);
if (entityPath == null)
{
return false;
}
var resultPath = entityPath.PartialPath;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled && ContextLanguageInfo.DisplayLanguageCodeInUrl)
{
resultPath = contextLanguageInfo.StripLanguageCodeFromAbsolutePath(entityPath.PartialPath);
}
return string.Equals(path, resultPath);
}
protected virtual bool TryGetBlogNodeByPartialUrl(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = PathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var filter = new Filter
{
Conditions = new[]
{
new Condition("adx_websiteid", ConditionOperator.Equal, website.Id),
new Condition("adx_partialurl", ConditionOperator.Equal, pathMatch.Groups["right"].Value)
}
};
var languageInfo = HttpContext.Current.GetContextLanguageInfo();
var mlpFilter = new Filter();
if (languageInfo.IsCrmMultiLanguageEnabled)
{
mlpFilter.Type = LogicalOperator.Or;
mlpFilter.Conditions = new[]
{
new Condition("adx_websitelanguageid", ConditionOperator.Null),
new Condition("adx_websitelanguageid", ConditionOperator.Equal, languageInfo.ContextLanguage.EntityReference.Id)
};
}
var fetch = new Fetch
{
Entity = new FetchEntity("adx_blog")
{
Filters = new[] { filter, mlpFilter }
}
};
var blogs = serviceContext.RetrieveMultiple(fetch);
var blogWithMatchingPath = blogs.Entities.FirstOrDefault(e => this.EntityHasPath(serviceContext, e, path));
if (blogWithMatchingPath != null)
{
node = this.GetAccessibleNodeOrAccessDeniedNode(serviceContext, blogWithMatchingPath);
return true;
}
return false;
}
protected virtual bool TryGetBlogPostNodeById(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = PathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
Guid postId;
// If the right-most path segment is a Guid, try look up a post by that ID. Posts can have
// their partial URL be a their ID, as the adx_partialurl attribute is not required.
if (!Guid.TryParse(pathMatch.Groups["right"].Value, out postId))
{
return false;
}
var filter = new Filter
{
Conditions = new[]
{
new Condition("adx_websiteid", ConditionOperator.Equal, website.Id)
}
};
var languageInfo = HttpContext.Current.GetContextLanguageInfo();
var mlpFilter = new Filter();
if (languageInfo.IsCrmMultiLanguageEnabled)
{
mlpFilter.Type = LogicalOperator.Or;
mlpFilter.Conditions = new[]
{
new Condition("adx_websitelanguageid", ConditionOperator.Null),
new Condition("adx_websitelanguageid", ConditionOperator.Equal, languageInfo.ContextLanguage.EntityReference.Id)
};
}
var fetch = new Fetch
{
Entity = new FetchEntity("adx_blogpost")
{
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("adx_blogid", ConditionOperator.NotNull),
new Condition("adx_blogpostid", ConditionOperator.Equal, postId)
}
}
},
Links = new[]
{
new Link
{
Name = "adx_blog",
ToAttribute = "adx_blogid",
FromAttribute = "adx_blogid",
Filters = new[] { filter, mlpFilter }
}
}
}
};
var posts = serviceContext.RetrieveMultiple(fetch);
var postWithMatchingPath = posts.Entities.FirstOrDefault(e => this.EntityHasPath(serviceContext, e, path));
if (postWithMatchingPath != null)
{
node = this.GetAccessibleNodeOrAccessDeniedNode(serviceContext, postWithMatchingPath);
return true;
}
return false;
}
protected virtual bool TryGetBlogPostByPartialUrl(OrganizationServiceContext serviceContext, EntityReference website, string path, out Entity blogPost)
{
blogPost = null;
var pathMatch = PathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var filter = new Filter
{
Conditions = new[]
{
new Condition("adx_websiteid", ConditionOperator.Equal, website.Id)
}
};
var languageInfo = HttpContext.Current.GetContextLanguageInfo();
var mlpFilter = new Filter();
if (languageInfo.IsCrmMultiLanguageEnabled)
{
mlpFilter.Type = LogicalOperator.Or;
mlpFilter.Conditions = new[]
{
new Condition("adx_websitelanguageid", ConditionOperator.Null),
new Condition("adx_websitelanguageid", ConditionOperator.Equal, languageInfo.ContextLanguage.EntityReference.Id)
};
}
var fetch = new Fetch
{
Entity = new FetchEntity("adx_blogpost")
{
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("adx_blogid", ConditionOperator.NotNull),
new Condition("adx_partialurl", ConditionOperator.Equal, pathMatch.Groups["right"].Value)
}
}
},
Links = new[]
{
new Link
{
Name = "adx_blog",
ToAttribute = "adx_blogid",
FromAttribute = "adx_blogid",
Filters = new[] { filter, mlpFilter }
}
}
}
};
var posts = serviceContext.RetrieveMultiple(fetch);
blogPost = posts.Entities.FirstOrDefault(e => this.EntityHasPath(serviceContext, e, path));
return blogPost != null;
}
protected virtual bool TryGetBlogPostNodeByPartialUrl(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
Entity postWithMatchingPath;
if (TryGetBlogPostByPartialUrl(serviceContext, website, path, out postWithMatchingPath))
{
node = GetAccessibleNodeOrAccessDeniedNode(serviceContext, postWithMatchingPath);
return true;
}
return false;
}
protected virtual bool TryGetAuthorArchiveNode(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = AuthorArchivePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var archiveRootPath = Regex.Replace(path, @"author/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/$", string.Empty);
var blogAggregationArchivePageQuery = from page in serviceContext.CreateQuery("adx_webpage")
join siteMarker in serviceContext.CreateQuery("adx_sitemarker") on page.GetAttributeValue<Guid>("adx_webpageid") equals siteMarker.GetAttributeValue<EntityReference>("adx_pageid").Id
where siteMarker.GetAttributeValue<EntityReference>("adx_pageid") != null && siteMarker.GetAttributeValue<string>("adx_name") == AggregationArchiveSiteMarkerName
where page.GetAttributeValue<EntityReference>("adx_websiteid") == website
select page;
var blogAggregationArchivePageMatch = blogAggregationArchivePageQuery.ToArray().FirstOrDefault(e => EntityHasPath(serviceContext, e, archiveRootPath));
Guid authorId;
if (blogAggregationArchivePageMatch != null && Guid.TryParse(pathMatch.Groups["author"].Value, out authorId))
{
node = GetBlogAggregationAuthorArchiveNode(serviceContext, blogAggregationArchivePageMatch, authorId);
return true;
}
var blogsByAuthorArchivePathMatch = from blog in serviceContext.CreateQuery("adx_blog")
where blog.GetAttributeValue<EntityReference>("adx_websiteid") == website
where blog.GetAttributeValue<string>("adx_partialurl") == pathMatch.Groups["blog"].Value
select blog;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
blogsByAuthorArchivePathMatch = blogsByAuthorArchivePathMatch.Where(
blog => blog.GetAttributeValue<EntityReference>("adx_websitelanguageid") == null ||
blog.GetAttributeValue<EntityReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EntityReference.Id);
}
var blogByAuthorArchivePathMatch = blogsByAuthorArchivePathMatch.ToArray().FirstOrDefault(e => EntityHasPath(serviceContext, e, archiveRootPath));
if (blogByAuthorArchivePathMatch != null && Guid.TryParse(pathMatch.Groups["author"].Value, out authorId))
{
node = GetBlogAuthorArchiveNode(serviceContext, blogByAuthorArchivePathMatch, authorId);
return true;
}
return false;
}
protected virtual bool TryGetMonthArchiveNode(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = MonthArchivePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
DateTime date;
try
{
date = new DateTime(
int.Parse(pathMatch.Groups["year"].Value),
int.Parse(pathMatch.Groups["month"].Value),
1, 0, 0, 0,
DateTimeKind.Utc);
}
catch
{
return false;
}
var archiveRootPath = Regex.Replace(path, @"\d{4}/\d{2}/$", string.Empty);
var blogAggregationArchivePageQuery = from page in serviceContext.CreateQuery("adx_webpage")
join siteMarker in serviceContext.CreateQuery("adx_sitemarker") on page.GetAttributeValue<Guid>("adx_webpageid") equals siteMarker.GetAttributeValue<EntityReference>("adx_pageid").Id
where siteMarker.GetAttributeValue<EntityReference>("adx_pageid") != null && siteMarker.GetAttributeValue<string>("adx_name") == AggregationArchiveSiteMarkerName
where page.GetAttributeValue<EntityReference>("adx_websiteid") == website
select page;
var blogAggregationArchivePageMatch = blogAggregationArchivePageQuery.ToArray().FirstOrDefault(e => EntityHasPath(serviceContext, e, archiveRootPath));
if (blogAggregationArchivePageMatch != null)
{
node = GetBlogAggregationMonthArchiveNode(serviceContext, blogAggregationArchivePageMatch, date);
return true;
}
var blogsByMonthArchivePathMatch = from blog in serviceContext.CreateQuery("adx_blog")
where blog.GetAttributeValue<EntityReference>("adx_websiteid") == website
where blog.GetAttributeValue<string>("adx_partialurl") == pathMatch.Groups["blog"].Value
select blog;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
blogsByMonthArchivePathMatch = blogsByMonthArchivePathMatch.Where(
blog => blog.GetAttributeValue<EntityReference>("adx_websitelanguageid") == null ||
blog.GetAttributeValue<EntityReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EntityReference.Id);
}
var blogByMonthArchivePath = blogsByMonthArchivePathMatch.ToArray().FirstOrDefault(e => EntityHasPath(serviceContext, e, archiveRootPath));
if (blogByMonthArchivePath != null)
{
node = GetBlogMonthArchiveNode(serviceContext, blogByMonthArchivePath, date);
return true;
}
return false;
}
protected virtual bool TryGetTagArchiveNode(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = TagArchivePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var archiveRootPath = Regex.Replace(path, @"tags/[^/]+$", string.Empty);
var tagSlug = pathMatch.Groups["tag"].Value;
var blogAggregationArchivePageQuery = from page in serviceContext.CreateQuery("adx_webpage")
join siteMarker in serviceContext.CreateQuery("adx_sitemarker") on page.GetAttributeValue<Guid>("adx_webpageid") equals siteMarker.GetAttributeValue<EntityReference>("adx_pageid").Id
where siteMarker.GetAttributeValue<EntityReference>("adx_pageid") != null && siteMarker.GetAttributeValue<string>("adx_name") == AggregationArchiveSiteMarkerName
where page.GetAttributeValue<EntityReference>("adx_websiteid") == website
select page;
var blogAggregationArchivePageMatch = blogAggregationArchivePageQuery.ToArray().FirstOrDefault(e => EntityHasPath(serviceContext, e, archiveRootPath));
if (blogAggregationArchivePageMatch != null)
{
node = GetBlogAggregationTagArchiveNode(serviceContext, blogAggregationArchivePageMatch, tagSlug);
return true;
}
var blogsByTagArchivePathMatch = from blog in serviceContext.CreateQuery("adx_blog")
where blog.GetAttributeValue<EntityReference>("adx_websiteid") == website
where blog.GetAttributeValue<string>("adx_partialurl") == pathMatch.Groups["blog"].Value
select blog;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
blogsByTagArchivePathMatch = blogsByTagArchivePathMatch.Where(
blog => blog.GetAttributeValue<EntityReference>("adx_websitelanguageid") == null ||
blog.GetAttributeValue<EntityReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EntityReference.Id);
}
var blogByTagArchivePath = blogsByTagArchivePathMatch.ToArray().FirstOrDefault(e => EntityHasPath(serviceContext, e, archiveRootPath));
if (blogByTagArchivePath != null)
{
node = GetBlogTagArchiveNode(serviceContext, blogByTagArchivePath, tagSlug);
return true;
}
return false;
}
protected virtual bool TryGetWebFileNode(OrganizationServiceContext serviceContext, EntityReference website, string path, out CrmSiteMapNode node)
{
node = null;
var pathMatch = WebFilePathRegex.Match(path);
if (!pathMatch.Success)
{
return false;
}
var contentMapProvider = HttpContext.Current.GetContentMapProvider();
IDictionary<EntityReference, EntityNode> webfiles = new Dictionary<EntityReference, EntityNode>();
contentMapProvider.Using(map => map.TryGetValue("adx_webfile", out webfiles));
var files =
webfiles.Values.Cast<WebFileNode>()
.Where(wf => wf.BlogPost != null && wf.PartialUrl.Equals(pathMatch.Groups["file"].Value) && wf.StateCode == 0);
if (!files.Any())
{
return false;
}
Entity blogPost;
if (TryGetBlogPostByPartialUrl(serviceContext, website, pathMatch.Groups["post"].Value, out blogPost))
{
var file = files.FirstOrDefault(f =>
{
var blogPostReference = f.BlogPost;
return blogPostReference != null && blogPostReference.Equals(blogPost.ToEntityReference());
});
if (file != null)
{
var entity = serviceContext.MergeClone(file.ToEntity());
node = GetWebFileNode(serviceContext, entity, HttpStatusCode.OK);
return true;
}
}
return false;
}
private CrmSiteMapNode GetWebFileNode(OrganizationServiceContext serviceContext, Entity file, HttpStatusCode statusCode)
{
if (file == null)
{
return null;
}
var url = OrganizationServiceContextExtensions.GetUrl(serviceContext, file);
var name = file.GetAttributeValue<string>("adx_name");
var summary = file.GetAttributeValue<string>("adx_summary");
var fileAttachmentProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityFileAttachmentProvider>();
var attachmentInfo = fileAttachmentProvider.GetAttachmentInfo(serviceContext, file).FirstOrDefault();
// apply a detached clone of the entity since the SiteMapNode is out of the scope of the current OrganizationServiceContext
var fileClone = file.Clone(false);
// If there's no file attached to the webfile, return a NotFound node with no rewrite path.
if (attachmentInfo == null)
{
return new CrmSiteMapNode(
this,
url,
url,
name,
summary,
null,
file.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
fileClone,
HttpStatusCode.NotFound);
}
return new CrmSiteMapNode(
this,
url,
url,
name,
summary,
attachmentInfo.Url,
attachmentInfo.LastModified.GetValueOrDefault(DateTime.UtcNow),
file,
statusCode);
}
private static Entity GetBlog(OrganizationServiceContext serviceContext, EntityReference website, Guid id)
{
return serviceContext.CreateQuery("adx_blog")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_blogid") == id && e.GetAttributeValue<EntityReference>("adx_websiteid") == website);
}
private static string GetBlogAuthorName(OrganizationServiceContext serviceContext, Guid authorId)
{
var fetch = new Fetch
{
Entity = new FetchEntity("contact")
{
Attributes = new List<FetchAttribute> { new FetchAttribute("fullname") },
Filters = new List<Filter> { new Filter { Conditions = new[] { new Condition("contactid", ConditionOperator.Equal, authorId) } } }
}
};
var contact = serviceContext.RetrieveSingle(fetch);
return contact == null ? "?" : contact.GetAttributeValue<string>("fullname");
}
private static Entity GetBlogPost(OrganizationServiceContext serviceContext, Guid id)
{
return serviceContext.CreateQuery("adx_blogpost").FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_blogpostid") == id);
}
private static Entity GetPage(OrganizationServiceContext serviceContext, EntityReference website, Guid id)
{
return serviceContext.CreateQuery("adx_webpage")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webpageid") == id && e.GetAttributeValue<EntityReference>("adx_websiteid") == website);
}
public static bool TryGetAuthorArchiveNodeAttribute(SiteMapNode node, out Guid authorId)
{
authorId = default(Guid);
return node != null && Guid.TryParse(node[AuthorArchiveNodeAttributeKey], out authorId);
}
public static bool TryGetMonthArchiveNodeAttribute(SiteMapNode node, out DateTime month)
{
month = default(DateTime);
return node != null && DateTime.TryParseExact(node[MonthArchiveNodeAttributeKey], "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out month);
}
public static bool TryGetTagArchiveNodeAttribute(SiteMapNode node, out string tag)
{
if (node == null)
{
tag = null;
return false;
}
tag = node[TagArchiveNodeAttributeKey];
return !string.IsNullOrWhiteSpace(tag);
}
private string GetRewriteUrl(Entity pageTemplate, out string webTemplateId)
{
webTemplateId = null;
if (pageTemplate == null)
{
return null;
}
if (TryGetWebTemplateId(pageTemplate, out webTemplateId))
{
return pageTemplate.GetAttributeValue<bool?>("adx_usewebsiteheaderandfooter").GetValueOrDefault(true)
? "~/Pages/WebTemplate.aspx"
: "~/Pages/WebTemplateNoMaster.aspx";
}
return pageTemplate.GetAttributeValue<string>("adx_rewriteurl");
}
private bool TryGetWebTemplateId(Entity pageTemplate, out string webTemplateId)
{
webTemplateId = null;
if (pageTemplate == null)
{
return false;
}
var type = pageTemplate.GetAttributeValue<OptionSetValue>("adx_type");
var webTemplate = pageTemplate.GetAttributeValue<EntityReference>("adx_webtemplateid");
if (type == null || type.Value != (int)PageTemplateNode.TemplateType.WebTemplate || webTemplate == null)
{
return false;
}
webTemplateId = webTemplate.Id.ToString();
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("WorkItemGroup Name={Name} State={state}")]
internal class WorkItemGroup : IWorkItem
{
private enum WorkGroupStatus
{
Waiting = 0,
Runnable = 1,
Running = 2,
Shutdown = 3
}
private readonly ILogger log;
private readonly OrleansTaskScheduler masterScheduler;
private WorkGroupStatus state;
private readonly Object lockable;
private readonly Queue<Task> workItems;
private long totalItemsEnQueued; // equals total items queued, + 1
private long totalItemsProcessed;
private readonly QueueTrackingStatistic queueTracking;
private TimeSpan totalQueuingDelay;
private readonly long quantumExpirations;
private readonly int workItemGroupStatisticsNumber;
internal ActivationTaskScheduler TaskRunner { get; private set; }
public DateTime TimeQueued { get; set; }
public TimeSpan TimeSinceQueued
{
get { return Utils.Since(TimeQueued); }
}
public ISchedulingContext SchedulingContext { get; set; }
public bool IsSystemPriority
{
get { return SchedulingUtils.IsSystemPriorityContext(SchedulingContext); }
}
internal bool IsSystemGroup
{
get { return SchedulingUtils.IsSystemContext(SchedulingContext); }
}
public string Name { get { return SchedulingContext == null ? "unknown" : SchedulingContext.Name; } }
internal int ExternalWorkItemCount
{
get { lock (lockable) { return WorkItemCount; } }
}
private int WorkItemCount
{
get { return workItems.Count; }
}
internal float AverageQueueLenght
{
get
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
{
return queueTracking.AverageQueueLength;
}
#endif
return 0;
}
}
internal float NumEnqueuedRequests
{
get
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
{
return queueTracking.NumEnqueuedRequests;
}
#endif
return 0;
}
}
internal float ArrivalRate
{
get
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
{
return queueTracking.ArrivalRate;
}
#endif
return 0;
}
}
private bool IsActive
{
get
{
return WorkItemCount != 0;
}
}
// This is the maximum number of work items to be processed in an activation turn.
// If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing).
private const int MaxWorkItemsPerTurn = 0; // Unlimited
// This is a soft time limit on the duration of activation macro-turn (a number of micro-turns).
// If a activation was running its micro-turns longer than this, we will give up the thread.
// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing).
public static TimeSpan ActivationSchedulingQuantum { get; set; }
// This is the maximum number of waiting threads (blocked in WaitForResponse) allowed
// per ActivationWorker. An attempt to wait when there are already too many threads waiting
// will result in a TooManyWaitersException being thrown.
//private static readonly int MaxWaitingThreads = 500;
internal WorkItemGroup(OrleansTaskScheduler sched, ISchedulingContext schedulingContext, ILoggerFactory loggerFactory)
{
masterScheduler = sched;
SchedulingContext = schedulingContext;
state = WorkGroupStatus.Waiting;
workItems = new Queue<Task>();
lockable = new Object();
totalItemsEnQueued = 0;
totalItemsProcessed = 0;
totalQueuingDelay = TimeSpan.Zero;
quantumExpirations = 0;
TaskRunner = new ActivationTaskScheduler(this, loggerFactory);
log = IsSystemPriority ? loggerFactory.CreateLogger($"{this.GetType().Namespace} {Name}.{this.GetType().Name}") : loggerFactory.CreateLogger<WorkItemGroup>();
if (StatisticsCollector.CollectShedulerQueuesStats)
{
queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name);
queueTracking.OnStartExecution();
}
if (StatisticsCollector.CollectPerWorkItemStats)
{
workItemGroupStatisticsNumber = SchedulerStatisticsGroup.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext,
() =>
{
var sb = new StringBuilder();
lock (lockable)
{
sb.Append("QueueLength = " + WorkItemCount);
sb.Append(String.Format(", State = {0}", state));
if (state == WorkGroupStatus.Runnable)
sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null"));
}
return sb.ToString();
});
}
}
/// <summary>
/// Adds a task to this activation.
/// If we're adding it to the run list and we used to be waiting, now we're runnable.
/// </summary>
/// <param name="task">The work item to add.</param>
public void EnqueueTask(Task task)
{
lock (lockable)
{
#if DEBUG
if (log.IsEnabled(LogLevel.Trace)) log.Trace("EnqueueWorkItem {0} into {1} when TaskScheduler.Current={2}", task, SchedulingContext, TaskScheduler.Current);
#endif
if (state == WorkGroupStatus.Shutdown)
{
ReportWorkGroupProblem(
String.Format("Enqueuing task {0} to a stopped work item group. Going to ignore and not execute it. "
+ "The likely reason is that the task is not being 'awaited' properly.", task),
ErrorCode.SchedulerNotEnqueuWorkWhenShutdown);
task.Ignore(); // Ignore this Task, so in case it is faulted it will not cause UnobservedException.
return;
}
long thisSequenceNumber = totalItemsEnQueued++;
int count = WorkItemCount;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectShedulerQueuesStats)
queueTracking.OnEnQueueRequest(1, count);
if (StatisticsCollector.CollectGlobalShedulerStats)
SchedulerStatisticsGroup.OnWorkItemEnqueue();
#endif
workItems.Enqueue(task);
int maxPendingItemsLimit = masterScheduler.MaxPendingItemsSoftLimit;
if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit)
{
log.Warn(ErrorCode.SchedulerTooManyPendingItems, String.Format("{0} pending work items for group {1}, exceeding the warning threshold of {2}",
count, Name, maxPendingItemsLimit));
}
if (state != WorkGroupStatus.Waiting) return;
state = WorkGroupStatus.Runnable;
#if DEBUG
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Add to RunQueue {0}, #{1}, onto {2}", task, thisSequenceNumber, SchedulingContext);
#endif
masterScheduler.RunQueue.Add(this);
}
}
/// <summary>
/// Shuts down this work item group so that it will not process any additional work items, even if they
/// have already been queued.
/// </summary>
internal void Stop()
{
lock (lockable)
{
if (IsActive)
{
ReportWorkGroupProblem(
String.Format("WorkItemGroup is being stoped while still active. workItemCount = {0}."
+ "The likely reason is that the task is not being 'awaited' properly.", WorkItemCount),
ErrorCode.SchedulerWorkGroupStopping);
}
if (state == WorkGroupStatus.Shutdown)
{
log.Warn(ErrorCode.SchedulerWorkGroupShuttingDown, "WorkItemGroup is already shutting down {0}", this.ToString());
return;
}
state = WorkGroupStatus.Shutdown;
if (StatisticsCollector.CollectPerWorkItemStats)
SchedulerStatisticsGroup.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber);
if (StatisticsCollector.CollectGlobalShedulerStats)
SchedulerStatisticsGroup.OnWorkItemDrop(WorkItemCount);
if (StatisticsCollector.CollectShedulerQueuesStats)
queueTracking.OnStopExecution();
foreach (Task task in workItems)
{
// Ignore all queued Tasks, so in case they are faulted they will not cause UnobservedException.
task.Ignore();
}
workItems.Clear();
}
}
#region IWorkItem Members
public WorkItemType ItemType
{
get { return WorkItemType.WorkItemGroup; }
}
// Execute one or more turns for this activation.
// This method is always called in a single-threaded environment -- that is, no more than one
// thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc.
public void Execute()
{
lock (lockable)
{
if (state == WorkGroupStatus.Shutdown)
{
if (!IsActive) return; // Don't mind if no work has been queued to this work group yet.
ReportWorkGroupProblemWithBacktrace(
"Cannot execute work items in a work item group that is in a shutdown state.",
ErrorCode.SchedulerNotExecuteWhenShutdown); // Throws InvalidOperationException
return;
}
state = WorkGroupStatus.Running;
}
var thread = WorkerPoolThread.CurrentWorkerThread;
try
{
// Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation
int count = 0;
var stopwatch = new Stopwatch();
stopwatch.Start();
do
{
lock (lockable)
{
if (state == WorkGroupStatus.Shutdown)
{
if (WorkItemCount > 0)
log.Warn(ErrorCode.SchedulerSkipWorkStopping, "Thread {0} is exiting work loop due to Shutdown state {1} while still having {2} work items in the queue.",
thread.ToString(), this.ToString(), WorkItemCount);
else
if(log.IsEnabled(LogLevel.Debug)) log.Debug("Thread {0} is exiting work loop due to Shutdown state {1}. Has {2} work items in the queue.",
thread.ToString(), this.ToString(), WorkItemCount);
break;
}
// Check the cancellation token (means that the silo is stopping)
if (thread.CancelToken.IsCancellationRequested)
{
log.Warn(ErrorCode.SchedulerSkipWorkCancelled, "Thread {0} is exiting work loop due to cancellation token. WorkItemGroup: {1}, Have {2} work items in the queue.",
thread.ToString(), this.ToString(), WorkItemCount);
break;
}
}
// Get the first Work Item on the list
Task task;
lock (lockable)
{
if (workItems.Count > 0)
task = workItems.Dequeue();
else // If the list is empty, then we're done
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectGlobalShedulerStats)
SchedulerStatisticsGroup.OnWorkItemDequeue();
#endif
#if DEBUG
if (log.IsEnabled(LogLevel.Trace)) log.Trace("About to execute task {0} in SchedulingContext={1}", task, SchedulingContext);
#endif
var taskStart = stopwatch.Elapsed;
try
{
thread.CurrentTask = task;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectTurnsStats)
SchedulerStatisticsGroup.OnTurnExecutionStartsByWorkGroup(workItemGroupStatisticsNumber, thread.WorkerThreadStatisticsNumber, SchedulingContext);
#endif
TaskRunner.RunTask(task);
}
catch (Exception ex)
{
log.Error(ErrorCode.SchedulerExceptionFromExecute, String.Format("Worker thread caught an exception thrown from Execute by task {0}", task), ex);
throw;
}
finally
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectTurnsStats)
SchedulerStatisticsGroup.OnTurnExecutionEnd(Utils.Since(thread.CurrentStateStarted));
if (StatisticsCollector.CollectThreadTimeTrackingStats)
thread.threadTracking.IncrementNumberOfProcessed();
#endif
totalItemsProcessed++;
var taskLength = stopwatch.Elapsed - taskStart;
if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold)
{
SchedulerStatisticsGroup.NumLongRunningTurns.Increment();
log.Warn(ErrorCode.SchedulerTurnTooLong3, "Task {0} in WorkGroup {1} took elapsed time {2:g} for execution, which is longer than {3}. Running on thread {4}",
OrleansTaskExtentions.ToString(task), SchedulingContext.ToString(), taskLength, OrleansTaskScheduler.TurnWarningLengthThreshold, thread.ToString());
}
thread.CurrentTask = null;
}
count++;
}
while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) &&
((ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < ActivationSchedulingQuantum)));
stopwatch.Stop();
}
catch (Exception ex)
{
log.Error(ErrorCode.Runtime_Error_100032, String.Format("Worker thread {0} caught an exception thrown from IWorkItem.Execute", thread), ex);
}
finally
{
// Now we're not Running anymore.
// If we left work items on our run list, we're Runnable, and need to go back on the silo run queue;
// If our run list is empty, then we're waiting.
lock (lockable)
{
if (state != WorkGroupStatus.Shutdown)
{
if (WorkItemCount > 0)
{
state = WorkGroupStatus.Runnable;
masterScheduler.RunQueue.Add(this);
}
else
{
state = WorkGroupStatus.Waiting;
}
}
}
}
}
#endregion
public override string ToString()
{
return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}",
IsSystemGroup ? "System*" : "",
Name,
state);
}
public string DumpStatus()
{
lock (lockable)
{
var sb = new StringBuilder();
sb.Append(this);
sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ",
WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations);
if (AverageQueueLenght > 0)
{
sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLenght);
if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0)
{
sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds);
}
}
sb.AppendFormat("TaskRunner={0}; ", TaskRunner);
if (SchedulingContext != null)
{
sb.AppendFormat("Detailed SchedulingContext=<{0}>", SchedulingContext.DetailedStatus());
}
return sb.ToString();
}
}
private void ReportWorkGroupProblemWithBacktrace(string what, ErrorCode errorCode)
{
var st = Utils.GetStackTrace();
var msg = string.Format("{0} {1}", what, DumpStatus());
log.Warn(errorCode, msg + Environment.NewLine + " Called from " + st);
}
private void ReportWorkGroupProblem(string what, ErrorCode errorCode)
{
var msg = string.Format("{0} {1}", what, DumpStatus());
log.Warn(errorCode, msg);
}
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload001.overload001
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(11,23\).*CS0649</Expects>
public class Base
{
public static int Status;
public static int operator +(short x, Base b)
{
return int.MinValue;
}
}
public class Derived : Base
{
public static int operator +(int x, Derived d)
{
return int.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = 3;
int xx = x + d;
if (xx == int.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload002.overload002
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static float operator -(short x, Base b)
{
return float.Epsilon;
}
}
public class Derived : Base
{
public static float operator -(int x, Derived d)
{
return float.NegativeInfinity;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
float f = x - d;
if (float.IsNegativeInfinity(f))
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload003.overload003
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static double operator *(Base b, short x)
{
return double.MinValue;
}
}
public class Derived : Base
{
public static double operator *(Derived d, int x)
{
return double.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
double dd = d * x;
if (dd == double.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload004.overload004
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static short operator /(Base x, short d)
{
return short.MinValue;
}
}
public class Derived : Base
{
public static short operator /(Derived x, int d)
{
return short.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
short s = d / x;
if (s == short.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload005.overload005
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static int?[] operator %(short x, Base b)
{
return new int?[]
{
1, 2, null
}
;
}
}
public class Derived : Base
{
public static int?[] operator %(int x, Derived d)
{
return new int?[]
{
null, null
}
;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
int?[] xx = x % d;
if (xx.Length == 2)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload006.overload006
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static string operator &(Base b, short x)
{
return string.Empty;
}
}
public class Derived : Base
{
public static string operator &(Derived d, int x)
{
return "foo";
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
string s = d & x;
if (s == "foo")
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload007.overload007
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static byte[] operator |(short x, Base b)
{
return new byte[]
{
1, 2, 3
}
;
}
}
public class Derived : Base
{
public static byte[] operator |(int x, Derived d)
{
return new byte[]
{
1, 2
}
;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = 3;
byte[] b = x | d;
if (b.Length == 2)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload008.overload008
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Select the best method to call.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static decimal operator ^(dynamic x, Base b)
{
return decimal.Zero;
}
public static decimal operator ^(short x, Base b)
{
return decimal.One;
}
}
public class Derived : Base
{
public static decimal operator ^(int x, Derived d)
{
return decimal.MinusOne;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
dynamic x = 3;
decimal dec = x ^ d;
if (dec == decimal.MinusOne)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.binary.overload009.overload009
{
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Select the best method to call.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static decimal operator ^(dynamic x, Base b)
{
return decimal.Zero;
}
public static decimal operator ^(short x, Base b)
{
return decimal.One;
}
}
public class Derived : Base
{
public static decimal operator ^(int x, Derived d)
{
return decimal.MinusOne;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Base();
dynamic x = 3;
decimal dec = x ^ d;
if (dec == decimal.Zero)
return 0;
return 1;
}
}
// </Code>
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime;
using System.Xml;
using System.Threading.Tasks;
using System.Threading;
namespace System.ServiceModel.Description
{
internal static class NamingHelper
{
internal const string DefaultNamespace = "http://tempuri.org/";
internal const string DefaultServiceName = "service";
internal const string MSNamespace = "http://schemas.microsoft.com/2005/07/ServiceModel";
// simplified rules for appending paths to base URIs. note that this differs from new Uri(baseUri, string)
// 1) CombineUriStrings("http://foo/bar/z", "baz") ==> "http://foo/bar/z/baz"
// 2) CombineUriStrings("http://foo/bar/z/", "baz") ==> "http://foo/bar/z/baz"
// 3) CombineUriStrings("http://foo/bar/z", "/baz") ==> "http://foo/bar/z/baz"
// 4) CombineUriStrings("http://foo/bar/z", "http://baz/q") ==> "http://baz/q"
// 5) CombineUriStrings("http://foo/bar/z", "") ==> ""
internal static string CombineUriStrings(string baseUri, string path)
{
if (Uri.IsWellFormedUriString(path, UriKind.Absolute) || path == String.Empty)
{
return path;
}
else
{
// combine
if (baseUri.EndsWith("/", StringComparison.Ordinal))
{
return baseUri + (path.StartsWith("/", StringComparison.Ordinal) ? path.Substring(1) : path);
}
else
{
return baseUri + (path.StartsWith("/", StringComparison.Ordinal) ? path : "/" + path);
}
}
}
internal static string TypeName(Type t)
{
Type[] args = null;
if (t.GetTypeInfo().IsGenericType)
{
args = t.GetTypeInfo().GenericTypeArguments;
}
else if (t.GetTypeInfo().ContainsGenericParameters)
{
args = t.GetTypeInfo().GenericTypeParameters;
}
if (args != null)
{
int nameEnd = t.Name.IndexOf('`');
string result = nameEnd > 0 ? t.Name.Substring(0, nameEnd) : t.Name;
result += "Of";
for (int i = 0; i < args.Length; ++i)
{
result = result + "_" + TypeName(args[i]);
}
return result;
}
else if (t.IsArray)
{
return "ArrayOf" + TypeName(t.GetElementType());
}
else
{
return t.Name;
}
}
// name, ns could have any combination of nulls
internal static XmlQualifiedName GetContractName(Type contractType, string name, string ns)
{
XmlName xmlName = new XmlName(name ?? TypeName(contractType));
// ns can be empty
if (ns == null)
{
ns = DefaultNamespace;
}
return new XmlQualifiedName(xmlName.EncodedName, ns);
}
// name could be null
// logicalMethodName is MethodInfo.Name with Begin removed for async pattern
// return encoded version to be used in OperationDescription
internal static XmlName GetOperationName(string logicalMethodName, string name)
{
return new XmlName(String.IsNullOrEmpty(name) ? logicalMethodName : name);
}
internal static string GetMessageAction(OperationDescription operation, bool isResponse)
{
ContractDescription contract = operation.DeclaringContract;
XmlQualifiedName contractQname = new XmlQualifiedName(contract.Name, contract.Namespace);
return GetMessageAction(contractQname, operation.CodeName, null, isResponse);
}
// name could be null
// logicalMethodName is MethodInfo.Name with Begin removed for async pattern
internal static string GetMessageAction(XmlQualifiedName contractName, string opname, string action, bool isResponse)
{
if (action != null)
{
return action;
}
System.Text.StringBuilder actionBuilder = new System.Text.StringBuilder(64);
if (String.IsNullOrEmpty(contractName.Namespace))
{
actionBuilder.Append("urn:");
}
else
{
actionBuilder.Append(contractName.Namespace);
if (!contractName.Namespace.EndsWith("/", StringComparison.Ordinal))
{
actionBuilder.Append('/');
}
}
actionBuilder.Append(contractName.Name);
actionBuilder.Append('/');
action = isResponse ? opname + "Response" : opname;
return CombineUriStrings(actionBuilder.ToString(), action);
}
internal delegate bool DoesNameExist(string name, object nameCollection);
internal static string GetUniqueName(string baseName, DoesNameExist doesNameExist, object nameCollection)
{
for (int i = 0; i < Int32.MaxValue; i++)
{
string name = i > 0 ? baseName + i : baseName;
if (!doesNameExist(name, nameCollection))
{
return name;
}
}
Fx.Assert("Too Many Names");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Cannot generate unique name for name {0}", baseName)));
}
internal static void CheckUriProperty(string ns, string propName)
{
Uri uri;
if (!Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out uri))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.SFXUnvalidNamespaceValue, ns, propName));
}
internal static void CheckUriParameter(string ns, string paramName)
{
Uri uri;
if (!Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out uri))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(paramName, SR.Format(SR.SFXUnvalidNamespaceParam, ns));
}
// Converts names that contain characters that are not permitted in XML names to valid names.
internal static string XmlName(string name)
{
if (string.IsNullOrEmpty(name))
return name;
if (IsAsciiLocalName(name))
return name;
if (IsValidNCName(name))
return name;
return XmlConvert.EncodeLocalName(name);
}
// Transforms an XML name into an object name.
internal static string CodeName(string name)
{
return XmlConvert.DecodeName(name);
}
private static bool IsAlpha(char ch)
{
return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z');
}
private static bool IsDigit(char ch)
{
return (ch >= '0' && ch <= '9');
}
private static bool IsAsciiLocalName(string localName)
{
Fx.Assert(null != localName, "");
if (!IsAlpha(localName[0]))
return false;
for (int i = 1; i < localName.Length; i++)
{
char ch = localName[i];
if (!IsAlpha(ch) && !IsDigit(ch))
return false;
}
return true;
}
internal static bool IsValidNCName(string name)
{
try
{
XmlConvert.VerifyNCName(name);
return true;
}
catch (XmlException)
{
return false;
}
}
}
internal class XmlName
{
private string _decoded;
private string _encoded;
internal XmlName(string name)
: this(name, false)
{
}
internal XmlName(string name, bool isEncoded)
{
if (isEncoded)
{
ValidateEncodedName(name, true /*allowNull*/);
_encoded = name;
}
else
{
_decoded = name;
}
}
internal string EncodedName
{
get
{
if (_encoded == null)
_encoded = NamingHelper.XmlName(_decoded);
return _encoded;
}
}
internal string DecodedName
{
get
{
if (_decoded == null)
_decoded = NamingHelper.CodeName(_encoded);
return _decoded;
}
}
private static void ValidateEncodedName(string name, bool allowNull)
{
if (allowNull && name == null)
return;
try
{
XmlConvert.VerifyNCName(name);
}
catch (XmlException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(e.Message, "name"));
}
}
private bool IsEmpty { get { return string.IsNullOrEmpty(_encoded) && string.IsNullOrEmpty(_decoded); } }
internal static bool IsNullOrEmpty(XmlName xmlName)
{
return xmlName == null || xmlName.IsEmpty;
}
private bool Matches(XmlName xmlName)
{
return string.Equals(this.EncodedName, xmlName.EncodedName, StringComparison.Ordinal);
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, this))
{
return true;
}
if (object.ReferenceEquals(obj, null))
{
return false;
}
XmlName xmlName = obj as XmlName;
if (xmlName == null)
{
return false;
}
return Matches(xmlName);
}
public override int GetHashCode()
{
if (string.IsNullOrEmpty(EncodedName))
return 0;
return EncodedName.GetHashCode();
}
public override string ToString()
{
if (_encoded == null && _decoded == null)
return null;
if (_encoded != null)
return _encoded;
return _decoded;
}
public static bool operator ==(XmlName a, XmlName b)
{
if (object.ReferenceEquals(a, null))
{
return object.ReferenceEquals(b, null);
}
return (a.Equals(b));
}
public static bool operator !=(XmlName a, XmlName b)
{
return !(a == b);
}
}
static internal class ServiceReflector
{
internal const string BeginMethodNamePrefix = "Begin";
internal const string EndMethodNamePrefix = "End";
internal static readonly Type VoidType = typeof(void);
internal const string AsyncMethodNameSuffix = "Async";
internal static readonly Type taskType = typeof(Task);
internal static readonly Type taskTResultType = typeof(Task<>);
internal static readonly Type CancellationTokenType = typeof(CancellationToken);
internal static readonly Type IProgressType = typeof(IProgress<>);
private static readonly Type s_asyncCallbackType = typeof(AsyncCallback);
private static readonly Type s_asyncResultType = typeof(IAsyncResult);
private static readonly Type s_objectType = typeof(object);
private static readonly Type s_OperationContractAttributeType = typeof(OperationContractAttribute);
static internal Type GetOperationContractProviderType(MethodInfo method)
{
if (GetSingleAttribute<OperationContractAttribute>(method) != null)
{
return s_OperationContractAttributeType;
}
IOperationContractAttributeProvider provider = GetFirstAttribute<IOperationContractAttributeProvider>(method);
if (provider != null)
{
return provider.GetType();
}
return null;
}
// returns the set of root interfaces for the service class (meaning doesn't include callback ifaces)
static internal List<Type> GetInterfaces(Type service)
{
List<Type> types = new List<Type>();
bool implicitContract = false;
if (service.IsDefined(typeof(ServiceContractAttribute), false))
{
implicitContract = true;
types.Add(service);
}
if (!implicitContract)
{
Type t = GetAncestorImplicitContractClass(service);
if (t != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxContractInheritanceRequiresInterfaces2, service, t)));
}
foreach (MethodInfo method in GetMethodsInternal(service))
{
Type operationContractProviderType = GetOperationContractProviderType(method);
if (operationContractProviderType == s_OperationContractAttributeType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ServicesWithoutAServiceContractAttributeCan2, operationContractProviderType.Name, method.Name, service.FullName)));
}
}
}
foreach (Type t in service.GetInterfaces())
{
if (t.IsDefined(typeof(ServiceContractAttribute), false))
{
if (implicitContract)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxContractInheritanceRequiresInterfaces, service, t)));
}
types.Add(t);
}
}
return types;
}
private static Type GetAncestorImplicitContractClass(Type service)
{
for (service = service.BaseType(); service != null; service = service.BaseType())
{
if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(service) != null)
{
return service;
}
}
return null;
}
static internal List<Type> GetInheritedContractTypes(Type service)
{
List<Type> types = new List<Type>();
foreach (Type t in service.GetInterfaces())
{
if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(t) != null)
{
types.Add(t);
}
}
for (service = service.BaseType(); service != null; service = service.BaseType())
{
if (ServiceReflector.GetSingleAttribute<ServiceContractAttribute>(service) != null)
{
types.Add(service);
}
}
return types;
}
static internal object[] GetCustomAttributes(ICustomAttributeProvider attrProvider, Type attrType)
{
return GetCustomAttributes(attrProvider, attrType, false);
}
static internal object[] GetCustomAttributes(ICustomAttributeProvider attrProvider, Type attrType, bool inherit)
{
try
{
if (typeof(Attribute).IsAssignableFrom(attrType))
{
return attrProvider.GetCustomAttributes(attrType, inherit);
}
else
{
List<object> attrTypeAttributes = new List<object>();
object[] allCustomAttributes = attrProvider.GetCustomAttributes(inherit);
foreach (object customAttribute in allCustomAttributes)
{
if (attrType.IsAssignableFrom(customAttribute.GetType()))
{
attrTypeAttributes.Add(customAttribute);
}
}
return attrTypeAttributes.ToArray();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
Type type = attrProvider as Type;
MethodInfo method = attrProvider as MethodInfo;
ParameterInfo param = attrProvider as ParameterInfo;
// there is no good way to know if this is a return type attribute
if (type != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxErrorReflectingOnType2, attrType.Name, type.Name), e));
}
else if (method != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxErrorReflectingOnMethod3,
attrType.Name, method.Name, method.DeclaringType.Name), e));
}
else if (param != null)
{
method = param.Member as MethodInfo;
if (method != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxErrorReflectingOnParameter4,
attrType.Name, param.Name, method.Name, method.DeclaringType.Name), e));
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxErrorReflectionOnUnknown1, attrType.Name), e));
}
}
static internal T GetFirstAttribute<T>(ICustomAttributeProvider attrProvider)
where T : class
{
Type attrType = typeof(T);
object[] attrs = GetCustomAttributes(attrProvider, attrType);
if (attrs.Length == 0)
{
return null;
}
else
{
return attrs[0] as T;
}
}
static internal T GetSingleAttribute<T>(ICustomAttributeProvider attrProvider)
where T : class
{
Type attrType = typeof(T);
object[] attrs = GetCustomAttributes(attrProvider, attrType);
if (attrs == null || attrs.Length == 0)
{
return null;
}
else if (attrs.Length > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.tooManyAttributesOfTypeOn2, attrType, attrProvider.ToString())));
}
else
{
return attrs[0] as T;
}
}
static internal T GetRequiredSingleAttribute<T>(ICustomAttributeProvider attrProvider)
where T : class
{
T result = GetSingleAttribute<T>(attrProvider);
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.couldnTFindRequiredAttributeOfTypeOn2, typeof(T), attrProvider.ToString())));
}
return result;
}
static internal T GetSingleAttribute<T>(ICustomAttributeProvider attrProvider, Type[] attrTypeGroup)
where T : class
{
T result = GetSingleAttribute<T>(attrProvider);
if (result != null)
{
Type attrType = typeof(T);
foreach (Type otherType in attrTypeGroup)
{
if (otherType == attrType)
{
continue;
}
object[] attrs = GetCustomAttributes(attrProvider, otherType);
if (attrs != null && attrs.Length > 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxDisallowedAttributeCombination, attrProvider, attrType.FullName, otherType.FullName)));
}
}
}
return result;
}
static internal T GetRequiredSingleAttribute<T>(ICustomAttributeProvider attrProvider, Type[] attrTypeGroup)
where T : class
{
T result = GetSingleAttribute<T>(attrProvider, attrTypeGroup);
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.couldnTFindRequiredAttributeOfTypeOn2, typeof(T), attrProvider.ToString())));
}
return result;
}
static internal Type GetContractType(Type interfaceType)
{
ServiceContractAttribute contractAttribute;
return GetContractTypeAndAttribute(interfaceType, out contractAttribute);
}
static internal Type GetContractTypeAndAttribute(Type interfaceType, out ServiceContractAttribute contractAttribute)
{
contractAttribute = GetSingleAttribute<ServiceContractAttribute>(interfaceType);
if (contractAttribute != null)
{
return interfaceType;
}
List<Type> types = new List<Type>(GetInheritedContractTypes(interfaceType));
if (types.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.AttemptedToGetContractTypeForButThatTypeIs1, interfaceType.Name)));
}
foreach (Type potentialContractRoot in types)
{
bool mayBeTheRoot = true;
foreach (Type t in types)
{
if (!t.IsAssignableFrom(potentialContractRoot))
{
mayBeTheRoot = false;
}
}
if (mayBeTheRoot)
{
contractAttribute = GetSingleAttribute<ServiceContractAttribute>(potentialContractRoot);
return potentialContractRoot;
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.SFxNoMostDerivedContract, interfaceType.Name)));
}
private static List<MethodInfo> GetMethodsInternal(Type interfaceType)
{
List<MethodInfo> methods = new List<MethodInfo>();
foreach (MethodInfo mi in interfaceType.GetRuntimeMethods().Where(m => !m.IsStatic))
{
if (GetSingleAttribute<OperationContractAttribute>(mi) != null)
{
methods.Add(mi);
}
else if (GetFirstAttribute<IOperationContractAttributeProvider>(mi) != null)
{
methods.Add(mi);
}
}
return methods;
}
// The metadata for "in" versus "out" seems to be inconsistent, depending upon what compiler generates it.
// The following code assumes this is the truth table that all compilers will obey:
//
// True Parameter Type .IsIn .IsOut .ParameterType.IsByRef
//
// in F F F ...OR...
// in T F F
//
// in/out T T T ...OR...
// in/out F F T
//
// out F T T
static internal void ValidateParameterMetadata(MethodInfo methodInfo)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
if (!parameter.ParameterType.IsByRef)
{
if (parameter.IsOut)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.SFxBadByValueParameterMetadata,
methodInfo.Name, methodInfo.DeclaringType.Name)));
}
}
else
{
if (parameter.IsIn && !parameter.IsOut)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.SFxBadByReferenceParameterMetadata,
methodInfo.Name, methodInfo.DeclaringType.Name)));
}
}
}
}
static internal bool FlowsIn(ParameterInfo paramInfo) // conceptually both "in" and "in/out" params return true
{
return !paramInfo.IsOut || paramInfo.IsIn;
}
static internal bool FlowsOut(ParameterInfo paramInfo) // conceptually both "out" and "in/out" params return true
{
return paramInfo.ParameterType.IsByRef;
}
// for async method is the begin method
static internal ParameterInfo[] GetInputParameters(MethodInfo method, bool asyncPattern)
{
int count = 0;
ParameterInfo[] parameters = method.GetParameters();
// length of parameters we care about (-2 for async)
int len = parameters.Length;
if (asyncPattern)
{
len -= 2;
}
// count the ins
for (int i = 0; i < len; i++)
{
if (FlowsIn(parameters[i]))
{
count++;
}
}
// grab the ins
ParameterInfo[] result = new ParameterInfo[count];
int pos = 0;
for (int i = 0; i < len; i++)
{
ParameterInfo param = parameters[i];
if (FlowsIn(param))
{
result[pos++] = param;
}
}
return result;
}
// for async method is the end method
static internal ParameterInfo[] GetOutputParameters(MethodInfo method, bool asyncPattern)
{
int count = 0;
ParameterInfo[] parameters = method.GetParameters();
// length of parameters we care about (-1 for async)
int len = parameters.Length;
if (asyncPattern)
{
len -= 1;
}
// count the outs
for (int i = 0; i < len; i++)
{
if (FlowsOut(parameters[i]))
{
count++;
}
}
// grab the outs
ParameterInfo[] result = new ParameterInfo[count];
int pos = 0;
for (int i = 0; i < len; i++)
{
ParameterInfo param = parameters[i];
if (FlowsOut(param))
{
result[pos++] = param;
}
}
return result;
}
static internal bool HasOutputParameters(MethodInfo method, bool asyncPattern)
{
ParameterInfo[] parameters = method.GetParameters();
// length of parameters we care about (-1 for async)
int len = parameters.Length;
if (asyncPattern)
{
len -= 1;
}
// count the outs
for (int i = 0; i < len; i++)
{
if (FlowsOut(parameters[i]))
{
return true;
}
}
return false;
}
private static MethodInfo GetEndMethodInternal(MethodInfo beginMethod)
{
string logicalName = GetLogicalName(beginMethod);
string endMethodName = EndMethodNamePrefix + logicalName;
MethodInfo[] endMethods = beginMethod.DeclaringType.GetTypeInfo().GetDeclaredMethods(endMethodName).ToArray();
if (endMethods.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.NoEndMethodFoundForAsyncBeginMethod3, beginMethod.Name, beginMethod.DeclaringType.FullName, endMethodName)));
}
if (endMethods.Length > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.MoreThanOneEndMethodFoundForAsyncBeginMethod3, beginMethod.Name, beginMethod.DeclaringType.FullName, endMethodName)));
}
return (MethodInfo)endMethods[0];
}
static internal MethodInfo GetEndMethod(MethodInfo beginMethod)
{
MethodInfo endMethod = GetEndMethodInternal(beginMethod);
if (!HasEndMethodShape(endMethod))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidAsyncEndMethodSignatureForMethod2, endMethod.Name, endMethod.DeclaringType.FullName)));
}
return endMethod;
}
static internal XmlName GetOperationName(MethodInfo method)
{
OperationContractAttribute operationAttribute = GetOperationContractAttribute(method);
return NamingHelper.GetOperationName(GetLogicalName(method), operationAttribute.Name);
}
static internal bool HasBeginMethodShape(MethodInfo method)
{
ParameterInfo[] parameters = method.GetParameters();
if (!method.Name.StartsWith(BeginMethodNamePrefix, StringComparison.Ordinal) ||
parameters.Length < 2 ||
parameters[parameters.Length - 2].ParameterType != s_asyncCallbackType ||
parameters[parameters.Length - 1].ParameterType != s_objectType ||
method.ReturnType != s_asyncResultType)
{
return false;
}
return true;
}
static internal bool IsBegin(OperationContractAttribute opSettings, MethodInfo method)
{
if (opSettings.AsyncPattern)
{
if (!HasBeginMethodShape(method))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidAsyncBeginMethodSignatureForMethod2, method.Name, method.DeclaringType.FullName)));
}
return true;
}
return false;
}
static internal bool IsTask(MethodInfo method)
{
if (method.ReturnType == taskType)
{
return true;
}
if (method.ReturnType.IsGenericType() && method.ReturnType.GetGenericTypeDefinition() == taskTResultType)
{
return true;
}
return false;
}
static internal bool IsTask(MethodInfo method, out Type taskTResult)
{
taskTResult = null;
Type methodReturnType = method.ReturnType;
if (methodReturnType == taskType)
{
taskTResult = VoidType;
return true;
}
if (methodReturnType.IsGenericType() && methodReturnType.GetGenericTypeDefinition() == taskTResultType)
{
taskTResult = methodReturnType.GetGenericArguments()[0];
return true;
}
return false;
}
static internal bool HasEndMethodShape(MethodInfo method)
{
ParameterInfo[] parameters = method.GetParameters();
if (!method.Name.StartsWith(EndMethodNamePrefix, StringComparison.Ordinal) ||
parameters.Length < 1 ||
parameters[parameters.Length - 1].ParameterType != s_asyncResultType)
{
return false;
}
return true;
}
internal static OperationContractAttribute GetOperationContractAttribute(MethodInfo method)
{
OperationContractAttribute operationContractAttribute = GetSingleAttribute<OperationContractAttribute>(method);
if (operationContractAttribute != null)
{
return operationContractAttribute;
}
IOperationContractAttributeProvider operationContractProvider = GetFirstAttribute<IOperationContractAttributeProvider>(method);
if (operationContractProvider != null)
{
return operationContractProvider.GetOperationContractAttribute();
}
return null;
}
static internal bool IsBegin(MethodInfo method)
{
OperationContractAttribute opSettings = GetOperationContractAttribute(method);
if (opSettings == null)
return false;
return IsBegin(opSettings, method);
}
static internal string GetLogicalName(MethodInfo method)
{
bool isAsync = IsBegin(method);
bool isTask = isAsync ? false : IsTask(method);
return GetLogicalName(method, isAsync, isTask);
}
static internal string GetLogicalName(MethodInfo method, bool isAsync, bool isTask)
{
if (isAsync)
{
return method.Name.Substring(BeginMethodNamePrefix.Length);
}
else if (isTask && method.Name.EndsWith(AsyncMethodNameSuffix, StringComparison.Ordinal))
{
return method.Name.Substring(0, method.Name.Length - AsyncMethodNameSuffix.Length);
}
else
{
return method.Name;
}
}
static internal bool HasNoDisposableParameters(MethodInfo methodInfo)
{
foreach (ParameterInfo inputInfo in methodInfo.GetParameters())
{
if (IsParameterDisposable(inputInfo.ParameterType))
{
return false;
}
}
if (methodInfo.ReturnParameter != null)
{
return (!IsParameterDisposable(methodInfo.ReturnParameter.ParameterType));
}
return true;
}
static internal bool IsParameterDisposable(Type type)
{
return ((!type.IsSealed()) || typeof(IDisposable).IsAssignableFrom(type));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Hydra.Framework.Java
{
//
//**********************************************************************
/// <summary>
/// Java Specific Conversion Utilities
/// </summary>
//**********************************************************************
//
public class JavaUtils
{
#region Constructor
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:JavaUtils"/> class.
/// </summary>
//**********************************************************************
//
private JavaUtils()
{
}
#endregion
#region Public Static Methods
//
//**********************************************************************
/// <summary>
/// Gets the java date time.
/// </summary>
/// <param name="lngJavaDate">The Java DateTime ad a DateTime object</param>
/// <returns></returns>
//**********************************************************************
//
public static DateTime GetJavaDateTime(long lngJavaDate)
{
DateTime myDateTime = DateTime.MinValue;
try
{
DateTime UTCBaseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
myDateTime = UTCBaseTime.Add(new TimeSpan(lngJavaDate * TimeSpan.TicksPerMillisecond));
}
catch (Exception ex)
{
throw new Exception("GetJavaDateTime Reported the following exception: " + ex.ToString());
}
return myDateTime;
}
//
//**********************************************************************
/// <summary>
/// Sets the java datetime.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
//**********************************************************************
//
public static long SetJavaDatetime(DateTime date)
{
long javaTime;
try
{
DateTime UTCBaseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
TimeSpan ts = DateTime.Now.Subtract(UTCBaseTime);
javaTime = (long)ts.Seconds;
}
catch (Exception ex)
{
throw new Exception("GetJavaDateTime Reported the following exception: " + ex.ToString());
}
return javaTime;
}
//
// **********************************************************************
/// <summary>
/// Sets the java datetime.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
// **********************************************************************
//
public static long SetJavaDatetime(Nullable<DateTime> date)
{
long javaTime = -1;
try
{
if (date != null)
{
DateTime UTCBaseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
TimeSpan ts = DateTime.Now.Subtract(UTCBaseTime);
javaTime = (long)ts.Seconds;
}
}
catch (Exception ex)
{
throw new Exception("GetJavaDateTime Reported the following exception: " + ex.ToString());
}
return javaTime;
}
//
//**********************************************************************
/// <summary>
/// Base64s the encode.
/// </summary>
/// <param name="data">The data.</param>
/// <returns></returns>
//**********************************************************************
//
public static string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}
//
//**********************************************************************
/// <summary>
/// Base64s the decode.
/// </summary>
/// <param name="data">The data.</param>
/// <returns></returns>
//**********************************************************************
//
public static string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}
///
/// **********************************************************************
/// <summary>
/// Events the date.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
/// **********************************************************************
///
public static DateTime EventDate(string date)
{
string myDate = string.Empty;
DateTime newDate = DateTime.Now;
try
{
myDate = SubstituteMonth(Regex.Replace(date, getSepRegExp().ToString(), "$5/$6/$7 $1:$2:$3", RegexOptions.RightToLeft).ToLower());
if (!string.IsNullOrEmpty(myDate))
{
newDate = Convert.ToDateTime(myDate);
}
}
catch (Exception ex)
{
}
return newDate;
}
///
/// **********************************************************************
/// <summary>
/// Substitutes the month.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
/// **********************************************************************
///
public static string SubstituteMonth(string date)
{
string result = date;
if (date.IndexOf("jan") > 0)
result = date.Replace("jan", "01");
if (date.IndexOf("feb") > 0)
result = date.Replace("feb", "02");
if (date.IndexOf("mar") > 0)
result = date.Replace("mar", "03");
if (date.IndexOf("apr") > 0)
result = date.Replace("apr", "04");
if (date.IndexOf("may") > 0)
result = date.Replace("may", "05");
if (date.IndexOf("jun") > 0)
result = date.Replace("jun", "06");
if (date.IndexOf("jul") > 0)
result = date.Replace("jul", "07");
if (date.IndexOf("aug") > 0)
result = date.Replace("aug", "08");
if (date.IndexOf("sep") > 0)
result = date.Replace("sep", "09");
if (date.IndexOf("oct") > 0)
result = date.Replace("oct", "10");
if (date.IndexOf("nov") > 0)
result = date.Replace("nov", "11");
if (date.IndexOf("dec") > 0)
result = date.Replace("dec", "12");
return result;
}
//
//**********************************************************************
/// <summary>
/// Gets the sep reg exp.
/// </summary>
/// <returns></returns>
//**********************************************************************
//
private static Regex getSepRegExp()
{
return new Regex(@"([0-9]{2}):([0-9]{2}):([0-9]{2}) ([A-z]{3}) ([0-9]{2}) ([A-z]{3}) ([0-9]{4})", RegexOptions.IgnoreCase);
}
#endregion
}
}
| |
namespace TabBorderStyles
{
partial class Form1
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.groupBoxTabBorderStyles = new System.Windows.Forms.GroupBox();
this.radioSO = new System.Windows.Forms.RadioButton();
this.radioSE = new System.Windows.Forms.RadioButton();
this.radioON = new System.Windows.Forms.RadioButton();
this.radioSOB = new System.Windows.Forms.RadioButton();
this.radioSOF = new System.Windows.Forms.RadioButton();
this.radioSON = new System.Windows.Forms.RadioButton();
this.radioSEB = new System.Windows.Forms.RadioButton();
this.radioSEF = new System.Windows.Forms.RadioButton();
this.radioSEN = new System.Windows.Forms.RadioButton();
this.radioROL = new System.Windows.Forms.RadioButton();
this.radioROM = new System.Windows.Forms.RadioButton();
this.radioROS = new System.Windows.Forms.RadioButton();
this.radioREL = new System.Windows.Forms.RadioButton();
this.radioREM = new System.Windows.Forms.RadioButton();
this.radioRES = new System.Windows.Forms.RadioButton();
this.radioSOL = new System.Windows.Forms.RadioButton();
this.radioSOM = new System.Windows.Forms.RadioButton();
this.radioSOS = new System.Windows.Forms.RadioButton();
this.radioSEL = new System.Windows.Forms.RadioButton();
this.radioSEM = new System.Windows.Forms.RadioButton();
this.radioSES = new System.Windows.Forms.RadioButton();
this.kryptonNavigator = new ComponentFactory.Krypton.Navigator.KryptonNavigator();
this.kryptonPage1 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.kryptonPage2 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.kryptonPage3 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.kryptonPage4 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.kryptonPage5 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.kryptonPage6 = new ComponentFactory.Krypton.Navigator.KryptonPage();
this.buttonClose = new System.Windows.Forms.Button();
this.groupBoxTabStyles = new System.Windows.Forms.GroupBox();
this.radioOneNote = new System.Windows.Forms.RadioButton();
this.radioLP = new System.Windows.Forms.RadioButton();
this.radioSP = new System.Windows.Forms.RadioButton();
this.radioHP = new System.Windows.Forms.RadioButton();
this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.groupBoxTabBorderStyles.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonNavigator)).BeginInit();
this.kryptonNavigator.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage6)).BeginInit();
this.groupBoxTabStyles.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTabBorderStyles
//
this.groupBoxTabBorderStyles.Controls.Add(this.radioSO);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSE);
this.groupBoxTabBorderStyles.Controls.Add(this.radioON);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSOB);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSOF);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSON);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSEB);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSEF);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSEN);
this.groupBoxTabBorderStyles.Controls.Add(this.radioROL);
this.groupBoxTabBorderStyles.Controls.Add(this.radioROM);
this.groupBoxTabBorderStyles.Controls.Add(this.radioROS);
this.groupBoxTabBorderStyles.Controls.Add(this.radioREL);
this.groupBoxTabBorderStyles.Controls.Add(this.radioREM);
this.groupBoxTabBorderStyles.Controls.Add(this.radioRES);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSOL);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSOM);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSOS);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSEL);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSEM);
this.groupBoxTabBorderStyles.Controls.Add(this.radioSES);
this.groupBoxTabBorderStyles.Location = new System.Drawing.Point(12, 12);
this.groupBoxTabBorderStyles.Name = "groupBoxTabBorderStyles";
this.groupBoxTabBorderStyles.Size = new System.Drawing.Size(596, 181);
this.groupBoxTabBorderStyles.TabIndex = 0;
this.groupBoxTabBorderStyles.TabStop = false;
this.groupBoxTabBorderStyles.Text = "Tab Border Styles";
//
// radioSO
//
this.radioSO.AutoSize = true;
this.radioSO.Location = new System.Drawing.Point(485, 46);
this.radioSO.Name = "radioSO";
this.radioSO.Size = new System.Drawing.Size(100, 17);
this.radioSO.TabIndex = 19;
this.radioSO.Tag = "SmoothOutsize";
this.radioSO.Text = "Smooth Outsize";
this.radioSO.UseVisualStyleBackColor = true;
this.radioSO.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSE
//
this.radioSE.AutoSize = true;
this.radioSE.Location = new System.Drawing.Point(485, 23);
this.radioSE.Name = "radioSE";
this.radioSE.Size = new System.Drawing.Size(90, 17);
this.radioSE.TabIndex = 18;
this.radioSE.Tag = "SmoothEqual";
this.radioSE.Text = "Smooth Equal";
this.radioSE.UseVisualStyleBackColor = true;
this.radioSE.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioON
//
this.radioON.AutoSize = true;
this.radioON.Location = new System.Drawing.Point(485, 104);
this.radioON.Name = "radioON";
this.radioON.Size = new System.Drawing.Size(68, 17);
this.radioON.TabIndex = 20;
this.radioON.Tag = "OneNote";
this.radioON.Text = "OneNote";
this.radioON.UseVisualStyleBackColor = true;
this.radioON.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSOB
//
this.radioSOB.AutoSize = true;
this.radioSOB.Location = new System.Drawing.Point(340, 150);
this.radioSOB.Name = "radioSOB";
this.radioSOB.Size = new System.Drawing.Size(113, 17);
this.radioSOB.TabIndex = 17;
this.radioSOB.Tag = "SlantOutsizeBoth";
this.radioSOB.Text = "Slant Outsize Both";
this.radioSOB.UseVisualStyleBackColor = true;
this.radioSOB.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSOF
//
this.radioSOF.AutoSize = true;
this.radioSOF.Location = new System.Drawing.Point(340, 127);
this.radioSOF.Name = "radioSOF";
this.radioSOF.Size = new System.Drawing.Size(107, 17);
this.radioSOF.TabIndex = 16;
this.radioSOF.Tag = "SlantOutsizeFar";
this.radioSOF.Text = "Slant Outsize Far";
this.radioSOF.UseVisualStyleBackColor = true;
this.radioSOF.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSON
//
this.radioSON.AutoSize = true;
this.radioSON.Location = new System.Drawing.Point(340, 104);
this.radioSON.Name = "radioSON";
this.radioSON.Size = new System.Drawing.Size(114, 17);
this.radioSON.TabIndex = 15;
this.radioSON.Tag = "SlantOutsizeNear";
this.radioSON.Text = "Slant Outsize Near";
this.radioSON.UseVisualStyleBackColor = true;
this.radioSON.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSEB
//
this.radioSEB.AutoSize = true;
this.radioSEB.Location = new System.Drawing.Point(340, 69);
this.radioSEB.Name = "radioSEB";
this.radioSEB.Size = new System.Drawing.Size(103, 17);
this.radioSEB.TabIndex = 14;
this.radioSEB.Tag = "SlantEqualBoth";
this.radioSEB.Text = "Slant Equal Both";
this.radioSEB.UseVisualStyleBackColor = true;
this.radioSEB.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSEF
//
this.radioSEF.AutoSize = true;
this.radioSEF.Location = new System.Drawing.Point(340, 46);
this.radioSEF.Name = "radioSEF";
this.radioSEF.Size = new System.Drawing.Size(97, 17);
this.radioSEF.TabIndex = 13;
this.radioSEF.Tag = "SlantEqualFar";
this.radioSEF.Text = "Slant Equal Far";
this.radioSEF.UseVisualStyleBackColor = true;
this.radioSEF.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSEN
//
this.radioSEN.AutoSize = true;
this.radioSEN.Location = new System.Drawing.Point(340, 23);
this.radioSEN.Name = "radioSEN";
this.radioSEN.Size = new System.Drawing.Size(104, 17);
this.radioSEN.TabIndex = 12;
this.radioSEN.Tag = "SlantEqualNear";
this.radioSEN.Text = "Slant Equal Near";
this.radioSEN.UseVisualStyleBackColor = true;
this.radioSEN.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioROL
//
this.radioROL.AutoSize = true;
this.radioROL.Location = new System.Drawing.Point(173, 150);
this.radioROL.Name = "radioROL";
this.radioROL.Size = new System.Drawing.Size(137, 17);
this.radioROL.TabIndex = 11;
this.radioROL.Tag = "RoundedOutsizeLarge";
this.radioROL.Text = "Rounded Outsize Large";
this.radioROL.UseVisualStyleBackColor = true;
this.radioROL.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioROM
//
this.radioROM.AutoSize = true;
this.radioROM.Checked = true;
this.radioROM.Location = new System.Drawing.Point(173, 127);
this.radioROM.Name = "radioROM";
this.radioROM.Size = new System.Drawing.Size(146, 17);
this.radioROM.TabIndex = 10;
this.radioROM.TabStop = true;
this.radioROM.Tag = "RoundedOutsizeMedium";
this.radioROM.Text = "Rounded Outsize Medium";
this.radioROM.UseVisualStyleBackColor = true;
this.radioROM.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioROS
//
this.radioROS.AutoSize = true;
this.radioROS.Location = new System.Drawing.Point(173, 104);
this.radioROS.Name = "radioROS";
this.radioROS.Size = new System.Drawing.Size(134, 17);
this.radioROS.TabIndex = 9;
this.radioROS.Tag = "RoundedOutsizeSmall";
this.radioROS.Text = "Rounded Outsize Small";
this.radioROS.UseVisualStyleBackColor = true;
this.radioROS.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioREL
//
this.radioREL.AutoSize = true;
this.radioREL.Location = new System.Drawing.Point(173, 69);
this.radioREL.Name = "radioREL";
this.radioREL.Size = new System.Drawing.Size(127, 17);
this.radioREL.TabIndex = 8;
this.radioREL.Tag = "RoundedEqualLarge";
this.radioREL.Text = "Rounded Equal Large";
this.radioREL.UseVisualStyleBackColor = true;
this.radioREL.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioREM
//
this.radioREM.AutoSize = true;
this.radioREM.Location = new System.Drawing.Point(173, 46);
this.radioREM.Name = "radioREM";
this.radioREM.Size = new System.Drawing.Size(136, 17);
this.radioREM.TabIndex = 7;
this.radioREM.Tag = "RoundedEqualMedium";
this.radioREM.Text = "Rounded Equal Medium";
this.radioREM.UseVisualStyleBackColor = true;
this.radioREM.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioRES
//
this.radioRES.AutoSize = true;
this.radioRES.Location = new System.Drawing.Point(173, 23);
this.radioRES.Name = "radioRES";
this.radioRES.Size = new System.Drawing.Size(124, 17);
this.radioRES.TabIndex = 6;
this.radioRES.Tag = "RoundedEqualSmall";
this.radioRES.Text = "Rounded Equal Small";
this.radioRES.UseVisualStyleBackColor = true;
this.radioRES.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSOL
//
this.radioSOL.AutoSize = true;
this.radioSOL.Location = new System.Drawing.Point(16, 150);
this.radioSOL.Name = "radioSOL";
this.radioSOL.Size = new System.Drawing.Size(128, 17);
this.radioSOL.TabIndex = 5;
this.radioSOL.Tag = "SquareOutsizeLarge";
this.radioSOL.Text = "Square Outsize Large";
this.radioSOL.UseVisualStyleBackColor = true;
this.radioSOL.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSOM
//
this.radioSOM.AutoSize = true;
this.radioSOM.Location = new System.Drawing.Point(16, 127);
this.radioSOM.Name = "radioSOM";
this.radioSOM.Size = new System.Drawing.Size(137, 17);
this.radioSOM.TabIndex = 4;
this.radioSOM.Tag = "SquareOutsizeMedium";
this.radioSOM.Text = "Square Outsize Medium";
this.radioSOM.UseVisualStyleBackColor = true;
this.radioSOM.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSOS
//
this.radioSOS.AutoSize = true;
this.radioSOS.Location = new System.Drawing.Point(16, 104);
this.radioSOS.Name = "radioSOS";
this.radioSOS.Size = new System.Drawing.Size(125, 17);
this.radioSOS.TabIndex = 3;
this.radioSOS.Tag = "SquareOutsizeSmall";
this.radioSOS.Text = "Square Outsize Small";
this.radioSOS.UseVisualStyleBackColor = true;
this.radioSOS.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSEL
//
this.radioSEL.AutoSize = true;
this.radioSEL.Location = new System.Drawing.Point(16, 69);
this.radioSEL.Name = "radioSEL";
this.radioSEL.Size = new System.Drawing.Size(118, 17);
this.radioSEL.TabIndex = 2;
this.radioSEL.Tag = "SquareEqualLarge";
this.radioSEL.Text = "Square Equal Large";
this.radioSEL.UseVisualStyleBackColor = true;
this.radioSEL.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSEM
//
this.radioSEM.AutoSize = true;
this.radioSEM.Location = new System.Drawing.Point(16, 46);
this.radioSEM.Name = "radioSEM";
this.radioSEM.Size = new System.Drawing.Size(127, 17);
this.radioSEM.TabIndex = 1;
this.radioSEM.Tag = "SquareEqualMedium";
this.radioSEM.Text = "Square Equal Medium";
this.radioSEM.UseVisualStyleBackColor = true;
this.radioSEM.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// radioSES
//
this.radioSES.AutoSize = true;
this.radioSES.Location = new System.Drawing.Point(16, 23);
this.radioSES.Name = "radioSES";
this.radioSES.Size = new System.Drawing.Size(115, 17);
this.radioSES.TabIndex = 0;
this.radioSES.Tag = "SquareEqualSmall";
this.radioSES.Text = "Square Equal Small";
this.radioSES.UseVisualStyleBackColor = true;
this.radioSES.CheckedChanged += new System.EventHandler(this.tabBorderStyles_CheckedChanged);
//
// kryptonNavigator
//
this.kryptonNavigator.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.kryptonNavigator.Button.ButtonDisplayLogic = ComponentFactory.Krypton.Navigator.ButtonDisplayLogic.None;
this.kryptonNavigator.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide;
this.kryptonNavigator.Location = new System.Drawing.Point(12, 271);
this.kryptonNavigator.Name = "kryptonNavigator";
this.kryptonNavigator.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] {
this.kryptonPage1,
this.kryptonPage2,
this.kryptonPage3,
this.kryptonPage4,
this.kryptonPage5,
this.kryptonPage6});
this.kryptonNavigator.SelectedIndex = 0;
this.kryptonNavigator.Size = new System.Drawing.Size(597, 104);
this.kryptonNavigator.TabIndex = 2;
this.kryptonNavigator.Text = "kryptonNavigator1";
//
// kryptonPage1
//
this.kryptonPage1.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage1.Flags = 65534;
this.kryptonPage1.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage1.ImageLarge")));
this.kryptonPage1.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage1.ImageMedium")));
this.kryptonPage1.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage1.ImageSmall")));
this.kryptonPage1.LastVisibleSet = true;
this.kryptonPage1.MinimumSize = new System.Drawing.Size(50, 50);
this.kryptonPage1.Name = "kryptonPage1";
this.kryptonPage1.Size = new System.Drawing.Size(595, 78);
this.kryptonPage1.Text = "Page 1";
this.kryptonPage1.ToolTipTitle = "Page ToolTip";
this.kryptonPage1.UniqueName = "A605A21768024BACA605A21768024BAC";
//
// kryptonPage2
//
this.kryptonPage2.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage2.Flags = 65534;
this.kryptonPage2.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage2.ImageLarge")));
this.kryptonPage2.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage2.ImageMedium")));
this.kryptonPage2.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage2.ImageSmall")));
this.kryptonPage2.LastVisibleSet = true;
this.kryptonPage2.MinimumSize = new System.Drawing.Size(50, 50);
this.kryptonPage2.Name = "kryptonPage2";
this.kryptonPage2.Size = new System.Drawing.Size(595, 77);
this.kryptonPage2.Text = "Page 2";
this.kryptonPage2.ToolTipTitle = "Page ToolTip";
this.kryptonPage2.UniqueName = "0DD3743DCEDF48C70DD3743DCEDF48C7";
//
// kryptonPage3
//
this.kryptonPage3.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage3.Flags = 65534;
this.kryptonPage3.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage3.ImageLarge")));
this.kryptonPage3.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage3.ImageMedium")));
this.kryptonPage3.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage3.ImageSmall")));
this.kryptonPage3.LastVisibleSet = true;
this.kryptonPage3.MinimumSize = new System.Drawing.Size(50, 50);
this.kryptonPage3.Name = "kryptonPage3";
this.kryptonPage3.Size = new System.Drawing.Size(595, 77);
this.kryptonPage3.Text = "Page 3";
this.kryptonPage3.ToolTipTitle = "Page ToolTip";
this.kryptonPage3.UniqueName = "0BE20839F0EE48560BE20839F0EE4856";
//
// kryptonPage4
//
this.kryptonPage4.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage4.Flags = 65534;
this.kryptonPage4.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage4.ImageLarge")));
this.kryptonPage4.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage4.ImageMedium")));
this.kryptonPage4.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage4.ImageSmall")));
this.kryptonPage4.LastVisibleSet = true;
this.kryptonPage4.MinimumSize = new System.Drawing.Size(50, 50);
this.kryptonPage4.Name = "kryptonPage4";
this.kryptonPage4.Size = new System.Drawing.Size(595, 77);
this.kryptonPage4.Text = "Page 4";
this.kryptonPage4.ToolTipTitle = "Page ToolTip";
this.kryptonPage4.UniqueName = "86262F40276048FF86262F40276048FF";
//
// kryptonPage5
//
this.kryptonPage5.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage5.Flags = 65534;
this.kryptonPage5.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage5.ImageLarge")));
this.kryptonPage5.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage5.ImageMedium")));
this.kryptonPage5.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage5.ImageSmall")));
this.kryptonPage5.LastVisibleSet = true;
this.kryptonPage5.MinimumSize = new System.Drawing.Size(50, 50);
this.kryptonPage5.Name = "kryptonPage5";
this.kryptonPage5.Size = new System.Drawing.Size(595, 77);
this.kryptonPage5.Text = "Page 5";
this.kryptonPage5.ToolTipTitle = "Page ToolTip";
this.kryptonPage5.UniqueName = "398DE3D4C2F343B2398DE3D4C2F343B2";
//
// kryptonPage6
//
this.kryptonPage6.AutoHiddenSlideSize = new System.Drawing.Size(200, 200);
this.kryptonPage6.Flags = 65534;
this.kryptonPage6.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonPage6.ImageLarge")));
this.kryptonPage6.ImageMedium = ((System.Drawing.Image)(resources.GetObject("kryptonPage6.ImageMedium")));
this.kryptonPage6.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonPage6.ImageSmall")));
this.kryptonPage6.LastVisibleSet = true;
this.kryptonPage6.MinimumSize = new System.Drawing.Size(50, 50);
this.kryptonPage6.Name = "kryptonPage6";
this.kryptonPage6.Size = new System.Drawing.Size(595, 77);
this.kryptonPage6.Text = "Page 6";
this.kryptonPage6.ToolTipTitle = "Page ToolTip";
this.kryptonPage6.UniqueName = "140EC00B9F8A4042140EC00B9F8A4042";
//
// buttonClose
//
this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonClose.Location = new System.Drawing.Point(534, 385);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 23);
this.buttonClose.TabIndex = 3;
this.buttonClose.Text = "Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// groupBoxTabStyles
//
this.groupBoxTabStyles.Controls.Add(this.radioOneNote);
this.groupBoxTabStyles.Controls.Add(this.radioLP);
this.groupBoxTabStyles.Controls.Add(this.radioSP);
this.groupBoxTabStyles.Controls.Add(this.radioHP);
this.groupBoxTabStyles.Location = new System.Drawing.Point(12, 200);
this.groupBoxTabStyles.Name = "groupBoxTabStyles";
this.groupBoxTabStyles.Size = new System.Drawing.Size(595, 57);
this.groupBoxTabStyles.TabIndex = 1;
this.groupBoxTabStyles.TabStop = false;
this.groupBoxTabStyles.Text = "Tab Styles";
//
// radioOneNote
//
this.radioOneNote.AutoSize = true;
this.radioOneNote.Location = new System.Drawing.Point(485, 25);
this.radioOneNote.Name = "radioOneNote";
this.radioOneNote.Size = new System.Drawing.Size(68, 17);
this.radioOneNote.TabIndex = 3;
this.radioOneNote.Tag = "OneNote";
this.radioOneNote.Text = "OneNote";
this.radioOneNote.UseVisualStyleBackColor = true;
this.radioOneNote.CheckedChanged += new System.EventHandler(this.tabStyles_CheckedChanged);
//
// radioLP
//
this.radioLP.AutoSize = true;
this.radioLP.Location = new System.Drawing.Point(340, 25);
this.radioLP.Name = "radioLP";
this.radioLP.Size = new System.Drawing.Size(77, 17);
this.radioLP.TabIndex = 2;
this.radioLP.Tag = "LowProfile";
this.radioLP.Text = "Low Profile";
this.radioLP.UseVisualStyleBackColor = true;
this.radioLP.CheckedChanged += new System.EventHandler(this.tabStyles_CheckedChanged);
//
// radioSP
//
this.radioSP.AutoSize = true;
this.radioSP.Location = new System.Drawing.Point(173, 25);
this.radioSP.Name = "radioSP";
this.radioSP.Size = new System.Drawing.Size(102, 17);
this.radioSP.TabIndex = 1;
this.radioSP.Tag = "StandardProfile";
this.radioSP.Text = "Standard Profile";
this.radioSP.UseVisualStyleBackColor = true;
this.radioSP.CheckedChanged += new System.EventHandler(this.tabStyles_CheckedChanged);
//
// radioHP
//
this.radioHP.AutoSize = true;
this.radioHP.Checked = true;
this.radioHP.Location = new System.Drawing.Point(16, 25);
this.radioHP.Name = "radioHP";
this.radioHP.Size = new System.Drawing.Size(79, 17);
this.radioHP.TabIndex = 0;
this.radioHP.TabStop = true;
this.radioHP.Tag = "HighProfile";
this.radioHP.Text = "High Profile";
this.radioHP.UseVisualStyleBackColor = true;
this.radioHP.CheckedChanged += new System.EventHandler(this.tabStyles_CheckedChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(619, 418);
this.Controls.Add(this.groupBoxTabStyles);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.kryptonNavigator);
this.Controls.Add(this.groupBoxTabBorderStyles);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(627, 452);
this.Name = "Form1";
this.Text = "Tab Border Styles";
this.groupBoxTabBorderStyles.ResumeLayout(false);
this.groupBoxTabBorderStyles.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonNavigator)).EndInit();
this.kryptonNavigator.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonPage1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonPage6)).EndInit();
this.groupBoxTabStyles.ResumeLayout(false);
this.groupBoxTabStyles.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBoxTabBorderStyles;
private ComponentFactory.Krypton.Navigator.KryptonNavigator kryptonNavigator;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage1;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage2;
private System.Windows.Forms.RadioButton radioROL;
private System.Windows.Forms.RadioButton radioROM;
private System.Windows.Forms.RadioButton radioROS;
private System.Windows.Forms.RadioButton radioREL;
private System.Windows.Forms.RadioButton radioREM;
private System.Windows.Forms.RadioButton radioRES;
private System.Windows.Forms.RadioButton radioSOL;
private System.Windows.Forms.RadioButton radioSOM;
private System.Windows.Forms.RadioButton radioSOS;
private System.Windows.Forms.RadioButton radioSEL;
private System.Windows.Forms.RadioButton radioSEM;
private System.Windows.Forms.RadioButton radioSES;
private System.Windows.Forms.RadioButton radioSO;
private System.Windows.Forms.RadioButton radioSE;
private System.Windows.Forms.RadioButton radioON;
private System.Windows.Forms.RadioButton radioSOB;
private System.Windows.Forms.RadioButton radioSOF;
private System.Windows.Forms.RadioButton radioSON;
private System.Windows.Forms.RadioButton radioSEB;
private System.Windows.Forms.RadioButton radioSEF;
private System.Windows.Forms.RadioButton radioSEN;
private System.Windows.Forms.Button buttonClose;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage3;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage4;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage5;
private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage6;
private System.Windows.Forms.GroupBox groupBoxTabStyles;
private System.Windows.Forms.RadioButton radioLP;
private System.Windows.Forms.RadioButton radioSP;
private System.Windows.Forms.RadioButton radioHP;
private System.Windows.Forms.RadioButton radioOneNote;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.CodeAnalysis.Editing
{
/// <summary>
/// An editor for making changes to a syntax tree.
/// </summary>
public class SyntaxEditor
{
private readonly SyntaxGenerator _generator;
private readonly SyntaxNode _root;
private readonly List<Change> _changes;
/// <summary>
/// Creates a new <see cref="SyntaxEditor"/> instance.
/// </summary>
public SyntaxEditor(SyntaxNode root, Workspace workspace)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
_root = root;
_generator = SyntaxGenerator.GetGenerator(workspace, root.Language);
_changes = new List<Change>();
}
/// <summary>
/// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed.
/// </summary>
public SyntaxNode OriginalRoot
{
get { return _root; }
}
/// <summary>
/// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s.
/// </summary>
public SyntaxGenerator Generator
{
get { return _generator; }
}
/// <summary>
/// Returns the changed root node.
/// </summary>
public SyntaxNode GetChangedRoot()
{
var nodes = Enumerable.Distinct(_changes.Select(c => c.Node));
var newRoot = _root.TrackNodes(nodes);
foreach (var change in _changes)
{
newRoot = change.Apply(newRoot, _generator);
}
return newRoot;
}
/// <summary>
/// Makes sure the node is tracked, even if it is not changed.
/// </summary>
public void TrackNode(SyntaxNode node)
{
CheckNodeInTree(node);
_changes.Add(new NoChange(node));
}
/// <summary>
/// Remove the node from the tree.
/// </summary>
/// <param name="node">The node to remove that currently exists as part of the tree.</param>
public void RemoveNode(SyntaxNode node)
{
RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions);
}
/// <summary>
/// Remove the node from the tree.
/// </summary>
/// <param name="node">The node to remove that currently exists as part of the tree.</param>
/// <param name="options">Options that affect how node removal works.</param>
public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options)
{
CheckNodeInTree(node);
_changes.Add(new RemoveChange(node, options));
}
/// <summary>
/// Replace the specified node with a node produced by the function.
/// </summary>
/// <param name="node">The node to replace that already exists in the tree.</param>
/// <param name="computeReplacement">A function that computes a replacement node.
/// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param>
public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement)
{
CheckNodeInTree(node);
_changes.Add(new ReplaceChange(node, computeReplacement));
}
internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument)
{
CheckNodeInTree(node);
_changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument));
}
/// <summary>
/// Replace the specified node with a different node.
/// </summary>
/// <param name="node">The node to replace that already exists in the tree.</param>
/// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param>
public void ReplaceNode(SyntaxNode node, SyntaxNode newNode)
{
CheckNodeInTree(node);
if (node == newNode)
{
return;
}
this.ReplaceNode(node, (n, g) => newNode);
}
/// <summary>
/// Insert the new nodes before the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param>
/// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes)
{
CheckNodeInTree(node);
_changes.Add(new InsertChange(node, newNodes, isBefore: true));
}
/// <summary>
/// Insert the new node before the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param>
/// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertBefore(SyntaxNode node, SyntaxNode newNode)
{
CheckNodeInTree(node);
this.InsertBefore(node, new[] { newNode });
}
/// <summary>
/// Insert the new nodes after the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param>
/// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes)
{
CheckNodeInTree(node);
_changes.Add(new InsertChange(node, newNodes, isBefore: false));
}
/// <summary>
/// Insert the new node after the specified node already existing in the tree.
/// </summary>
/// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param>
/// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param>
public void InsertAfter(SyntaxNode node, SyntaxNode newNode)
{
CheckNodeInTree(node);
this.InsertAfter(node, new[] { newNode });
}
private void CheckNodeInTree(SyntaxNode node)
{
if (!_root.Contains(node))
{
throw new ArgumentException(Microsoft.CodeAnalysis.WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node));
}
}
private abstract class Change
{
internal readonly SyntaxNode Node;
public Change(SyntaxNode node)
{
this.Node = node;
}
public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator);
}
private class NoChange : Change
{
public NoChange(SyntaxNode node)
: base(node)
{
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
return root;
}
}
private class RemoveChange : Change
{
private readonly SyntaxRemoveOptions _options;
public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options)
: base(node)
{
_options = options;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
return generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options);
}
}
private class ReplaceChange : Change
{
private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode> _modifier;
public ReplaceChange(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> modifier)
: base(node)
{
_modifier = modifier;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
var current = root.GetCurrentNode(this.Node);
var newNode = _modifier(current, generator);
return generator.ReplaceNode(root, current, newNode);
}
}
private class ReplaceChange<TArgument> : Change
{
private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier;
private readonly TArgument _argument;
public ReplaceChange(
SyntaxNode node,
Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier,
TArgument argument)
: base(node)
{
_modifier = modifier;
_argument = argument;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
var current = root.GetCurrentNode(this.Node);
var newNode = _modifier(current, generator, _argument);
return generator.ReplaceNode(root, current, newNode);
}
}
private class InsertChange : Change
{
private readonly List<SyntaxNode> _newNodes;
private readonly bool _isBefore;
public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore)
: base(node)
{
_newNodes = newNodes.ToList();
_isBefore = isBefore;
}
public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator)
{
if (_isBefore)
{
return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes);
}
else
{
return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes);
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// load gui used to display various metric outputs
exec("~/art/gui/FrameOverlayGui.gui");
// Note: To implement your own metrics overlay
// just add a function with a name in the form
// XXXXMetricsCallback which can be enabled via
// metrics( XXXX )
function fpsMetricsCallback()
{
return " | FPS |" @
" " @ $fps::real @
" max: " @ $fps::realMax @
" min: " @ $fps::realMin @
" mspf: " @ 1000 / $fps::real;
}
function gfxMetricsCallback()
{
return " | GFX |" @
" PolyCount: " @ $GFXDeviceStatistics::polyCount @
" DrawCalls: " @ $GFXDeviceStatistics::drawCalls @
" RTChanges: " @ $GFXDeviceStatistics::renderTargetChanges;
}
function terrainMetricsCallback()
{
return " | Terrain |" @
" Cells: " @ $TerrainBlock::cellsRendered @
" Override Cells: " @ $TerrainBlock::overrideCells @
" DrawCalls: " @ $TerrainBlock::drawCalls;
}
function netMetricsCallback()
{
return " | Net |" @
" BitsSent: " @ $Stats::netBitsSent @
" BitsRcvd: " @ $Stats::netBitsReceived @
" GhostUpd: " @ $Stats::netGhostUpdates;
}
function groundCoverMetricsCallback()
{
return " | GroundCover |" @
" Cells: " @ $GroundCover::renderedCells @
" Billboards: " @ $GroundCover::renderedBillboards @
" Batches: " @ $GroundCover::renderedBatches @
" Shapes: " @ $GroundCover::renderedShapes;
}
function forestMetricsCallback()
{
return " | Forest |" @
" Cells: " @ $Forest::totalCells @
" Cells Meshed: " @ $Forest::cellsRendered @
" Cells Billboarded: " @ $Forest::cellsBatched @
" Meshes: " @ $Forest::cellItemsRendered @
" Billboards: " @ $Forest::cellItemsBatched;
}
function sfxMetricsCallback()
{
return " | SFX |" @
" Sounds: " @ $SFX::numSounds @
" Lists: " @ ( $SFX::numSources - $SFX::numSounds - $SFX::Device::fmodNumEventSource ) @
" Events: " @ $SFX::fmodNumEventSources @
" Playing: " @ $SFX::numPlaying @
" Culled: " @ $SFX::numCulled @
" Voices: " @ $SFX::numVoices @
" Buffers: " @ $SFX::Device::numBuffers @
" Memory: " @ ( $SFX::Device::numBufferBytes / 1024.0 / 1024.0 ) @ " MB" @
" Time/S: " @ $SFX::sourceUpdateTime @
" Time/P: " @ $SFX::parameterUpdateTime @
" Time/A: " @ $SFX::ambientUpdateTime;
}
function sfxSourcesMetricsCallback()
{
return sfxDumpSourcesToString();
}
function sfxStatesMetricsCallback()
{
return " | SFXStates |" @ sfxGetActiveStates();
}
function timeMetricsCallback()
{
return " | Time |" @
" Sim Time: " @ getSimTime() @
" Mod: " @ getSimTime() % 32;
}
function reflectMetricsCallback()
{
return " | REFLECT |" @
" Objects: " @ $Reflect::numObjects @
" Visible: " @ $Reflect::numVisible @
" Occluded: " @ $Reflect::numOccluded @
" Updated: " @ $Reflect::numUpdated @
" Elapsed: " @ $Reflect::elapsed NL
" Allocated: " @ $Reflect::renderTargetsAllocated @
" Pooled: " @ $Reflect::poolSize NL
" " @ getWord( $Reflect::textureStats, 1 ) TAB
" " @ getWord( $Reflect::textureStats, 2 ) @ "MB" TAB
" " @ getWord( $Reflect::textureStats, 0 );
}
function decalMetricsCallback()
{
return " | DECAL |" @
" Batches: " @ $Decal::Batches @
" Buffers: " @ $Decal::Buffers @
" DecalsRendered: " @ $Decal::DecalsRendered;
}
function renderMetricsCallback()
{
return " | Render |" @
" Int: " @ $RenderMetrics::RIT_Interior @
" IntDL: " @ $RenderMetrics::RIT_InteriorDynamicLighting @
" Mesh: " @ $RenderMetrics::RIT_Mesh @
" MeshDL: " @ $RenderMetrics::RIT_MeshDynamicLighting @
" Shadow: " @ $RenderMetrics::RIT_Shadow @
" Sky: " @ $RenderMetrics::RIT_Sky @
" Obj: " @ $RenderMetrics::RIT_Object @
" ObjT: " @ $RenderMetrics::RIT_ObjectTranslucent @
" Decal: " @ $RenderMetrics::RIT_Decal @
" Water: " @ $RenderMetrics::RIT_Water @
" Foliage: " @ $RenderMetrics::RIT_Foliage @
" Trans: " @ $RenderMetris::RIT_Translucent @
" Custom: " @ $RenderMetrics::RIT_Custom;
}
function shadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $ShadowStats::activeMaps @
" Updated: " @ $ShadowStats::updatedMaps @
" PolyCount: " @ $ShadowStats::polyCount @
" DrawCalls: " @ $ShadowStats::drawCalls @
" RTChanges: " @ $ShadowStats::rtChanges @
" PoolTexCount: " @ $ShadowStats::poolTexCount @
" PoolTexMB: " @ $ShadowStats::poolTexMemory @ "MB";
}
function basicShadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $BasicLightManagerStats::activePlugins @
" Updated: " @ $BasicLightManagerStats::shadowsUpdated @
" Elapsed Ms: " @ $BasicLightManagerStats::elapsedUpdateMs;
}
function lightMetricsCallback()
{
return " | Deferred Lights |" @
" Active: " @ $lightMetrics::activeLights @
" Culled: " @ $lightMetrics::culledLights;
}
function particleMetricsCallback()
{
return " | Particles |" @
" # Simulated " @ $particle::numSimulated;
}
function partMetricsCallback()
{
return particleMetricsCallback();
}
// alias
function audioMetricsCallback()
{
return sfxMetricsCallback();
}
// alias
function videoMetricsCallback()
{
return gfxMetricsCallback();
}
// Add a metrics HUD. %expr can be a vector of names where each element
// must have a corresponding '<name>MetricsCallback()' function defined
// that will be called on each update of the GUI control. The results
// of each function are stringed together.
//
// Example: metrics( "fps gfx" );
function metrics( %expr )
{
%metricsExpr = "";
if( %expr !$= "" )
{
for( %i = 0;; %i ++ )
{
%name = getWord( %expr, %i );
if( %name $= "" )
break;
else
{
%cb = %name @ "MetricsCallback";
if( !isFunction( %cb ) )
error( "metrics - undefined callback: " @ %cb );
else
{
%cb = %cb @ "()";
if( %i > 0 )
%metricsExpr = %metricsExpr @ " NL ";
%metricsExpr = %metricsExpr @ %cb;
}
}
}
if( %metricsExpr !$= "" )
%metricsExpr = %metricsExpr @ " @ \" \"";
}
if( %metricsExpr !$= "" )
{
Canvas.pushDialog( FrameOverlayGui, 1000 );
TextOverlayControl.setValue( %metricsExpr );
}
else
Canvas.popDialog(FrameOverlayGui);
}
| |
using System;
using IntXLib;
using System.IO;
namespace ViewNet
{
/// <summary>
/// Represents the Diffie-Hellman algorithm.
/// </summary>
public class DiffieHellman : IDisposable
{
#region - Util -
Random _weakRND = new Random ();
#endregion
#region - Fields -
/// <summary>
/// The number of bytes to generate.
/// </summary>
int bytes = 128;
/// <summary>
/// The shared prime.
/// </summary>
IntX p;
/// <summary>
/// The shared base.
/// </summary>
IntX g;
/// <summary>
/// The secret number
/// </summary>
uint a;
/// <summary>
/// The final key.
/// </summary>
public IntX S;
#endregion
#region - Properties -
/// <summary>
/// Gets the final key to use for encryption.
/// </summary>
public byte[] Key {
get;
set;
}
#endregion
#region - Ctor -
public DiffieHellman ()
{
}
public DiffieHellman (int bytesize)
{
bytes = bytesize;
}
~DiffieHellman ()
{
Dispose ();
}
#endregion
#region - Implementation Methods -
#region Flow
IntX GeneratePrime ()
{
int limit = bytes;
if (limit < 4)
limit = 4;
var raw = new byte[limit];
_weakRND.NextBytes (raw);
var newInt = new IntX (DigitConverter.FromBytes (raw), false);
return newInt;
}
/// <summary>
/// Generates a request packet.
/// </summary>
/// <returns></returns>
public byte[] GenerateRequest ()
{
// Generate the parameters.
var raw = new byte[bytes * 8];
_weakRND.NextBytes (raw);
a = (uint)_weakRND.Next ((bytes * 8) / 4 * 3, bytes * 8);
p = GeneratePrime ();
g = new IntX (DigitConverter.FromBytes (raw), false);
IntX A = IntX.Pow (g, a, MultiplyMode.AutoFht);
A = IntX.Modulo (A, p, DivideMode.AutoNewton);
var memStream = new MemoryStream ();
uint[] temp;
bool ignoreThis;
// Get Raw IntX Data
g.GetInternalState (out temp, out ignoreThis);
var gData = DigitConverter.ToBytes (temp);
p.GetInternalState (out temp, out ignoreThis);
var pData = DigitConverter.ToBytes (temp);
A.GetInternalState (out temp, out ignoreThis);
var AData = DigitConverter.ToBytes (temp);
// Write Length to Stream
memStream.Write (BitConverter.GetBytes (gData.Length), 0, 4);
memStream.Write (BitConverter.GetBytes (pData.Length), 0, 4);
memStream.Write (BitConverter.GetBytes (AData.Length), 0, 4);
// Write Data to Stream
memStream.Write (gData, 0, gData.Length);
memStream.Write (pData, 0, pData.Length);
memStream.Write (AData, 0, AData.Length);
var finalDataSend = memStream.ToArray ();
memStream.Dispose ();
return finalDataSend;
}
void GetKeyData ()
{
uint[] digits;
bool fakebool;
S.GetInternalState (out digits, out fakebool);
Key = DigitConverter.ToBytes (digits);
}
/// <summary>
/// Generate a response packet.
/// </summary>
/// <param name="request">The string representation of the request.</param>
/// <returns></returns>
public byte[] GenerateResponse (byte[] request)
{
var instream = new MemoryStream (request);
var temp = new byte[4];
instream.Read (temp, 0, temp.Length);
int gLength = BitConverter.ToInt32 (temp, 0);
instream.Read (temp, 0, temp.Length);
int pLength = BitConverter.ToInt32 (temp, 0);
instream.Read (temp, 0, temp.Length);
int ALength = BitConverter.ToInt32 (temp, 0);
temp = new byte[gLength];
instream.Read (temp, 0, gLength);
g = new IntX (DigitConverter.FromBytes (temp), false);
temp = new byte[pLength];
instream.Read (temp, 0, pLength);
p = new IntX (DigitConverter.FromBytes (temp), false);
temp = new byte[ALength];
instream.Read (temp, 0, ALength);
var A = new IntX (DigitConverter.FromBytes (temp), false);
// Generate the parameters.
a = (uint)_weakRND.Next (bytes);
IntX B = IntX.Pow (g, a);
B = IntX.Modulo (B, p, DivideMode.AutoNewton);
var memStream = new MemoryStream ();
bool ignoreThis;
// Get Raw IntX Data
uint[] tempDigits;
B.GetInternalState (out tempDigits, out ignoreThis);
var BData = DigitConverter.ToBytes (tempDigits);
memStream.Write (BData, 0, BData.Length);
var finalDataSend = memStream.ToArray ();
memStream.Dispose ();
// Got the key!!! HOORAY!
S = IntX.Pow (A, a);
S = IntX.Modulo (S, p, DivideMode.AutoNewton);
GetKeyData ();
return finalDataSend;
}
/// <summary>
/// Generates the key after a response is received.
/// </summary>
/// <param name="response">The string representation of the response.</param>
public void HandleResponse (byte[] response)
{
var B = new IntX (DigitConverter.FromBytes (response), false);
S = IntX.Pow (B, a);
S = IntX.Modulo (S, p, DivideMode.AutoNewton);
GetKeyData ();
Dispose ();
}
#endregion
#endregion
#region IDisposable Members
/// <summary>
/// Ends the calculation. The key will still be available.
/// </summary>
public void Dispose ()
{
p = null;
g = null;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class DoNotRaiseExceptionsInUnexpectedLocationsTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer();
}
#region Property and Event Tests
[Fact]
public void CSharpPropertyNoDiagnostics()
{
var code = @"
using System;
public class C
{
public int PropWithNoException { get { return 10; } set { } }
public int PropWithSetterException { get { return 10; } set { throw new NotSupportedException(); } }
public int PropWithAllowedException { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public int this[int x] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
}
class NonPublic
{
public int PropWithException { get { throw new Exception(); } set { throw new NotSupportedException(); } }
}
";
VerifyCSharp(code);
}
[Fact]
public void BasicPropertyNoDiagnostics()
{
var code = @"
Imports System
Public Class C
Public Property PropWithNoException As Integer
Get
Return 10
End Get
Set
End Set
End Property
Public Property PropWithSetterException As Integer
Get
Return 10
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Public Property PropWithAllowedException As Integer
Get
Throw New NotSupportedException()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Default Public Property Item(x As Integer) As Integer
Get
Throw New NotSupportedException()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
End Class
Class NonPublic
Public Property PropWithInvalidException As Integer
Get
Throw New Exception() 'Doesn't fire because it's not visible outside assembly
End Get
Set
End Set
End Property
End Class
";
VerifyBasic(code);
}
[Fact]
public void CSharpPropertyWithInvalidExceptions()
{
var code = @"
using System;
public class C
{
public int Prop1 { get { throw new Exception(); } set { throw new NotSupportedException(); } }
public int this[int x] { get { throw new Exception(); } set { throw new NotSupportedException(); } }
public event EventHandler Event1 { add { throw new Exception(); } remove { throw new Exception(); } }
}
";
VerifyCSharp(code,
GetCSharpPropertyResultAt(6, 30, "get_Prop1", "Exception"),
GetCSharpPropertyResultAt(7, 36, "get_Item", "Exception"),
GetCSharpAllowedExceptionsResultAt(8, 46, "add_Event1", "Exception"),
GetCSharpAllowedExceptionsResultAt(8, 80, "remove_Event1", "Exception"));
}
[Fact]
public void BasicPropertyWithInvalidExceptions()
{
var code = @"
Imports System
Public Class C
Public Property Prop1 As Integer
Get
Throw New Exception()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Default Public Property Item(x As Integer) As Integer
Get
Throw New Exception()
End Get
Set
Throw New NotSupportedException()
End Set
End Property
Public Custom Event Event1 As EventHandler
AddHandler(ByVal value As EventHandler)
Throw New Exception()
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Throw New Exception()
End RemoveHandler
' RaiseEvent accessors are considered private and we won't flag this exception.
RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
Throw New Exception()
End RaiseEvent
End Event
End Class
";
VerifyBasic(code,
GetBasicPropertyResultAt(7, 12, "get_Prop1", "Exception"),
GetBasicPropertyResultAt(15, 12, "get_Item", "Exception"),
GetBasicAllowedExceptionsResultAt(24, 13, "add_Event1", "Exception"),
GetBasicAllowedExceptionsResultAt(28, 13, "remove_Event1", "Exception"));
}
#endregion
#region Equals, GetHashCode, Dispose and ToString Tests
[Fact]
public void CSharpEqualsAndGetHashCodeWithExceptions()
{
var code = @"
using System;
public class C
{
public override bool Equals(object obj)
{
throw new Exception();
}
public override int GetHashCode()
{
throw new ArgumentException("""");
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"),
GetCSharpNoExceptionsResultAt(12, 9, "GetHashCode", "ArgumentException"));
}
[Fact]
public void BasicEqualsAndGetHashCodeWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Overrides Function Equals(obj As Object) As Boolean
Throw New Exception()
End Function
Public Overrides Function GetHashCode() As Integer
Throw New ArgumentException("""")
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "Equals", "Exception"),
GetBasicNoExceptionsResultAt(9, 9, "GetHashCode", "ArgumentException"));
}
[Fact]
public void CSharpEqualsAndGetHashCodeNoDiagnostics()
{
var code = @"
using System;
public class C
{
public new bool Equals(object obj)
{
throw new Exception();
}
public new int GetHashCode()
{
throw new ArgumentException("""");
}
}
";
VerifyCSharp(code);
}
[Fact]
public void BasicEqualsAndGetHashCodeNoDiagnostics()
{
var code = @"
Imports System
Public Class C
Public Shadows Function Equals(obj As Object) As Boolean
Throw New Exception()
End Function
Public Shadows Function GetHashCode() As Integer
Throw New ArgumentException("""")
End Function
End Class
";
VerifyBasic(code);
}
[Fact]
public void CSharpIEquatableEqualsWithExceptions()
{
var code = @"
using System;
public class C : IEquatable<C>
{
public bool Equals(C obj)
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"));
}
[Fact]
public void BasicIEquatableEqualsExceptions()
{
var code = @"
Imports System
Public Class C
Implements IEquatable(Of C)
Public Function Equals(obj As C) As Boolean Implements IEquatable(Of C).Equals
Throw New Exception()
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"));
}
[Fact]
public void CSharpIHashCodeProviderGetHashCode()
{
var code = @"
using System;
using System.Collections;
public class C : IHashCodeProvider
{
public int GetHashCode(object obj)
{
throw new Exception();
}
}
public class D : IHashCodeProvider
{
public int GetHashCode(object obj)
{
throw new ArgumentException(""obj""); // this is fine.
}
}
";
VerifyCSharp(code,
GetCSharpAllowedExceptionsResultAt(8, 9, "GetHashCode", "Exception"));
}
[Fact]
public void BasicIHashCodeProviderGetHashCode()
{
var code = @"
Imports System
Imports System.Collections
Public Class C
Implements IHashCodeProvider
Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode
Throw New Exception()
End Function
End Class
Public Class D
Implements IHashCodeProvider
Public Function GetHashCode(obj As Object) As Integer Implements IHashCodeProvider.GetHashCode
Throw New ArgumentException() ' This is fine.
End Function
End Class
";
VerifyBasic(code,
GetBasicAllowedExceptionsResultAt(7, 9, "GetHashCode", "Exception"));
}
[Fact]
public void CSharpIEqualityComparer()
{
var code = @"
using System;
using System.Collections.Generic;
public class C : IEqualityComparer<C>
{
public bool Equals(C obj1, C obj2)
{
throw new Exception();
}
public int GetHashCode(C obj)
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Equals", "Exception"),
GetCSharpAllowedExceptionsResultAt(12, 9, "GetHashCode", "Exception"));
}
[Fact]
public void BasicIEqualityComparer()
{
var code = @"
Imports System
Imports System.Collections.Generic
Public Class C
Implements IEqualityComparer(Of C)
Public Function Equals(obj1 As C, obj2 As C) As Boolean Implements IEqualityComparer(Of C).Equals
Throw New Exception()
End Function
Public Function GetHashCode(obj As C) As Integer Implements IEqualityComparer(Of C).GetHashCode
Throw New Exception()
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(7, 9, "Equals", "Exception"),
GetBasicAllowedExceptionsResultAt(10, 9, "GetHashCode", "Exception"));
}
[Fact]
public void CSharpIDisposable()
{
var code = @"
using System;
public class C : IDisposable
{
public void Dispose()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Dispose", "Exception"));
}
[Fact]
public void BasicIDisposable()
{
var code = @"
Imports System
Public Class C
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New Exception()
End Sub
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(7, 9, "Dispose", "Exception"));
}
[Fact]
public void CSharpToStringWithExceptions()
{
var code = @"
using System;
public class C
{
public override string ToString()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "ToString", "Exception"));
}
[Fact]
public void BasicToStringWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Overrides Function ToString() As String
Throw New Exception()
End Function
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "ToString", "Exception"));
}
#endregion
#region Constructor and Destructor tests
[Fact]
public void CSharpStaticConstructorWithExceptions()
{
var code = @"
using System;
class NonPublic
{
static NonPublic()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, ".cctor", "Exception"));
}
[Fact]
public void BasicStaticConstructorWithExceptions()
{
var code = @"
Imports System
Class NonPublic
Shared Sub New()
Throw New Exception()
End Sub
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, ".cctor", "Exception"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")]
public void CSharpFinalizerWithExceptions()
{
var code = @"
using System;
class NonPublic
{
~NonPublic()
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "Finalize", "Exception"));
}
[Fact]
public void BasicFinalizerWithExceptions()
{
var code = @"
Imports System
Class NonPublic
Protected Overrides Sub Finalize()
Throw New Exception()
End Sub
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "Finalize", "Exception"));
}
#endregion
#region Operator tests
[Fact]
public void CSharpEqualityOperatorWithExceptions()
{
var code = @"
using System;
public class C
{
public static C operator ==(C c1, C c2)
{
throw new Exception();
}
public static C operator !=(C c1, C c2)
{
throw new Exception();
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "op_Equality", "Exception"),
GetCSharpNoExceptionsResultAt(12, 9, "op_Inequality", "Exception"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")]
public void BasicEqualityOperatorWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Shared Operator =(c1 As C, c2 As C) As C
Throw New Exception()
End Operator
Public Shared Operator <>(c1 As C, c2 As C) As C
Throw New Exception()
End Operator
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "op_Equality", "Exception"),
GetBasicNoExceptionsResultAt(9, 9, "op_Inequality", "Exception"));
}
[Fact]
public void CSharpImplicitOperatorWithExceptions()
{
var code = @"
using System;
public class C
{
public static implicit operator int(C c1)
{
throw new Exception();
}
public static explicit operator double(C c1)
{
throw new Exception(); // This is fine.
}
}
";
VerifyCSharp(code,
GetCSharpNoExceptionsResultAt(8, 9, "op_Implicit", "Exception"));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/7428")]
public void BasicImplicitOperatorWithExceptions()
{
var code = @"
Imports System
Public Class C
Public Shared Widening Operator CType(x As Integer) As C
Throw New Exception()
End Operator
Public Shared Narrowing Operator CType(x As Double) As C
Throw New Exception()
End Operator
End Class
";
VerifyBasic(code,
GetBasicNoExceptionsResultAt(6, 9, "op_Implicit", "Exception"));
}
#endregion
private DiagnosticResult GetCSharpPropertyResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName);
}
private DiagnosticResult GetCSharpAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName);
}
private DiagnosticResult GetCSharpNoExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetCSharpResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName);
}
private DiagnosticResult GetBasicPropertyResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.PropertyGetterRule, methodName, exceptionName);
}
private DiagnosticResult GetBasicAllowedExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.HasAllowedExceptionsRule, methodName, exceptionName);
}
private DiagnosticResult GetBasicNoExceptionsResultAt(int line, int column, string methodName, string exceptionName)
{
return GetBasicResultAt(line, column, DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.NoAllowedExceptionsRule, methodName, exceptionName);
}
}
}
| |
using NBitcoin;
using NBitcoin.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.BitcoinCore.Rpc;
using WalletWasabi.Blockchain.Analysis.Clustering;
using WalletWasabi.Blockchain.BlockFilters;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
using WalletWasabi.Services;
using WalletWasabi.Stores;
using WalletWasabi.Tests.XunitConfiguration;
using WalletWasabi.Wallets;
using WalletWasabi.WebClients.Wasabi;
using Xunit;
namespace WalletWasabi.Tests.RegressionTests
{
[Collection("RegTest collection")]
public class WalletTests
{
public WalletTests(RegTestFixture regTestFixture)
{
RegTestFixture = regTestFixture;
}
private RegTestFixture RegTestFixture { get; }
private async Task WaitForIndexesToSyncAsync(Backend.Global global, TimeSpan timeout, BitcoinStore bitcoinStore)
{
var bestHash = await global.RpcClient.GetBestBlockHashAsync();
var times = 0;
while (bitcoinStore.SmartHeaderChain.TipHash != bestHash)
{
if (times > timeout.TotalSeconds)
{
throw new TimeoutException($"{nameof(WasabiSynchronizer)} test timed out. Filter was not downloaded.");
}
await Task.Delay(TimeSpan.FromSeconds(1));
times++;
}
}
[Fact]
public async Task FilterDownloaderTestAsync()
{
(_, IRPCClient rpc, _, _, _, BitcoinStore bitcoinStore, _) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
var httpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => new Uri(RegTestFixture.BackendEndPoint));
var synchronizer = new WasabiSynchronizer(rpc.Network, bitcoinStore, httpClientFactory);
try
{
synchronizer.Start(requestInterval: TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), 1000);
var blockCount = await rpc.GetBlockCountAsync() + 1; // Plus one because of the zeroth.
// Test initial synchronization.
var times = 0;
int filterCount;
while ((filterCount = bitcoinStore.SmartHeaderChain.HashCount) < blockCount)
{
if (times > 500) // 30 sec
{
throw new TimeoutException($"{nameof(WasabiSynchronizer)} test timed out. Needed filters: {blockCount}, got only: {filterCount}.");
}
await Task.Delay(100);
times++;
}
Assert.Equal(blockCount, bitcoinStore.SmartHeaderChain.HashCount);
// Test later synchronization.
await RegTestFixture.BackendRegTestNode.GenerateAsync(10);
times = 0;
while ((filterCount = bitcoinStore.SmartHeaderChain.HashCount) < blockCount + 10)
{
if (times > 500) // 30 sec
{
throw new TimeoutException($"{nameof(WasabiSynchronizer)} test timed out. Needed filters: {blockCount + 10}, got only: {filterCount}.");
}
await Task.Delay(100);
times++;
}
// Test correct number of filters is received.
Assert.Equal(blockCount + 10, bitcoinStore.SmartHeaderChain.HashCount);
// Test filter block hashes are correct.
var filterList = new List<FilterModel>();
await bitcoinStore.IndexStore.ForeachFiltersAsync(async x =>
{
filterList.Add(x);
await Task.CompletedTask;
},
new Height(0));
FilterModel[] filters = filterList.ToArray();
for (int i = 0; i < 101; i++)
{
var expectedHash = await rpc.GetBlockHashAsync(i);
var filter = filters[i];
Assert.Equal(i, (int)filter.Header.Height);
Assert.Equal(expectedHash, filter.Header.BlockHash);
Assert.Equal(IndexBuilderService.CreateDummyEmptyFilter(expectedHash).ToString(), filter.Filter.ToString());
}
}
finally
{
if (synchronizer is { })
{
await synchronizer.StopAsync();
}
}
}
[Fact]
public async Task ReorgTestAsync()
{
(string password, IRPCClient rpc, Network network, _, _, BitcoinStore bitcoinStore, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
var keyManager = KeyManager.CreateNew(out _, password);
// Mine some coins, make a few bech32 transactions then make it confirm.
await rpc.GenerateAsync(1);
var key = keyManager.GenerateNewKey(SmartLabel.Empty, KeyState.Clean, isInternal: false);
var tx2 = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(0.1m));
key = keyManager.GenerateNewKey(SmartLabel.Empty, KeyState.Clean, isInternal: false);
var tx3 = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(0.1m));
var tx4 = await rpc.SendToAddressAsync(key.GetP2pkhAddress(network), Money.Coins(0.1m));
var tx5 = await rpc.SendToAddressAsync(key.GetP2shOverP2wpkhAddress(network), Money.Coins(0.1m));
var tx1 = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(0.1m), replaceable: true);
await rpc.GenerateAsync(2); // Generate two, so we can test for two reorg
var node = RegTestFixture.BackendRegTestNode;
var httpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => new Uri(RegTestFixture.BackendEndPoint));
var synchronizer = new WasabiSynchronizer(rpc.Network, bitcoinStore, httpClientFactory);
try
{
synchronizer.Start(requestInterval: TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(5), 1000);
var reorgAwaiter = new EventsAwaiter<FilterModel>(
h => bitcoinStore.IndexStore.Reorged += h,
h => bitcoinStore.IndexStore.Reorged -= h,
2);
// Test initial synchronization.
await WaitForIndexesToSyncAsync(global, TimeSpan.FromSeconds(90), bitcoinStore);
var tip = await rpc.GetBestBlockHashAsync();
Assert.Equal(tip, bitcoinStore.SmartHeaderChain.TipHash);
var tipBlock = await rpc.GetBlockHeaderAsync(tip);
Assert.Equal(tipBlock.HashPrevBlock, bitcoinStore.SmartHeaderChain.GetChain().Select(x => x.header.BlockHash).ToArray()[bitcoinStore.SmartHeaderChain.HashCount - 2]);
// Test synchronization after fork.
await rpc.InvalidateBlockAsync(tip); // Reorg 1
tip = await rpc.GetBestBlockHashAsync();
await rpc.InvalidateBlockAsync(tip); // Reorg 2
var tx1bumpRes = await rpc.BumpFeeAsync(tx1); // RBF it
await rpc.GenerateAsync(5);
await WaitForIndexesToSyncAsync(global, TimeSpan.FromSeconds(90), bitcoinStore);
var hashes = bitcoinStore.SmartHeaderChain.GetChain().Select(x => x.header.BlockHash).ToArray();
Assert.DoesNotContain(tip, hashes);
Assert.DoesNotContain(tipBlock.HashPrevBlock, hashes);
tip = await rpc.GetBestBlockHashAsync();
Assert.Equal(tip, bitcoinStore.SmartHeaderChain.TipHash);
var filterList = new List<FilterModel>();
await bitcoinStore.IndexStore.ForeachFiltersAsync(async x =>
{
filterList.Add(x);
await Task.CompletedTask;
},
new Height(0));
var filterTip = filterList.Last();
Assert.Equal(tip, filterTip.Header.BlockHash);
// Test filter block hashes are correct after fork.
var blockCountIncludingGenesis = await rpc.GetBlockCountAsync() + 1;
filterList.Clear();
await bitcoinStore.IndexStore.ForeachFiltersAsync(async x =>
{
filterList.Add(x);
await Task.CompletedTask;
},
new Height(0));
FilterModel[] filters = filterList.ToArray();
for (int i = 0; i < blockCountIncludingGenesis; i++)
{
var expectedHash = await rpc.GetBlockHashAsync(i);
var filter = filters[i];
Assert.Equal(i, (int)filter.Header.Height);
Assert.Equal(expectedHash, filter.Header.BlockHash);
if (i < 101) // Later other tests may fill the filter.
{
Assert.Equal(IndexBuilderService.CreateDummyEmptyFilter(expectedHash).ToString(), filter.Filter.ToString());
}
}
// Test the serialization, too.
tip = await rpc.GetBestBlockHashAsync();
var blockHash = tip;
for (var i = 0; i < hashes.Length; i++)
{
var block = await rpc.GetBlockHeaderAsync(blockHash);
Assert.Equal(blockHash, hashes[hashes.Length - i - 1]);
blockHash = block.HashPrevBlock;
}
// Assert reorg happened exactly as many times as we reorged.
await reorgAwaiter.WaitAsync(TimeSpan.FromSeconds(10));
}
finally
{
if (synchronizer is { })
{
await synchronizer.StopAsync();
}
}
}
[Fact]
public async Task WalletTestsAsync()
{
(string password, IRPCClient rpc, Network network, _, ServiceConfiguration serviceConfiguration, BitcoinStore bitcoinStore, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);
// Create the services.
// 1. Create connection service.
var nodes = new NodesGroup(global.Config.Network, requirements: Constants.NodeRequirements);
nodes.ConnectedNodes.Add(await RegTestFixture.BackendRegTestNode.CreateNewP2pNodeAsync());
Node node = await RegTestFixture.BackendRegTestNode.CreateNewP2pNodeAsync();
node.Behaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior());
// 2. Create wasabi synchronizer service.
var httpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => new Uri(RegTestFixture.BackendEndPoint));
var synchronizer = new WasabiSynchronizer(rpc.Network, bitcoinStore, httpClientFactory);
// 3. Create key manager service.
var keyManager = KeyManager.CreateNew(out _, password);
// 4. Create wallet service.
var workDir = Helpers.Common.GetWorkDir();
CachedBlockProvider blockProvider = new CachedBlockProvider(
new P2pBlockProvider(nodes, null, synchronizer, serviceConfiguration, network),
bitcoinStore.BlockRepository);
using var wallet = Wallet.CreateAndRegisterServices(network, bitcoinStore, keyManager, synchronizer, nodes, workDir, serviceConfiguration, synchronizer, blockProvider);
wallet.NewFilterProcessed += Common.Wallet_NewFilterProcessed;
// Get some money, make it confirm.
var key = keyManager.GetNextReceiveKey("foo label", out _);
var txId = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(0.1m));
await rpc.GenerateAsync(1);
try
{
Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
nodes.Connect(); // Start connection service.
node.VersionHandshake(); // Start mempool service.
synchronizer.Start(requestInterval: TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(5), 1000); // Start wasabi synchronizer service.
// Wait until the filter our previous transaction is present.
var blockCount = await rpc.GetBlockCountAsync();
await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), blockCount);
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
await wallet.StartAsync(cts.Token); // Initialize wallet service.
}
Assert.Equal(1, await blockProvider.BlockRepository.CountAsync(CancellationToken.None));
Assert.Single(wallet.Coins);
var firstCoin = wallet.Coins.Single();
Assert.Equal(Money.Coins(0.1m), firstCoin.Amount);
Assert.Equal(new Height((int)bitcoinStore.SmartHeaderChain.TipHeight), firstCoin.Height);
Assert.InRange(firstCoin.Index, 0U, 1U);
Assert.True(firstCoin.IsAvailable());
Assert.Equal("foo label", firstCoin.HdPubKey.Label);
Assert.Equal(key.P2wpkhScript, firstCoin.ScriptPubKey);
Assert.Null(firstCoin.SpenderTransaction);
Assert.Equal(txId, firstCoin.TransactionId);
Assert.Single(keyManager.GetKeys(KeyState.Used, false));
Assert.Equal("foo label", keyManager.GetKeys(KeyState.Used, false).Single().Label);
// Get some money, make it confirm.
var key2 = keyManager.GetNextReceiveKey("bar label", out _);
var txId2 = await rpc.SendToAddressAsync(key2.GetP2wpkhAddress(network), Money.Coins(0.01m));
Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
await rpc.GenerateAsync(1);
var txId3 = await rpc.SendToAddressAsync(key2.GetP2wpkhAddress(network), Money.Coins(0.02m));
await rpc.GenerateAsync(1);
await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), 2);
Assert.Equal(3, await blockProvider.BlockRepository.CountAsync(CancellationToken.None));
Assert.Equal(3, wallet.Coins.Count());
firstCoin = wallet.Coins.OrderBy(x => x.Height).First();
var secondCoin = wallet.Coins.OrderBy(x => x.Height).Take(2).Last();
var thirdCoin = wallet.Coins.OrderBy(x => x.Height).Last();
Assert.Equal(Money.Coins(0.01m), secondCoin.Amount);
Assert.Equal(Money.Coins(0.02m), thirdCoin.Amount);
Assert.Equal(new Height(bitcoinStore.SmartHeaderChain.TipHeight).Value - 2, firstCoin.Height.Value);
Assert.Equal(new Height(bitcoinStore.SmartHeaderChain.TipHeight).Value - 1, secondCoin.Height.Value);
Assert.Equal(new Height(bitcoinStore.SmartHeaderChain.TipHeight), thirdCoin.Height);
Assert.True(thirdCoin.IsAvailable());
Assert.Equal("foo label", firstCoin.HdPubKey.Label);
Assert.Equal("bar label", secondCoin.HdPubKey.Label);
Assert.Equal("bar label", thirdCoin.HdPubKey.Label);
Assert.Equal(key.P2wpkhScript, firstCoin.ScriptPubKey);
Assert.Equal(key2.P2wpkhScript, secondCoin.ScriptPubKey);
Assert.Equal(key2.P2wpkhScript, thirdCoin.ScriptPubKey);
Assert.Null(thirdCoin.SpenderTransaction);
Assert.Equal(txId, firstCoin.TransactionId);
Assert.Equal(txId2, secondCoin.TransactionId);
Assert.Equal(txId3, thirdCoin.TransactionId);
Assert.Equal(2, keyManager.GetKeys(KeyState.Used, false).Count());
Assert.Empty(keyManager.GetKeys(KeyState.Used, true));
Assert.Equal(2, keyManager.GetKeys(KeyState.Used).Count());
Assert.Empty(keyManager.GetKeys(KeyState.Locked, false));
Assert.Equal(14, keyManager.GetKeys(KeyState.Locked, true).Count());
Assert.Equal(14, keyManager.GetKeys(KeyState.Locked).Count());
Assert.Equal(21, keyManager.GetKeys(KeyState.Clean, true).Count());
Assert.Equal(21, keyManager.GetKeys(KeyState.Clean, false).Count());
Assert.Equal(42, keyManager.GetKeys(KeyState.Clean).Count());
Assert.Equal(58, keyManager.GetKeys().Count());
Assert.Single(keyManager.GetKeys(x => x.Label == "foo label" && x.KeyState == KeyState.Used && !x.IsInternal));
Assert.Single(keyManager.GetKeys(x => x.Label == "bar label" && x.KeyState == KeyState.Used && !x.IsInternal));
// REORG TESTS
var txId4 = await rpc.SendToAddressAsync(key2.GetP2wpkhAddress(network), Money.Coins(0.03m), replaceable: true);
Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
await rpc.GenerateAsync(2);
await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), 2);
Assert.NotEmpty(wallet.Coins.Where(x => x.TransactionId == txId4));
var tip = await rpc.GetBestBlockHashAsync();
await rpc.InvalidateBlockAsync(tip); // Reorg 1
tip = await rpc.GetBestBlockHashAsync();
await rpc.InvalidateBlockAsync(tip); // Reorg 2
var tx4bumpRes = await rpc.BumpFeeAsync(txId4); // RBF it
Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
await rpc.GenerateAsync(3);
await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), 3);
Assert.Equal(4, await blockProvider.BlockRepository.CountAsync(CancellationToken.None));
Assert.Equal(4, wallet.Coins.Count());
Assert.Empty(wallet.Coins.Where(x => x.TransactionId == txId4));
Assert.NotEmpty(wallet.Coins.Where(x => x.TransactionId == tx4bumpRes.TransactionId));
var rbfCoin = wallet.Coins.Single(x => x.TransactionId == tx4bumpRes.TransactionId);
Assert.Equal(Money.Coins(0.03m), rbfCoin.Amount);
Assert.Equal(new Height(bitcoinStore.SmartHeaderChain.TipHeight).Value - 2, rbfCoin.Height.Value);
Assert.True(rbfCoin.IsAvailable());
Assert.Equal("bar label", rbfCoin.HdPubKey.Label);
Assert.Equal(key2.P2wpkhScript, rbfCoin.ScriptPubKey);
Assert.Null(rbfCoin.SpenderTransaction);
Assert.Equal(tx4bumpRes.TransactionId, rbfCoin.TransactionId);
Assert.Equal(2, keyManager.GetKeys(KeyState.Used, false).Count());
Assert.Empty(keyManager.GetKeys(KeyState.Used, true));
Assert.Equal(2, keyManager.GetKeys(KeyState.Used).Count());
Assert.Empty(keyManager.GetKeys(KeyState.Locked, false));
Assert.Equal(14, keyManager.GetKeys(KeyState.Locked, true).Count());
Assert.Equal(14, keyManager.GetKeys(KeyState.Locked).Count());
Assert.Equal(21, keyManager.GetKeys(KeyState.Clean, true).Count());
Assert.Equal(21, keyManager.GetKeys(KeyState.Clean, false).Count());
Assert.Equal(42, keyManager.GetKeys(KeyState.Clean).Count());
Assert.Equal(58, keyManager.GetKeys().Count());
Assert.Single(keyManager.GetKeys(KeyState.Used, false).Where(x => x.Label == "foo label"));
Assert.Single(keyManager.GetKeys(KeyState.Used, false).Where(x => x.Label == "bar label"));
// TEST MEMPOOL
var txId5 = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(0.1m));
await Task.Delay(1000); // Wait tx to arrive and get processed.
Assert.NotEmpty(wallet.Coins.Where(x => x.TransactionId == txId5));
var mempoolCoin = wallet.Coins.Single(x => x.TransactionId == txId5);
Assert.Equal(Height.Mempool, mempoolCoin.Height);
Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
await rpc.GenerateAsync(1);
await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), 1);
var res = await rpc.GetTxOutAsync(mempoolCoin.TransactionId, (int)mempoolCoin.Index, true);
Assert.Equal(new Height(bitcoinStore.SmartHeaderChain.TipHeight), mempoolCoin.Height);
}
finally
{
wallet.NewFilterProcessed -= Common.Wallet_NewFilterProcessed;
await wallet.StopAsync(CancellationToken.None);
// Dispose wasabi synchronizer service.
if (synchronizer is { })
{
await synchronizer.StopAsync();
}
// Dispose connection service.
nodes?.Dispose();
// Dispose mempool serving node.
node?.Disconnect();
}
}
}
}
| |
//
// Replication.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Web;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Linq;
using System.Threading;
using Newtonsoft.Json.Linq;
using Couchbase.Lite.Util;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Support;
using Couchbase.Lite.Internal;
using Sharpen;
namespace Couchbase.Lite
{
#region Enums
public enum ReplicationStatus {
Stopped,
Offline,
Idle,
Active
}
#endregion
public abstract partial class Replication
{
#region Constants
internal static readonly String ReplicatorDatabaseName = "_replicator";
#endregion
#region Constructors
protected Replication(Database db, Uri remote, bool continuous, TaskFactory workExecutor)
: this(db, remote, continuous, null, workExecutor) { }
/// <summary>Private Constructor</summary>
protected Replication(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory, TaskFactory workExecutor, CancellationTokenSource tokenSource = null)
{
LocalDatabase = db;
Continuous = continuous;
WorkExecutor = workExecutor;
CancellationTokenSource = tokenSource ?? new CancellationTokenSource();
RemoteUrl = remote;
Status = ReplicationStatus.Stopped;
online = true;
RequestHeaders = new Dictionary<String, Object>();
if (RemoteUrl.GetQuery() != null && !RemoteUrl.GetQuery().IsEmpty())
{
var uri = new Uri(remote.ToString());
var personaAssertion = URIUtils.GetQueryParameter(uri, PersonaAuthorizer.QueryParameter);
if (personaAssertion != null && !personaAssertion.IsEmpty())
{
var email = PersonaAuthorizer.RegisterAssertion(personaAssertion);
var authorizer = new PersonaAuthorizer(email);
Authorizer = authorizer;
}
var facebookAccessToken = URIUtils.GetQueryParameter(uri, FacebookAuthorizer.QueryParameter);
if (facebookAccessToken != null && !facebookAccessToken.IsEmpty())
{
var email = URIUtils.GetQueryParameter(uri, FacebookAuthorizer.QueryParameterEmail);
var authorizer = new FacebookAuthorizer(email);
Uri remoteWithQueryRemoved = null;
try
{
remoteWithQueryRemoved = new UriBuilder(remote.Scheme, remote.GetHost(), remote.Port, remote.AbsolutePath).Uri;
}
catch (UriFormatException e)
{
throw new ArgumentException("Invalid URI format.", "remote", e);
}
FacebookAuthorizer.RegisterAccessToken(facebookAccessToken, email, remoteWithQueryRemoved.ToString());
Authorizer = authorizer;
}
// we need to remove the query from the URL, since it will cause problems when
// communicating with sync gw / couchdb
try
{
RemoteUrl = new UriBuilder(remote.Scheme, remote.GetHost(), remote.Port, remote.AbsolutePath).Uri;
}
catch (UriFormatException e)
{
throw new ArgumentException("Invalid URI format.", "remote", e);
}
}
Batcher = new Batcher<RevisionInternal>(workExecutor, InboxCapacity, ProcessorDelay,
inbox =>
{
Log.V (Database.Tag, "*** " + this + ": BEGIN processInbox (" + inbox.Count + " sequences)");
ProcessInbox (new RevisionList (inbox));
Log.V (Database.Tag, "*** " + this.ToString () + ": END processInbox (lastSequence=" + LastSequence);
UpdateActive();
}, CancellationTokenSource);
this.clientFactory = clientFactory ?? CouchbaseLiteHttpClientFactory.Instance;
}
#endregion
#region Constants
const int ProcessorDelay = 500; //Milliseconds
const int InboxCapacity = 100;
const int RetryDelay = 60; // Seconds
const int SaveLastSequenceDelay = 2; //Seconds
readonly string Tag = "Replication";
#endregion
#region Non-public Members
private static Int32 lastSessionID = 0;
readonly protected TaskFactory WorkExecutor; // FIXME: Remove this.
readonly protected IHttpClientFactory clientFactory;
protected internal String sessionID;
protected internal Boolean lastSequenceChanged;
private String lastSequence;
protected internal String LastSequence
{
get { return lastSequence; }
set
{
if (value != null && !value.Equals(lastSequence))
{
Log.V(Tag, this + ": Setting lastSequence to " + value + " from( " + lastSequence + ")");
lastSequence = value;
if (!lastSequenceChanged)
{
lastSequenceChanged = true;
Task.Delay(SaveLastSequenceDelay)
.ContinueWith(task =>
{
SaveLastSequence();
});
}
}
}
}
protected internal Boolean savingCheckpoint;
protected internal Boolean overdueForSave;
protected internal IDictionary<String, Object> remoteCheckpoint;
protected internal Boolean online;
protected internal Boolean continuous;
protected internal Int32 completedChangesCount;
protected internal Int32 changesCount;
protected internal Int32 asyncTaskCount;
protected internal Boolean active;
internal Authorizer Authorizer { get; set; }
internal Batcher<RevisionInternal> Batcher { get; set; }
private CancellationTokenSource CancellationTokenSource { get; set; }
private CancellationTokenSource RetryIfReadyTokenSource { get; set; }
private Task RetryIfReadyTask { get; set; }
protected internal IDictionary<String, Object> RequestHeaders { get; set; }
private Int32 revisionsFailed;
readonly object asyncTaskLocker = new object ();
void NotifyChangeListeners ()
{
var evt = Changed;
if (evt == null) return;
var args = new ReplicationChangeEventArgs(this);
evt(this, args);
}
//TODO: Do we need this method? It's not in the API Spec.
internal bool GoOffline()
{
if (!online)
{
return false;
}
Log.D(Database.Tag, this + ": Going offline");
online = false;
StopRemoteRequests();
UpdateProgress();
NotifyChangeListeners();
return true;
}
//TODO: Do we need this method? It's not in the API Spec.
internal bool GoOnline()
{
if (online)
{
return false;
}
Log.D(Database.Tag, this + ": Going online");
online = true;
if (IsRunning)
{
lastSequence = null;
LastError = null;
}
CheckSession();
NotifyChangeListeners();
return true;
}
internal void StopRemoteRequests()
{
// TODO:
}
internal void UpdateProgress()
{
if (!IsRunning)
{
Status = ReplicationStatus.Stopped;
}
else
{
if (!online)
{
Status = ReplicationStatus.Offline;
}
else
{
if (active)
{
Status = ReplicationStatus.Active;
}
else
{
Status = ReplicationStatus.Idle;
}
}
}
}
internal void DatabaseClosing()
{
SaveLastSequence();
Stop();
ClearDbRef();
}
internal void ClearDbRef()
{
if (savingCheckpoint && LastSequence != null)
{
LocalDatabase.SetLastSequence(LastSequence, RemoteCheckpointDocID(), !IsPull);
LocalDatabase = null;
}
}
internal void AddToInbox(RevisionInternal rev)
{
Batcher.QueueObject(rev);
UpdateActive();
}
internal void CheckSession()
{
if (Authorizer != null && Authorizer.UsesCookieBasedLogin)
{
CheckSessionAtPath("/_session");
}
else
{
FetchRemoteCheckpointDoc();
}
}
internal void CheckSessionAtPath(string sessionPath)
{
Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": checkSessionAtPath() calling asyncTaskStarted()");
AsyncTaskStarted();
SendAsyncRequest(HttpMethod.Get, sessionPath, null, (result, e) => {
try
{
if (e != null)
{
if (e is HttpException && ((HttpException)e).GetHttpCode() == 404
&& sessionPath.Equals("/_session", StringComparison.InvariantCultureIgnoreCase)) {
CheckSessionAtPath ("_session");
return;
}
Log.E(Tag, this + ": Session check failed", e);
LastError = e;
}
else
{
var response = (IDictionary<String, Object>)result;
var userCtx = (IDictionary<String, Object>)response.Get ("userCtx");
var username = (string)userCtx.Get ("name");
if (!string.IsNullOrEmpty (username)) {
Log.D (Tag, string.Format ("{0} Active session, logged in as {1}", this, username));
FetchRemoteCheckpointDoc ();
} else {
Log.D (Tag, string.Format ("{0} No active session, going to login", this));
Login ();
}
}
}
finally
{
Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": checkSessionAtPath() calling asyncTaskFinished()");
AsyncTaskFinished (1);
}
});
}
protected internal virtual void Login()
{
var loginParameters = Authorizer.LoginParametersForSite(RemoteUrl);
if (loginParameters == null)
{
Log.D(Tag, String.Format("{0}: {1} has no login parameters, so skipping login", this, Authorizer));
FetchRemoteCheckpointDoc();
return;
}
var loginPath = Authorizer.LoginPathForSite(RemoteUrl);
Log.D(Tag, string.Format("{0}: Doing login with {1} at {2}", this, Authorizer.GetType(), loginPath));
Log.D(Tag, string.Format("{0} | {1} : login() calling asyncTaskStarted()", this, Sharpen.Thread.CurrentThread()));
AsyncTaskStarted();
SendAsyncRequest(HttpMethod.Post, loginPath, loginParameters, (result, e) => {
try
{
if (e != null)
{
Log.D (Tag, string.Format ("{0}: Login failed for path: {1}", this, loginPath));
LastError = e;
}
else
{
Log.D (Tag, string.Format ("{0}: Successfully logged in!", this));
FetchRemoteCheckpointDoc ();
}
}
finally
{
Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": login() calling asyncTaskFinished()");
AsyncTaskFinished (1);
}
});
}
internal void FetchRemoteCheckpointDoc()
{
lastSequenceChanged = false;
var localLastSequence = LocalDatabase.LastSequenceWithRemoteURL(RemoteUrl, !IsPull);
Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": fetchRemoteCheckpointDoc() calling asyncTaskStarted()");
AsyncTaskStarted();
SendAsyncRequest(HttpMethod.Get, "/_local/" + RemoteCheckpointDocID(), null, (response, e) => {
try
{
if (e != null && !Is404 (e)) {
Log.D (Tag, this + " error getting remote checkpoint: " + e);
LastError = e;
} else {
if (e != null && Is404 (e)) {
Log.D (Tag, this + " 404 error getting remote checkpoint " + RemoteCheckpointDocID () + ", calling maybeCreateRemoteDB");
MaybeCreateRemoteDB ();
}
var responseData = (JObject)response;
var result = responseData.ToObject<IDictionary<string, object>>();
remoteCheckpoint = result;
var remoteLastSequence = String.Empty;
if (result != null) {
remoteLastSequence = (string)result.Get ("lastSequence");
}
if (remoteLastSequence != null && remoteLastSequence.Equals (localLastSequence)) {
LastSequence = localLastSequence;
Log.V (Tag, this + ": Replicating from lastSequence=" + LastSequence);
} else {
Log.V (Tag, this + ": lastSequence mismatch: I had " + localLastSequence + ", remote had " + remoteLastSequence);
}
BeginReplicating ();
}
}
catch (Exception ex)
{
Log.E(Tag, "Error", ex);
}
finally
{
AsyncTaskFinished (1);
}
});
}
private static bool Is404(Exception e)
{
return e is HttpException && ((HttpException)e).GetHttpCode () == 404;
}
internal abstract void BeginReplicating();
/// <summary>CHECKPOINT STORAGE:</summary>
protected internal virtual void MaybeCreateRemoteDB() { }
// FIXME: No-op.
abstract internal void ProcessInbox(RevisionList inbox);
internal void AsyncTaskStarted()
{ // TODO.ZJG: Replace lock with Interlocked.CompareExchange.
lock (asyncTaskLocker)
{
Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": asyncTaskStarted() called, asyncTaskCount: " + asyncTaskCount);
if (asyncTaskCount++ == 0)
{
UpdateActive();
}
Log.D(Database.Tag, "asyncTaskStarted() updated asyncTaskCount to " + asyncTaskCount);
}
}
internal void AsyncTaskFinished(Int32 numTasks)
{ // TODO.ZJG: Replace lock with Interlocked.CompareExchange.
lock (asyncTaskLocker) {
Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": asyncTaskFinished() called, asyncTaskCount: "
+ asyncTaskCount + " numTasks: " + numTasks);
asyncTaskCount -= numTasks;
if (asyncTaskCount == 0)
{
if (!continuous)
{
UpdateActive();
}
}
Log.D(Tag, "asyncTaskFinished() updated asyncTaskCount to: " + asyncTaskCount);
}
}
internal void UpdateActive()
{
try {
var batcherCount = 0;
if (Batcher != null)
{
batcherCount = Batcher.Count();
}
else
{
Log.W(Tag, this + ": batcher object is null");
}
Boolean newActive = batcherCount > 0 || asyncTaskCount > 0;
if (active != newActive)
{
Log.D(Tag, this + " Progress: set active = " + newActive + " asyncTaskCount: " + asyncTaskCount + " batcherCount: " + batcherCount );
active = newActive;
NotifyChangeListeners();
if (!active)
{
if (!continuous)
{
Log.D(Tag, this + " since !continuous, calling stopped()");
Stopped();
}
else if (LastError != null) /*(revisionsFailed > 0)*/
{
string msg = string.Format("%s: Failed to xfer %d revisions, will retry in %d sec", this, revisionsFailed, RetryDelay);
Log.D(Tag, msg);
CancelPendingRetryIfReady();
ScheduleRetryIfReady();
}
}
}
}
catch (Exception e)
{
Log.E(Tag, "Exception in updateActive()", e);
}
}
internal virtual void Stopped()
{
Log.V(Tag, ToString() + " STOPPING");
IsRunning = false;
completedChangesCount = changesCount = 0;
NotifyChangeListeners();
SaveLastSequence();
Log.V(Tag, this + " set batcher to null");
Batcher = null;
ClearDbRef();
Log.V(Database.Tag, ToString() + " STOPPED");
}
internal void SaveLastSequence()
{
if (!lastSequenceChanged)
{
return;
}
if (savingCheckpoint)
{
// If a save is already in progress, don't do anything. (The completion block will trigger
// another save after the first one finishes.)
overdueForSave = true;
return;
}
lastSequenceChanged = false;
overdueForSave = false;
Log.D(Tag, this + " saveLastSequence() called. lastSequence: " + LastSequence);
var body = new Dictionary<String, Object>();
if (remoteCheckpoint != null)
{
body.PutAll(remoteCheckpoint);
}
body["lastSequence"] = LastSequence;
var remoteCheckpointDocID = RemoteCheckpointDocID();
if (String.IsNullOrEmpty(remoteCheckpointDocID))
{
Log.W(Tag, this + ": remoteCheckpointDocID is null, aborting saveLastSequence()");
return;
}
savingCheckpoint = true;
Log.D(Tag, this + " put remote _local document. checkpointID: " + remoteCheckpointDocID);
SendAsyncRequest(HttpMethod.Put, "/_local/" + remoteCheckpointDocID, body, (result, e) => {
savingCheckpoint = false;
if (e != null)
{
Log.V (Tag, this + ": Unable to save remote checkpoint", e);
}
if (LocalDatabase == null)
{
Log.W(Tag, this + ": Database is null, ignoring remote checkpoint response");
return;
}
if (e != null)
{
switch (GetStatusFromError(e))
{
case StatusCode.NotFound:
{
remoteCheckpoint = null;
overdueForSave = true;
break;
}
case StatusCode.Conflict:
{
RefreshRemoteCheckpointDoc();
break;
}
default:
{
// TODO: On 401 or 403, and this is a pull, remember that remote
// TODO: is read-only & don't attempt to read its checkpoint next time.
break;
}
}
}
else
{
var response = (IDictionary<String, Object>)result;
body.Put ("_rev", response.Get ("rev"));
remoteCheckpoint = body;
LocalDatabase.SetLastSequence(LastSequence, RemoteCheckpointDocID(), IsPull);
}
if (overdueForSave) {
SaveLastSequence ();
}
});
}
internal void SendAsyncRequest(HttpMethod method, string relativePath, object body, RemoteRequestCompletionBlock completionHandler)
{
try
{
var urlStr = BuildRelativeURLString(relativePath);
var url = new Uri(urlStr);
SendAsyncRequest(method, url, body, completionHandler);
}
catch (UriFormatException e)
{
Log.E(Tag, "Malformed URL for async request", e);
}
}
internal String BuildRelativeURLString(String relativePath)
{
// the following code is a band-aid for a system problem in the codebase
// where it is appending "relative paths" that start with a slash, eg:
// http://dotcom/db/ + /relpart == http://dotcom/db/relpart
// which is not compatible with the way the java url concatonation works.
var remoteUrlString = RemoteUrl.ToString();
if (remoteUrlString.EndsWith ("/", StringComparison.InvariantCultureIgnoreCase) && relativePath.StartsWith ("/", StringComparison.InvariantCultureIgnoreCase))
{
remoteUrlString = remoteUrlString.Substring(0, remoteUrlString.Length - 1);
}
return remoteUrlString + relativePath;
}
internal void SendAsyncRequest(HttpMethod method, Uri url, Object body, RemoteRequestCompletionBlock completionHandler)
{
var message = new HttpRequestMessage(method, url);
var mapper = Manager.GetObjectMapper();
if (body != null)
{
var bytes = mapper.WriteValueAsBytes(body).ToArray();
var byteContent = new ByteArrayContent(bytes);
message.Content = byteContent;
}
message.Headers.Add("Accept", new[] { "multipart/related", "application/json" });
PreemptivelySetAuthCredentials(message);
var client = clientFactory.GetHttpClient();
client.CancelPendingRequests();
client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, CancellationTokenSource.Token)
.ContinueWith(response => {
if (response.Status != TaskStatus.RanToCompletion)
{
Log.E(Tag, "SendAsyncRequest did not run to completion.", response.Exception);
return null;
}
return response.Result;
}, CancellationTokenSource.Token)
.ContinueWith(response => {
if (completionHandler != null) {
var fullBody = mapper.ReadValue<Object>(response.Result.Content.ReadAsStreamAsync().Result);
Exception error = response.Exception;
if (error == null && !response.Result.IsSuccessStatusCode)
{
error = new HttpResponseException(response.Result.StatusCode);
}
completionHandler (fullBody, response.Exception);
}
});
}
void PreemptivelySetAuthCredentials (HttpRequestMessage message)
{
// FIXME Not sure we actually need this, since our handler should do it.. Will find out in tests.
// if the URL contains user info AND if this a DefaultHttpClient
// then preemptively set the auth credentials
// if (url.GetUserInfo() != null)
// {
// if (url.GetUserInfo().Contains(":") && !url.GetUserInfo().Trim().Equals(":"))
// {
// string[] userInfoSplit = url.GetUserInfo().Split(":");
// Credentials creds = new UsernamePasswordCredentials(URIUtils.Decode(userInfoSplit
// [0]), URIUtils.Decode(userInfoSplit[1]));
// if (httpClient is DefaultHttpClient)
// {
// DefaultHttpClient dhc = (DefaultHttpClient)httpClient;
// IHttpRequestInterceptor preemptiveAuth = new _IHttpRequestInterceptor_167(creds);
// dhc.AddRequestInterceptor(preemptiveAuth, 0);
// }
// }
// else
// {
// Log.W(Database.Tag, "RemoteRequest Unable to parse user info, not setting credentials"
// );
// }
// }
}
private void AddRequestHeaders(HttpRequestMessage request)
{
foreach (string requestHeaderKey in RequestHeaders.Keys)
{
request.Headers.Add(requestHeaderKey, RequestHeaders.Get(requestHeaderKey).ToString());
}
}
internal void SendAsyncMultipartDownloaderRequest(HttpMethod method, string relativePath, object body, Database db, RemoteRequestCompletionBlock onCompletion)
{
try
{
var urlStr = BuildRelativeURLString(relativePath);
var url = new Uri(urlStr);
var message = new HttpRequestMessage(method, url);
message.Headers.Add("Accept", "*/*");
AddRequestHeaders(message);
var httpClient = clientFactory.GetHttpClient();
httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, CancellationTokenSource.Token)
.ContinueWith(new Action<Task<HttpResponseMessage>>(responseMessage=> {
object fullBody = null;
Exception error = null;
try
{
var response = responseMessage.Result;
// add in cookies to global store
CouchbaseLiteHttpClientFactory.Instance.AddCookies(clientFactory.HttpHandler.CookieContainer.GetCookies(url));
var status = response.StatusCode;
if ((Int32)status.GetStatusCode() >= 300)
{
Log.E(Database.Tag, "Got error " + Sharpen.Extensions.ToString(status.GetStatusCode
()));
Log.E(Database.Tag, "Request was for: " + message);
Log.E(Database.Tag, "Status reason: " + response.ReasonPhrase);
error = new HttpException((Int32)status.GetStatusCode(), response.ReasonPhrase);
}
else
{
var entity = response.Content;
var contentTypeHeader = response.Content.Headers.ContentType;
InputStream inputStream = null;
if (contentTypeHeader != null && contentTypeHeader.ToString().Contains("multipart/related"))
{
try
{
var reader = new MultipartDocumentReader(responseMessage.Result, LocalDatabase);
reader.SetContentType(contentTypeHeader.MediaType);
var inputStreamTask = entity.ReadAsStreamAsync();
inputStreamTask.Wait(90000, CancellationTokenSource.Token);
const int bufLen = 1024;
var buffer = new byte[bufLen];
int numBytesRead = 0;
while ((numBytesRead = inputStream.Read(buffer)) != -1)
{
if (numBytesRead != bufLen)
{
var bufferToAppend = new ArraySegment<Byte>(buffer, 0, numBytesRead).Array;
reader.AppendData(bufferToAppend);
}
else
{
reader.AppendData(buffer);
}
}
reader.Finish();
fullBody = reader.GetDocumentProperties();
if (onCompletion != null)
onCompletion(fullBody, error);
}
finally
{
try
{
inputStream.Close();
}
catch (IOException)
{
// NOTE: swallow?
}
}
}
else
{
if (entity != null)
{
try
{
var readTask = entity.ReadAsStreamAsync();
readTask.Wait(); // TODO: This should be scaled based on content length.
inputStream = readTask.Result;
fullBody = Manager.GetObjectMapper().ReadValue<Object>(inputStream);
if (onCompletion != null)
onCompletion(fullBody, error);
}
catch (Exception ex)
{
Log.E(Tag, ex.Message);
}
finally
{
try
{
inputStream.Close();
}
catch (IOException)
{
}
}
}
}
}
}
catch (ProtocolViolationException e)
{
Log.E(Database.Tag, "client protocol exception", e);
error = e;
}
catch (IOException e)
{
Log.E(Database.Tag, "io exception", e);
error = e;
}
}));
}
catch (UriFormatException e)
{
Log.E(Database.Tag, "Malformed URL for async request", e);
}
}
internal void SendAsyncMultipartRequest(HttpMethod method, String relativePath, MultipartContent multiPartEntity, RemoteRequestCompletionBlock completionHandler)
{
Uri url = null;
try
{
var urlStr = BuildRelativeURLString(relativePath);
url = new Uri(urlStr);
}
catch (UriFormatException e)
{
throw new ArgumentException("Invalid URI format.", e);
}
var message = new HttpRequestMessage(method, url);
message.Content = multiPartEntity;
message.Headers.Add("Accept", "*/*");
PreemptivelySetAuthCredentials(message);
var client = clientFactory.GetHttpClient();
client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, CancellationTokenSource.Token)
.ContinueWith(response=> {
if (response.Status != TaskStatus.RanToCompletion)
{
Log.E(Tag, "SendAsyncRequest did not run to completion.", response.Exception);
return null;
}
return response.Result.Content.ReadAsStreamAsync();
}, CancellationTokenSource.Token)
.ContinueWith(response=> {
if (response.Status != TaskStatus.RanToCompletion)
{
Log.E(Tag, "SendAsyncRequest did not run to completion.", response.Exception);
} else if (response.Result.Result == null || response.Result.Result.Length == 0)
{
Log.E(Tag, "Server returned an empty response.", response.Exception);
}
if (completionHandler != null) {
var mapper = Manager.GetObjectMapper();
var fullBody = mapper.ReadValue<Object>(response.Result.Result);
completionHandler (fullBody, response.Exception);
}
}, CancellationTokenSource.Token);
}
// Pusher overrides this to implement the .createTarget option
/// <summary>This is the _local document ID stored on the remote server to keep track of state.
/// </summary>
/// <remarks>
/// This is the _local document ID stored on the remote server to keep track of state.
/// Its ID is based on the local database ID (the private one, to make the result unguessable)
/// and the remote database's URL.
/// </remarks>
internal String RemoteCheckpointDocID()
{
if (LocalDatabase == null)
return null;
var input = LocalDatabase.PrivateUUID () + "\n" + RemoteUrl + "\n" + (!IsPull ? "1" : "0");
return Misc.TDHexSHA1Digest(Runtime.GetBytesForString(input));
}
internal StatusCode GetStatusFromError(Exception e)
{
var couchbaseLiteException = e as CouchbaseLiteException;
if (couchbaseLiteException != null)
{
return couchbaseLiteException.GetCBLStatus().GetCode();
}
return StatusCode.Unknown;
}
internal void RefreshRemoteCheckpointDoc()
{
Log.D(Tag, this + ": Refreshing remote checkpoint to get its _rev...");
savingCheckpoint = true;
AsyncTaskStarted();
SendAsyncRequest(HttpMethod.Get, "/_local/" + RemoteCheckpointDocID(), null, (result, e) =>
{
try
{
if (LocalDatabase == null)
{
Log.W(Tag, this + ": db == null while refreshing remote checkpoint. aborting");
return;
}
savingCheckpoint = false;
if (e != null && GetStatusFromError(e) != StatusCode.NotFound)
{
Log.E(Database.Tag, this + ": Error refreshing remote checkpoint", e);
}
else
{
Log.D(Database.Tag, this + ": Refreshed remote checkpoint: " + result);
remoteCheckpoint = (IDictionary<string, object>)result;
lastSequenceChanged = true;
SaveLastSequence();
}
}
finally
{
AsyncTaskFinished(1);
}
}
);
}
internal void RevisionFailed()
{
revisionsFailed++;
}
/// <summary>
/// Called after a continuous replication has gone idle, but it failed to transfer some revisions
/// and so wants to try again in a minute.
/// </summary>
/// <remarks>
/// Called after a continuous replication has gone idle, but it failed to transfer some revisions
/// and so wants to try again in a minute. Should be overridden by subclasses.
/// </remarks>
protected internal virtual void Retry()
{
LastError = null;
}
protected internal virtual void RetryIfReady()
{
if (!IsRunning)
{
return;
}
if (online)
{
Log.D(Tag, this + " RETRYING, to transfer missed revisions...");
revisionsFailed = 0;
CancelPendingRetryIfReady();
Retry();
}
else
{
ScheduleRetryIfReady();
}
}
protected internal virtual void CancelPendingRetryIfReady()
{
if (RetryIfReadyTask != null && !RetryIfReadyTask.IsCanceled && RetryIfReadyTokenSource != null)
{
RetryIfReadyTokenSource.Cancel();
}
}
protected internal virtual void ScheduleRetryIfReady()
{
RetryIfReadyTokenSource = new CancellationTokenSource();
RetryIfReadyTask = Task.Delay(RetryDelay * 1000)
.ContinueWith(task =>
{
if (RetryIfReadyTokenSource != null && !RetryIfReadyTokenSource.IsCancellationRequested)
RetryIfReady();
}, RetryIfReadyTokenSource.Token);
}
#endregion
#region Instance Members
/// <summary>
/// Gets the local <see cref="Couchbase.Lite.Database"/> being replicated to\from.
/// </summary>
public Database LocalDatabase { get; private set; }
/// <summary>
/// Gets the remote URL being replicated to/from.
/// </summary>
public Uri RemoteUrl { get; private set; }
/// <summary>
/// Gets whether the <see cref="Couchbase.Lite.Replication"/> pulls from, as opposed to pushes to, the target.
/// </summary>
public abstract Boolean IsPull { get; }
/// <summary>
/// Gets or sets whether the target <see cref="Couchbase.Lite.Database"/> will be created if it doesn't already exist.
/// </summary>
public abstract Boolean CreateTarget { get; set; }
/// <summary>
/// Gets or sets whether the <see cref="Couchbase.Lite.Replication"/> operates continuously, replicating
/// changes as the source <see cref="Couchbase.Lite.Database"/> is modified.
/// </summary>
public Boolean Continuous
{
get { return continuous; }
set { if (!IsRunning) continuous = value; }
}
/// <summary>
/// Gets or sets the name of an optional filter function to run on the source
/// <see cref="Couchbase.Lite.Database"/>. Only documents for which the function returns <c>true</c> are replicated.
/// </summary>
public String Filter { get; set; }
/// <summary>
/// Gets or sets the parameters to pass to the filter function.
/// </summary>
public IDictionary<String, String> FilterParams { get; set; }
/// <summary>
/// Gets or sets the list of Sync Gateway channel names to filter by for pull <see cref="Couchbase.Lite.Replication"/>.
/// </summary>
/// <remarks>
/// A null value means no filtering, and all available channels will be replicated. Only valid for pull
/// replications whose source database is on a Couchbase Sync Gateway server. This is a convenience property
/// that just sets the values of filter and filterParams.
/// </remarks>
public abstract IEnumerable<String> Channels { get; set; }
/// <summary>
/// Gets or sets the ids of the <see cref="Couchbase.Lite.Document"/>s to replicate.
/// </summary>
public abstract IEnumerable<String> DocIds { get; set; }
/// <summary>
/// Gets or sets the extra HTTP headers to send in <see cref="Couchbase.Lite.Replication"/> requests to the
/// remote <see cref="Couchbase.Lite.Database"/>.
/// </summary>
public abstract Dictionary<String, String> Headers { get; set; }
/// <summary>
/// Gets the <see cref="Couchbase.Lite.Replication"/>'s current status.
/// </summary>
public ReplicationStatus Status { get; set; }
/// <summary>
/// Gets whether the <see cref="Couchbase.Lite.Replication"/> is running. Continuous <see cref="Couchbase.Lite.Replication"/> never actually stop, instead they go
/// idle waiting for new data to appear.
/// </summary>
/// <value><c>true</c> if this instance is running; otherwise, <c>false</c>.</value>
public Boolean IsRunning { get; protected set; }
/// <summary>
/// Gets the last error, if any, that occurred since the <see cref="Couchbase.Lite.Replication"/> was started.
/// </summary>
public Exception LastError { get; protected set; }
/// <summary>
/// If the <see cref="Couchbase.Lite.Replication"/> is active, gets the number of completed changes that have been processed, otherwise 0.
/// </summary>
/// <value>The completed changes count.</value>
public Int32 CompletedChangesCount {
get { return completedChangesCount; }
protected set {
completedChangesCount = value;
NotifyChangeListeners();
}
}
/// <summary>
/// If the <see cref="Couchbase.Lite.Replication"/> is active, gets the number of changes to be processed, otherwise 0.
/// </summary>
/// <value>The changes count.</value>
public Int32 ChangesCount {
get { return changesCount; }
protected set {
changesCount = value;
NotifyChangeListeners();
}
}
protected void SetLastError(Exception error) {
if (LastError != error)
{
Log.E(Tag, this + " Progress: set error = " + error);
LastError = error;
NotifyChangeListeners();
}
}
//Methods
/// <summary>
/// Starts the <see cref="Couchbase.Lite.Replication"/>.
/// </summary>
public void Start()
{
if (!LocalDatabase.Open())
{
// Race condition: db closed before replication starts
Log.W(Tag, "Not starting replication because db.isOpen() returned false.");
return;
}
if (IsRunning)
{
return;
}
LocalDatabase.AddReplication(this);
LocalDatabase.AddActiveReplication(this);
sessionID = string.Format("repl{0:000}", ++lastSessionID);
Log.V(Database.Tag, ToString() + " STARTING ...");
IsRunning = true;
LastSequence = null;
CheckSession();
}
/// <summary>
/// Stops the <see cref="Couchbase.Lite.Replication"/>.
/// </summary>
public virtual void Stop()
{
if (!IsRunning)
{
return;
}
Log.V(Database.Tag, ToString() + " STOPPING...");
Batcher.Clear();
// no sense processing any pending changes
continuous = false;
StopRemoteRequests();
CancelPendingRetryIfReady();
LocalDatabase.ForgetReplication(this);
if (IsRunning && asyncTaskCount == 0)
{
Stopped();
}
}
public void Restart()
{
// TODO: add the "started" flag and check it here
Stop();
Start();
}
public event EventHandler<ReplicationChangeEventArgs> Changed;
#endregion
#region EventArgs Subclasses
public class ReplicationChangeEventArgs : EventArgs
{
//Properties
public Replication Source { get; private set; }
public ReplicationChangeEventArgs (Replication sender)
{
Source = sender;
}
}
#endregion
}
}
| |
using System.Net;
using Facility.ConformanceApi;
using Facility.ConformanceApi.Http;
using Facility.ConformanceApi.Testing;
using Facility.Core;
using Facility.Core.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
namespace FacilityConformance;
public sealed class FacilityConformanceApp
{
public static async Task<int> Main(string[] args)
{
try
{
return await new FacilityConformanceApp().RunAsync(args);
}
catch (ArgsReaderException exception)
{
if (!string.IsNullOrWhiteSpace(exception.Message))
{
Console.WriteLine(exception.Message);
Console.WriteLine();
}
const int columnWidth = 40;
Console.WriteLine("Commands:");
Console.WriteLine(" host [--url <url>]".PadRight(columnWidth) + "Hosts a conformance server");
Console.WriteLine(" test [--url <url>] [<test> ...]".PadRight(columnWidth) + "Tests a conformance server");
Console.WriteLine(" fsd [--output <path> [--verify]]".PadRight(columnWidth) + "Writes the Conformance API FSD");
Console.WriteLine(" json [--output <path> [--verify]]".PadRight(columnWidth) + "Writes the conformance test data");
return -1;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return -2;
}
}
public FacilityConformanceApp()
{
using (var fsdTextReader = new StreamReader(GetType().Assembly.GetManifestResourceStream("FacilityConformance.ConformanceApi.fsd")!))
m_fsdText = fsdTextReader.ReadToEnd();
using (var testsJsonReader = new StreamReader(GetType().Assembly.GetManifestResourceStream("FacilityConformance.ConformanceTests.json")!))
m_testsJson = testsJsonReader.ReadToEnd();
}
public async Task<int> RunAsync(IReadOnlyList<string> args)
{
const string defaultUrl = "http://localhost:4117/";
var argsReader = new ArgsReader(args);
if (argsReader.ReadFlag("?|h|help"))
throw new ArgsReaderException("");
var serializerName = argsReader.ReadOption("serializer")?.ToLowerInvariant();
ServiceSerializer serializer = serializerName switch
{
null or "systemtextjson" => SystemTextJsonServiceSerializer.Instance,
"newtonsoftjson" or "obsoletejson" => NewtonsoftJsonServiceSerializer.Instance,
_ => throw new ArgsReaderException("Unsupported serializer."),
};
var contentSerializer = HttpContentSerializer.Create(serializer);
#pragma warning disable CS0618 // Type or member is obsolete
if (serializerName is "obsoletejson")
contentSerializer = new JsonHttpContentSerializer(new JsonHttpContentSerializerSettings { ForceAsyncIO = true });
#pragma warning restore CS0618 // Type or member is obsolete
var jsonSerializer = serializer as JsonServiceSerializer ?? NewtonsoftJsonServiceSerializer.Instance;
var tests = ConformanceTestsInfo.FromJson(m_testsJson, jsonSerializer).Tests!;
var command = argsReader.ReadArgument();
if (command == "host")
{
var url = argsReader.ReadOption("url") ?? defaultUrl;
argsReader.VerifyComplete();
var service = new ConformanceApiService(
new ConformanceApiServiceSettings
{
Tests = tests,
JsonSerializer = jsonSerializer,
});
await new WebHostBuilder()
.UseKestrel(options => options.AllowSynchronousIO = serializerName is "newtonsoftjson")
.UseUrls(url)
.Configure(app => app.Run(httpContext => HostAsync(httpContext, service, contentSerializer)))
.Build()
.RunAsync();
return 0;
}
if (command == "test")
{
var baseUri = new Uri(argsReader.ReadOption("url") ?? defaultUrl);
var testNames = argsReader.ReadArguments();
argsReader.VerifyComplete();
var api = new HttpClientConformanceApi(
new HttpClientServiceSettings
{
BaseUri = baseUri,
ContentSerializer = contentSerializer,
});
var tester = new ConformanceApiTester(
new ConformanceApiTesterSettings
{
Tests = tests,
Api = api,
HttpClient = new HttpClient { BaseAddress = baseUri },
JsonSerializer = jsonSerializer,
});
var results = new List<ConformanceTestResult>();
if (testNames.Count == 0)
{
results.AddRange((await tester.RunAllTestsAsync()).Results);
}
else
{
foreach (var testName in testNames)
{
var testInfo = tests.SingleOrDefault(x => x.Test == testName);
if (testInfo == null)
{
Console.WriteLine($"Test not found: {testName}");
return -1;
}
results.Add(await tester.RunTestAsync(testInfo));
}
}
var failureCount = 0;
foreach (var result in results.Where(x => x.Status == ConformanceTestStatus.Fail))
{
Console.WriteLine($"{result.TestName} fail: {result.Message}");
failureCount++;
}
Console.WriteLine($"{results.Count} tests: {results.Count - failureCount} passed, {failureCount} failed.");
return failureCount == 0 ? 0 : 1;
}
if (command == "fsd")
{
var outputPath = argsReader.ReadOption("output");
var shouldVerify = argsReader.ReadFlag("verify");
argsReader.VerifyComplete();
return WriteText(path: outputPath, contents: m_fsdText, shouldVerify: shouldVerify);
}
if (command == "json")
{
var outputPath = argsReader.ReadOption("output");
var shouldVerify = argsReader.ReadFlag("verify");
argsReader.VerifyComplete();
return WriteText(path: outputPath, contents: m_testsJson, shouldVerify: shouldVerify);
}
if (command != null)
throw new ArgsReaderException($"Invalid command: {command}");
throw new ArgsReaderException("Missing command.");
}
private static int WriteText(string? path, string contents, bool shouldVerify)
{
if (path != null)
{
if (shouldVerify)
{
if (!File.Exists(path: path) || File.ReadAllText(path: path) != contents)
return 1;
}
else
{
var directory = Path.GetDirectoryName(path);
if (directory != null && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
File.WriteAllText(path: path, contents: contents);
}
}
else
{
if (shouldVerify)
throw new ArgsReaderException("--verify requires --output.");
Console.Write(contents);
}
return 0;
}
private async Task HostAsync(HttpContext httpContext, IConformanceApi service, HttpContentSerializer contentSerializer)
{
var httpRequest = httpContext.Request;
var requestUrl = httpRequest.GetEncodedUrl();
var apiHandler = new ConformanceApiHttpHandler(service, new ServiceHttpHandlerSettings { ContentSerializer = contentSerializer });
var requestMessage = new HttpRequestMessage(new HttpMethod(httpRequest.Method), requestUrl)
{
Content = new StreamContent(httpRequest.Body),
};
foreach (var header in httpRequest.Headers)
{
// Every header should be able to fit into one of the two header collections.
// Try message.Headers first since that accepts more of them.
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable()))
requestMessage.Content.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable());
}
HttpResponseMessage? responseMessage = null;
ServiceErrorDto? error = null;
try
{
responseMessage = await apiHandler.TryHandleHttpRequestAsync(requestMessage, httpContext.RequestAborted).ConfigureAwait(false);
if (responseMessage == null)
error = ServiceErrors.CreateInvalidRequest($"Test not found for {httpRequest.Method} {requestUrl}");
}
catch (Exception exception)
{
error = ServiceErrorUtility.CreateInternalErrorForException(exception);
}
if (error != null)
{
var statusCode = HttpServiceErrors.TryGetHttpStatusCode(error.Code) ?? HttpStatusCode.InternalServerError;
responseMessage = new HttpResponseMessage(statusCode) { Content = contentSerializer.CreateHttpContent(error) };
}
if (responseMessage != null)
{
using (responseMessage)
{
var response = httpContext.Response;
response.StatusCode = (int) responseMessage.StatusCode;
var responseHeaders = responseMessage.Headers;
// Ignore the Transfer-Encoding header if it is just "chunked".
// We let the host decide about whether the response should be chunked or not.
if (responseHeaders.TransferEncodingChunked == true && responseHeaders.TransferEncoding.Count == 1)
responseHeaders.TransferEncoding.Clear();
foreach (var header in responseHeaders)
response.Headers.Append(header.Key, header.Value.ToArray());
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (responseMessage.Content != null)
{
var contentHeaders = responseMessage.Content.Headers;
// Copy the response content headers only after ensuring they are complete.
// We ask for Content-Length first because HttpContent lazily computes this
// and only afterwards writes the value into the content headers.
_ = contentHeaders.ContentLength;
foreach (var header in contentHeaders)
response.Headers.Append(header.Key, header.Value.ToArray());
await responseMessage.Content.CopyToAsync(response.Body).ConfigureAwait(false);
}
}
}
}
private readonly string m_fsdText;
private readonly string m_testsJson;
}
| |
#if !DISABLE_PLAYFABCLIENT_API
using PlayFab.ClientModels;
using PlayFab.Json;
using System;
using System.Collections.Generic;
namespace PlayFab.UUnit
{
/// <summary>
/// A real system would potentially run only the client or server API, and not both.
/// But, they still interact with eachother directly.
/// The tests can't be independent for Client/Server, as the sequence of calls isn't really independent for real-world scenarios.
/// The client logs in, which triggers a server, and then back and forth.
/// For the purpose of testing, they each have pieces of information they share with one another, and that sharing makes various calls possible.
/// </summary>
public class ClientApiTests : UUnitTestCase
{
private Action _tickAction = null;
// Test-data constants
private const string TEST_STAT_NAME = "str";
private const string TEST_DATA_KEY = "testCounter";
// Fixed values provided from testInputs
private static string _userEmail;
public static string PlayFabId; // Public because the test framework uses this when tests are complete (could be better)
// This test operates multi-threaded, so keep some thread-transfer varaibles
private int _testInteger;
public override void SetUp(UUnitTestContext testContext)
{
var titleData = TestTitleDataLoader.LoadTestTitleData();
_userEmail = titleData.userEmail;
// Verify all the inputs won't cause crashes in the tests
var titleInfoSet = !string.IsNullOrEmpty(PlayFabSettings.TitleId) && !string.IsNullOrEmpty(_userEmail);
if (!titleInfoSet)
testContext.Skip(); // We cannot do client tests if the titleId is not given
}
public override void Tick(UUnitTestContext testContext)
{
if (_tickAction != null)
_tickAction();
}
public override void TearDown(UUnitTestContext testContext)
{
PlayFabSettings.AdvertisingIdType = null;
PlayFabSettings.AdvertisingIdValue = null;
_tickAction = null;
}
private void SharedErrorCallback(PlayFabError error)
{
// This error was not expected. Report it and fail.
((UUnitTestContext)error.CustomData).Fail(error.GenerateErrorReport());
}
/// <summary>
/// CLIENT API
/// Try to deliberately log in with an inappropriate password,
/// and verify that the error displays as expected.
/// </summary>
[UUnitTest]
public void InvalidLogin(UUnitTestContext testContext)
{
// If the setup failed to log in a user, we need to create one.
var request = new LoginWithEmailAddressRequest
{
TitleId = PlayFabSettings.TitleId,
Email = _userEmail,
Password = "INVALID",
};
PlayFabClientAPI.LoginWithEmailAddress(request, PlayFabUUnitUtils.ApiActionWrapper<LoginResult>(testContext, InvalidLoginCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, ExpectedLoginErrorCallback), testContext);
}
private void InvalidLoginCallback(LoginResult result)
{
((UUnitTestContext)result.CustomData).Fail("Login was not expected to pass.");
}
private void ExpectedLoginErrorCallback(PlayFabError error)
{
var errorReport = error.GenerateErrorReport().ToLower();
var testContext = (UUnitTestContext)error.CustomData;
testContext.False(errorReport.Contains("successful"), errorReport);
testContext.True(errorReport.Contains("password"), errorReport);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Try to deliberately register a user with an invalid email and password.
/// Verify that errorDetails are populated correctly.
/// </summary>
[UUnitTest]
public void InvalidRegistration(UUnitTestContext testContext)
{
var registerRequest = new RegisterPlayFabUserRequest
{
Username = "x", // Provide invalid inputs for multiple parameters, which will show up in errorDetails
Email = "x", // Provide invalid inputs for multiple parameters, which will show up in errorDetails
Password = "x", // Provide invalid inputs for multiple parameters, which will show up in errorDetails
};
PlayFabClientAPI.RegisterPlayFabUser(registerRequest, PlayFabUUnitUtils.ApiActionWrapper<RegisterPlayFabUserResult>(testContext, InvalidRegistrationCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, ExpectedRegisterErrorCallback), testContext);
}
private void InvalidRegistrationCallback(RegisterPlayFabUserResult result)
{
((UUnitTestContext)result.CustomData).Fail("Register was not expected to pass.");
}
private void ExpectedRegisterErrorCallback(PlayFabError error)
{
var expectedEmailMsg = "email address is not valid.";
var expectedPasswordMsg = "password must be between";
var errorReport = error.GenerateErrorReport().ToLower();
var testContext = (UUnitTestContext)error.CustomData;
testContext.True(errorReport.Contains(expectedEmailMsg), errorReport);
testContext.True(errorReport.Contains(expectedPasswordMsg), errorReport);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Log in or create a user, track their PlayFabId
/// </summary>
[UUnitTest]
public void LoginOrRegister(UUnitTestContext testContext)
{
var loginRequest = new LoginWithCustomIDRequest
{
CustomId = PlayFabSettings.BuildIdentifier,
CreateAccount = true,
};
PlayFabClientAPI.LoginWithCustomID(loginRequest, PlayFabUUnitUtils.ApiActionWrapper<LoginResult>(testContext, LoginCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void LoginCallback(LoginResult result)
{
PlayFabId = result.PlayFabId;
var testContext = (UUnitTestContext)result.CustomData;
testContext.True(PlayFabClientAPI.IsClientLoggedIn(), "User login failed");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that the login call sequence sends the AdvertisingId when set
/// </summary>
[UUnitTest]
public void LoginWithAdvertisingId(UUnitTestContext testContext)
{
#if (!UNITY_IOS && !UNITY_ANDROID) || (!UNITY_5_3 && !UNITY_5_4 && !UNITY_5_5)
PlayFabSettings.AdvertisingIdType = PlayFabSettings.AD_TYPE_ANDROID_ID;
PlayFabSettings.AdvertisingIdValue = "PlayFabTestId";
#endif
var loginRequest = new LoginWithCustomIDRequest
{
CustomId = PlayFabSettings.BuildIdentifier,
CreateAccount = true,
};
PlayFabClientAPI.LoginWithCustomID(loginRequest, PlayFabUUnitUtils.ApiActionWrapper<LoginResult>(testContext, AdvertLoginCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void AdvertLoginCallback(LoginResult result)
{
PlayFabId = result.PlayFabId;
var testContext = (UUnitTestContext)result.CustomData;
testContext.True(PlayFabClientAPI.IsClientLoggedIn(), "User login failed");
var target = PlayFabSettings.AD_TYPE_ANDROID_ID + "_Successful";
var failTime = DateTime.UtcNow + TimeSpan.FromSeconds(10);
_tickAction = () =>
{
if (target == PlayFabSettings.AdvertisingIdType)
testContext.EndTest(UUnitFinishState.PASSED, PlayFabSettings.AdvertisingIdValue);
if (DateTime.UtcNow > failTime)
testContext.EndTest(UUnitFinishState.FAILED, "Timed out waiting for advertising attribution confirmation");
};
}
/// <summary>
/// CLIENT API
/// Test a sequence of calls that modifies saved data,
/// and verifies that the next sequential API call contains updated data.
/// Verify that the data is correctly modified on the next call.
/// Parameter types tested: string, Dictionary<string, string>, DateTime
/// </summary>
[UUnitTest]
public void UserDataApi(UUnitTestContext testContext)
{
var getRequest = new GetUserDataRequest();
PlayFabClientAPI.GetUserData(getRequest, PlayFabUUnitUtils.ApiActionWrapper<GetUserDataResult>(testContext, GetUserDataCallback1), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetUserDataCallback1(GetUserDataResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
UserDataRecord userDataRecord;
_testInteger = 0; // Default if the data isn't present
if (result.Data.TryGetValue(TEST_DATA_KEY, out userDataRecord))
int.TryParse(userDataRecord.Value, out _testInteger);
_testInteger = (_testInteger + 1) % 100; // This test is about the Expected value changing - but not testing more complicated issues like bounds
var updateRequest = new UpdateUserDataRequest
{
Data = new Dictionary<string, string>
{
{ TEST_DATA_KEY, _testInteger.ToString() }
}
};
PlayFabClientAPI.UpdateUserData(updateRequest, PlayFabUUnitUtils.ApiActionWrapper<UpdateUserDataResult>(testContext, UpdateUserDataCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void UpdateUserDataCallback(UpdateUserDataResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
var getRequest = new GetUserDataRequest();
PlayFabClientAPI.GetUserData(getRequest, PlayFabUUnitUtils.ApiActionWrapper<GetUserDataResult>(testContext, GetUserDataCallback2), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetUserDataCallback2(GetUserDataResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
UserDataRecord userDataRecord;
var actualValue = 0; // Default if the data isn't present
if (result.Data.TryGetValue(TEST_DATA_KEY, out userDataRecord))
int.TryParse(userDataRecord.Value, out actualValue);
testContext.IntEquals(_testInteger, actualValue);
testContext.NotNull(userDataRecord, "UserData record not found");
var timeUpdated = userDataRecord.LastUpdated;
var minTest = DateTime.UtcNow - TimeSpan.FromMinutes(5);
var maxTest = DateTime.UtcNow + TimeSpan.FromMinutes(5);
testContext.True(minTest <= timeUpdated && timeUpdated <= maxTest);
testContext.True(Math.Abs((DateTime.UtcNow - timeUpdated).TotalMinutes) < 5); // Make sure that this timestamp is recent - This must also account for the difference between local machine time and server time
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test a sequence of calls that modifies saved data,
/// and verifies that the next sequential API call contains updated data.
/// Verify that the data is saved correctly, and that specific types are tested
/// Parameter types tested: Dictionary<string, int>
/// </summary>
[UUnitTest]
public void PlayerStatisticsApi(UUnitTestContext testContext)
{
var getRequest = new GetPlayerStatisticsRequest();
PlayFabClientAPI.GetPlayerStatistics(getRequest, PlayFabUUnitUtils.ApiActionWrapper<GetPlayerStatisticsResult>(testContext, GetPlayerStatsCallback1), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetPlayerStatsCallback1(GetPlayerStatisticsResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
_testInteger = 0;
foreach (var eachStat in result.Statistics)
if (eachStat.StatisticName == TEST_STAT_NAME)
_testInteger = eachStat.Value;
_testInteger = (_testInteger + 1) % 100; // This test is about the Expected value changing - but not testing more complicated issues like bounds
var updateRequest = new UpdatePlayerStatisticsRequest
{
Statistics = new List<StatisticUpdate>
{
new StatisticUpdate { StatisticName = TEST_STAT_NAME, Value = _testInteger }
}
};
PlayFabClientAPI.UpdatePlayerStatistics(updateRequest, PlayFabUUnitUtils.ApiActionWrapper<UpdatePlayerStatisticsResult>(testContext, UpdatePlayerStatsCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void UpdatePlayerStatsCallback(UpdatePlayerStatisticsResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
var getRequest = new GetPlayerStatisticsRequest();
PlayFabClientAPI.GetPlayerStatistics(getRequest, PlayFabUUnitUtils.ApiActionWrapper<GetPlayerStatisticsResult>(testContext, GetPlayerStatsCallback2), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetPlayerStatsCallback2(GetPlayerStatisticsResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
var actualValue = int.MinValue; // a value that shouldn't actually occur in this test
foreach (var eachStat in result.Statistics)
if (eachStat.StatisticName == TEST_STAT_NAME)
actualValue = eachStat.Value;
testContext.IntEquals(_testInteger, actualValue);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// SERVER API
/// Get or create the given test character for the given user
/// Parameter types tested: Contained-Classes, string
/// </summary>
[UUnitTest]
public void UserCharacter(UUnitTestContext testContext)
{
var request = new ListUsersCharactersRequest
{
PlayFabId = PlayFabId // Received from client upon login
};
PlayFabClientAPI.GetAllUsersCharacters(request, PlayFabUUnitUtils.ApiActionWrapper<ListUsersCharactersResult>(testContext, GetCharsCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetCharsCallback(ListUsersCharactersResult result)
{
((UUnitTestContext)result.CustomData).EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that leaderboard results can be requested
/// Parameter types tested: List of contained-classes
/// </summary>
[UUnitTest]
public void ClientLeaderBoard(UUnitTestContext testContext)
{
var clientRequest = new GetLeaderboardRequest
{
MaxResultsCount = 3,
StatisticName = TEST_STAT_NAME,
};
PlayFabClientAPI.GetLeaderboard(clientRequest, PlayFabUUnitUtils.ApiActionWrapper<GetLeaderboardResult>(testContext, GetClientLbCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void GetClientLbCallback(GetLeaderboardResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
testContext.True(result.Leaderboard.Count > 0, "Client leaderboard should not be empty");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that AccountInfo can be requested
/// Parameter types tested: List of enum-as-strings converted to list of enums
/// </summary>
[UUnitTest]
public void AccountInfo(UUnitTestContext testContext)
{
var request = new GetAccountInfoRequest
{
PlayFabId = PlayFabId
};
PlayFabClientAPI.GetAccountInfo(request, PlayFabUUnitUtils.ApiActionWrapper<GetAccountInfoResult>(testContext, AcctInfoCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void AcctInfoCallback(GetAccountInfoResult result)
{
var enumCorrect = (result.AccountInfo != null
&& result.AccountInfo.TitleInfo != null
&& result.AccountInfo.TitleInfo.Origination != null
&& Enum.IsDefined(typeof(UserOrigination), result.AccountInfo.TitleInfo.Origination.Value));
var testContext = (UUnitTestContext)result.CustomData;
testContext.True(enumCorrect, "Enum value does not match expected options");
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that CloudScript can be properly set up and invoked
/// </summary>
[UUnitTest]
public void CloudScript(UUnitTestContext testContext)
{
var request = new ExecuteCloudScriptRequest
{
FunctionName = "helloWorld"
};
PlayFabClientAPI.ExecuteCloudScript(request, PlayFabUUnitUtils.ApiActionWrapper<ExecuteCloudScriptResult>(testContext, CloudScriptHwCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void CloudScriptHwCallback(ExecuteCloudScriptResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
testContext.NotNull(result.FunctionResult);
var jobj = (JsonObject)result.FunctionResult;
var messageValue = jobj["messageValue"] as string;
testContext.StringEquals("Hello " + PlayFabId + "!", messageValue);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that CloudScript errors can be deciphered
/// </summary>
[UUnitTest]
public void CloudScriptError(UUnitTestContext testContext)
{
var request = new ExecuteCloudScriptRequest
{
FunctionName = "throwError"
};
PlayFabClientAPI.ExecuteCloudScript(request, PlayFabUUnitUtils.ApiActionWrapper<ExecuteCloudScriptResult>(testContext, CloudScriptErrorCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void CloudScriptErrorCallback(ExecuteCloudScriptResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
testContext.IsNull(result.FunctionResult, "The result should be null because the function did not return properly.");
testContext.NotNull(result.Error, "The error should be defined because the function throws an error.");
testContext.StringEquals(result.Error.Error, "JavascriptException", result.Error.Error);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that CloudScript can be properly set up and invoked
/// </summary>
[UUnitTest]
public void CloudScriptGeneric(UUnitTestContext testContext)
{
var request = new ExecuteCloudScriptRequest
{
FunctionName = "helloWorld"
};
PlayFabClientAPI.ExecuteCloudScript<HelloWorldWrapper>(request, PlayFabUUnitUtils.ApiActionWrapper<ExecuteCloudScriptResult>(testContext, CloudScriptGenericHwCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private static void CloudScriptGenericHwCallback(ExecuteCloudScriptResult result)
{
var testContext = (UUnitTestContext)result.CustomData;
var hwResult = result.FunctionResult as HelloWorldWrapper;
testContext.NotNull(hwResult);
testContext.StringEquals("Hello " + PlayFabId + "!", hwResult.messageValue);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
private class HelloWorldWrapper
{
public string messageValue = null;
}
/// <summary>
/// CLIENT API
/// Test that the client can publish custom PlayStream events
/// </summary>
[UUnitTest]
public void WriteEvent(UUnitTestContext testContext)
{
var request = new WriteClientPlayerEventRequest
{
EventName = "ForumPostEvent",
Timestamp = DateTime.UtcNow,
Body = new Dictionary<string, object>
{
{ "Subject", "My First Post" },
{ "Body", "My awesome Post." }
}
};
PlayFabClientAPI.WritePlayerEvent(request, PlayFabUUnitUtils.ApiActionWrapper<WriteEventResponse>(testContext, WriteEventCallback), PlayFabUUnitUtils.ApiActionWrapper<PlayFabError>(testContext, SharedErrorCallback), testContext);
}
private void WriteEventCallback(WriteEventResponse result)
{
// There's nothing else useful to test about this right now
((UUnitTestContext)result.CustomData).EndTest(UUnitFinishState.PASSED, null);
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet establishes a new Runspace either on the local machine or
/// on the specified remote machine(s). The runspace established can be used
/// to invoke expressions remotely.
///
/// The cmdlet can be used in the following ways:
///
/// Open a local runspace
/// $rs = New-PSSession
///
/// Open a runspace to a remote system.
/// $rs = New-PSSession -Machine PowerShellWorld
///
/// Create a runspace specifying that it is globally scoped.
/// $global:rs = New-PSSession -Machine PowerShellWorld
///
/// Create a collection of runspaces
/// $runspaces = New-PSSession -Machine PowerShellWorld,PowerShellPublish,PowerShellRepo
///
/// Create a set of Runspaces using the Secure Socket Layer by specifying the URI form.
/// This assumes that an shell by the name of E12 exists on the remote server.
/// $serverURIs = 1..8 | ForEach-Object { "SSL://server${_}:443/E12" }
/// $rs = New-PSSession -URI $serverURIs
///
/// Create a runspace by connecting to port 8081 on servers s1, s2 and s3
/// $rs = New-PSSession -computername s1,s2,s3 -port 8081
///
/// Create a runspace by connecting to port 443 using ssl on servers s1, s2 and s3
/// $rs = New-PSSession -computername s1,s2,s3 -port 443 -useSSL
///
/// Create a runspace by connecting to port 8081 on server s1 and run shell named E12.
/// This assumes that a shell by the name E12 exists on the remote server
/// $rs = New-PSSession -computername s1 -port 8061 -ShellName E12.
/// </summary>
[Cmdlet(VerbsCommon.New, "PSSession", DefaultParameterSetName = "ComputerName",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096484", RemotingCapability = RemotingCapability.OwnedByCommand)]
[OutputType(typeof(PSSession))]
public class NewPSSessionCommand : PSRemotingBaseCmdlet, IDisposable
{
#region Parameters
/// <summary>
/// This parameter represents the address(es) of the remote
/// computer(s). The following formats are supported:
/// (a) Computer name
/// (b) IPv4 address : 132.3.4.5
/// (c) IPv6 address: 3ffe:8311:ffff:f70f:0:5efe:172.30.162.18.
/// </summary>
[Parameter(Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
[Alias("Cn")]
[ValidateNotNullOrEmpty]
public override string[] ComputerName { get; set; }
/// <summary>
/// Specifies the credentials of the user to impersonate in the
/// remote machine. If this parameter is not specified then the
/// credentials of the current user process will be assumed.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.UriParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMIdParameterSet)]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)]
[Credential()]
public override PSCredential Credential
{
get
{
return base.Credential;
}
set
{
base.Credential = value;
}
}
/// <summary>
/// The PSSession object describing the remote runspace
/// using which the specified cmdlet operation will be performed.
/// </summary>
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = true,
ParameterSetName = NewPSSessionCommand.SessionParameterSet)]
[ValidateNotNullOrEmpty]
public override PSSession[] Session
{
get
{
return _remoteRunspaceInfos;
}
set
{
_remoteRunspaceInfos = value;
}
}
private PSSession[] _remoteRunspaceInfos;
/// <summary>
/// Friendly names for the new PSSessions.
/// </summary>
[Parameter()]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name { get; set; }
/// <summary>
/// When set and in loopback scenario (localhost) this enables creation of WSMan
/// host process with the user interactive token, allowing PowerShell script network access,
/// i.e., allows going off box. When this property is true and a PSSession is disconnected,
/// reconnection is allowed only if reconnecting from a PowerShell session on the same box.
/// </summary>
[Parameter(ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ParameterSetName = NewPSSessionCommand.SessionParameterSet)]
[Parameter(ParameterSetName = NewPSSessionCommand.UriParameterSet)]
public SwitchParameter EnableNetworkAccess { get; set; }
/// <summary>
/// For WSMan sessions:
/// If this parameter is not specified then the value specified in
/// the environment variable DEFAULTREMOTESHELLNAME will be used. If
/// this is not set as well, then Microsoft.PowerShell is used.
///
/// For VM/Container sessions:
/// If this parameter is not specified then no configuration is used.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ComputerNameParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.UriParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.ContainerIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.VMIdParameterSet)]
[Parameter(ValueFromPipelineByPropertyName = true,
ParameterSetName = NewPSSessionCommand.VMNameParameterSet)]
public string ConfigurationName { get; set; }
/// <summary>
/// Gets or sets parameter value that creates connection to a Windows PowerShell process.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = NewPSSessionCommand.UseWindowsPowerShellParameterSet)]
public SwitchParameter UseWindowsPowerShell { get; set; }
#endregion Parameters
#region Cmdlet Overrides
/// <summary>
/// The throttle limit will be set here as it needs to be done
/// only once per cmdlet and not for every call.
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
_operationsComplete.Reset();
_throttleManager.ThrottleLimit = ThrottleLimit;
_throttleManager.ThrottleComplete += HandleThrottleComplete;
if (string.IsNullOrEmpty(ConfigurationName))
{
if ((ParameterSetName == NewPSSessionCommand.ComputerNameParameterSet) ||
(ParameterSetName == NewPSSessionCommand.UriParameterSet))
{
// set to default value for WSMan session
ConfigurationName = ResolveShell(null);
}
else
{
// convert null to string.Empty for VM/Container session
ConfigurationName = string.Empty;
}
}
}
/// <summary>
/// The runspace objects will be created using OpenAsync.
/// At the end, the method will check if any runspace
/// opened has already become available. If so, then it
/// will be written to the pipeline.
/// </summary>
protected override void ProcessRecord()
{
List<RemoteRunspace> remoteRunspaces = null;
List<IThrottleOperation> operations = new List<IThrottleOperation>();
switch (ParameterSetName)
{
case NewPSSessionCommand.SessionParameterSet:
{
remoteRunspaces = CreateRunspacesWhenRunspaceParameterSpecified();
}
break;
case "Uri":
{
remoteRunspaces = CreateRunspacesWhenUriParameterSpecified();
}
break;
case NewPSSessionCommand.ComputerNameParameterSet:
{
remoteRunspaces = CreateRunspacesWhenComputerNameParameterSpecified();
}
break;
case NewPSSessionCommand.VMIdParameterSet:
case NewPSSessionCommand.VMNameParameterSet:
{
remoteRunspaces = CreateRunspacesWhenVMParameterSpecified();
}
break;
case NewPSSessionCommand.ContainerIdParameterSet:
{
remoteRunspaces = CreateRunspacesWhenContainerParameterSpecified();
}
break;
case NewPSSessionCommand.SSHHostParameterSet:
{
remoteRunspaces = CreateRunspacesForSSHHostParameterSet();
}
break;
case NewPSSessionCommand.SSHHostHashParameterSet:
{
remoteRunspaces = CreateRunspacesForSSHHostHashParameterSet();
}
break;
case NewPSSessionCommand.UseWindowsPowerShellParameterSet:
{
remoteRunspaces = CreateRunspacesForUseWindowsPowerShellParameterSet();
}
break;
default:
{
Dbg.Assert(false, "Missing parameter set in switch statement");
remoteRunspaces = new List<RemoteRunspace>(); // added to avoid prefast warning
}
break;
}
foreach (RemoteRunspace remoteRunspace in remoteRunspaces)
{
remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;
OpenRunspaceOperation operation = new OpenRunspaceOperation(remoteRunspace);
// HandleRunspaceStateChanged callback is added before ThrottleManager complete
// callback handlers so HandleRunspaceStateChanged will always be called first.
operation.OperationComplete += HandleRunspaceStateChanged;
remoteRunspace.URIRedirectionReported += HandleURIDirectionReported;
operations.Add(operation);
}
// submit list of operations to throttle manager to start opening
// runspaces
_throttleManager.SubmitOperations(operations);
// Add to list for clean up.
_allOperations.Add(operations);
// If there are any runspaces opened asynchronously
// that are ready now, check their status and do
// necessary action. If there are any error records
// or verbose messages write them as well
Collection<object> streamObjects =
_stream.ObjectReader.NonBlockingRead();
foreach (object streamObject in streamObjects)
{
WriteStreamObject((Action<Cmdlet>)streamObject);
}
}
/// <summary>
/// OpenAsync would have been called from ProcessRecord. This method
/// will wait until all runspaces are opened and then write them to
/// the pipeline as and when they become available.
/// </summary>
protected override void EndProcessing()
{
// signal to throttle manager end of submit operations
_throttleManager.EndSubmitOperations();
while (true)
{
// Keep reading objects until end of pipeline is encountered
_stream.ObjectReader.WaitHandle.WaitOne();
if (!_stream.ObjectReader.EndOfPipeline)
{
object streamObject = _stream.ObjectReader.Read();
WriteStreamObject((Action<Cmdlet>)streamObject);
}
else
{
break;
}
}
}
/// <summary>
/// This method is called when the user sends a stop signal to the
/// cmdlet. The cmdlet will not exit until it has completed
/// creating all the runspaces (basically the runspaces its
/// waiting on OpenAsync is made available). However, when a stop
/// signal is sent, CloseAsyn needs to be called to close all the
/// pending runspaces.
/// </summary>
/// <remarks>This is called from a separate thread so need to worry
/// about concurrency issues
/// </remarks>
protected override void StopProcessing()
{
// close the outputStream so that further writes to the outputStream
// are not possible
_stream.ObjectWriter.Close();
// for all the runspaces that have been submitted for opening
// call StopOperation on each object and quit
_throttleManager.StopAllOperations();
}
#endregion Cmdlet Overrides
#region IDisposable Overrides
/// <summary>
/// Dispose method of IDisposable. Gets called in the following cases:
/// 1. Pipeline explicitly calls dispose on cmdlets
/// 2. Called by the garbage collector.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion IDisposable Overrides
#region Private Methods
/// <summary>
/// Adds forwarded events to the local queue.
/// </summary>
private void OnRunspacePSEventReceived(object sender, PSEventArgs e)
{
if (this.Events != null)
this.Events.AddForwardedEvent(e);
}
/// <summary>
/// When the client remote session reports a URI redirection, this method will report the
/// message to the user as a Warning using Host method calls.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs)
{
string message = StringUtil.Format(RemotingErrorIdStrings.URIRedirectWarningToHost, eventArgs.Data.OriginalString);
Action<Cmdlet> warningWriter = (Cmdlet cmdlet) => cmdlet.WriteWarning(message);
_stream.Write(warningWriter);
}
/// <summary>
/// Handles state changes for Runspace.
/// </summary>
/// <param name="sender">Sender of this event.</param>
/// <param name="stateEventArgs">Event information object which describes
/// the event which triggered this method</param>
private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs)
{
if (sender == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(sender));
}
if (stateEventArgs == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(stateEventArgs));
}
RunspaceStateEventArgs runspaceStateEventArgs =
stateEventArgs.BaseEvent as RunspaceStateEventArgs;
RunspaceStateInfo stateInfo = runspaceStateEventArgs.RunspaceStateInfo;
RunspaceState state = stateInfo.State;
OpenRunspaceOperation operation = sender as OpenRunspaceOperation;
RemoteRunspace remoteRunspace = operation.OperatedRunspace;
// since we got state changed event..we dont need to listen on
// URI redirections anymore
if (remoteRunspace != null)
{
remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported;
}
PipelineWriter writer = _stream.ObjectWriter;
Exception reason = runspaceStateEventArgs.RunspaceStateInfo.Reason;
switch (state)
{
case RunspaceState.Opened:
{
// Indicates that runspace is successfully opened
// Write it to PipelineWriter to be handled in
// HandleRemoteRunspace
PSSession remoteRunspaceInfo = new PSSession(remoteRunspace);
this.RunspaceRepository.Add(remoteRunspaceInfo);
Action<Cmdlet> outputWriter = (Cmdlet cmdlet) => cmdlet.WriteObject(remoteRunspaceInfo);
if (writer.IsOpen)
{
writer.Write(outputWriter);
}
}
break;
case RunspaceState.Broken:
{
// Open resulted in a broken state. Extract reason
// and write an error record
// set the transport message in the error detail so that
// the user can directly get to see the message without
// having to mine through the error record details
PSRemotingTransportException transException =
reason as PSRemotingTransportException;
string errorDetails = null;
int transErrorCode = 0;
if (transException != null)
{
OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation;
transErrorCode = transException.ErrorCode;
if (senderAsOp != null)
{
string host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName;
if (transException.ErrorCode ==
System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED)
{
// Handling a special case for redirection..we should talk about
// AllowRedirection parameter and WSManMaxRedirectionCount preference
// variables
string message = PSRemotingErrorInvariants.FormatResourceString(
RemotingErrorIdStrings.URIRedirectionReported,
transException.Message,
"MaximumConnectionRedirectionCount",
Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION,
"AllowRedirection");
errorDetails = "[" + host + "] " + message;
}
else
{
errorDetails = "[" + host + "] ";
if (!string.IsNullOrEmpty(transException.Message))
{
errorDetails += transException.Message;
}
else if (!string.IsNullOrEmpty(transException.TransportMessage))
{
errorDetails += transException.TransportMessage;
}
}
}
}
// add host identification information in data structure handler message
PSRemotingDataStructureException protoException = reason as PSRemotingDataStructureException;
if (protoException != null)
{
OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation;
if (senderAsOp != null)
{
string host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName;
errorDetails = "[" + host + "] " + protoException.Message;
}
}
if (reason == null)
{
reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state));
}
string fullyQualifiedErrorId = WSManTransportManagerUtils.GetFQEIDFromTransportError(
transErrorCode,
_defaultFQEID);
if (transErrorCode == WSManNativeApi.ERROR_WSMAN_NO_LOGON_SESSION_EXIST)
{
errorDetails += System.Environment.NewLine + string.Format(System.Globalization.CultureInfo.CurrentCulture, RemotingErrorIdStrings.RemotingErrorNoLogonSessionExist);
}
ErrorRecord errorRecord = new ErrorRecord(reason,
remoteRunspace, fullyQualifiedErrorId,
ErrorCategory.OpenError, null, null,
null, null, null, errorDetails, null);
Action<Cmdlet> errorWriter = (Cmdlet cmdlet) =>
{
//
// In case of PSDirectException, we should output the precise error message
// in inner exception instead of the generic one in outer exception.
//
if ((errorRecord.Exception != null) &&
(errorRecord.Exception.InnerException != null))
{
PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException;
if (ex != null)
{
errorRecord = new ErrorRecord(errorRecord.Exception.InnerException,
errorRecord.FullyQualifiedErrorId,
errorRecord.CategoryInfo.Category,
errorRecord.TargetObject);
}
}
cmdlet.WriteError(errorRecord);
};
if (writer.IsOpen)
{
writer.Write(errorWriter);
}
_toDispose.Add(remoteRunspace);
}
break;
case RunspaceState.Closed:
{
// The runspace was closed possibly because the user
// hit ctrl-C when runspaces were being opened or Dispose has been
// called when there are open runspaces
Uri connectionUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(remoteRunspace.ConnectionInfo,
"ConnectionUri", null);
string message =
GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed,
(connectionUri != null) ?
connectionUri.AbsoluteUri : string.Empty);
Action<Cmdlet> verboseWriter = (Cmdlet cmdlet) => cmdlet.WriteVerbose(message);
if (writer.IsOpen)
{
writer.Write(verboseWriter);
}
// runspace may not have been opened in certain cases
// like when the max memory is set to 25MB, in such
// cases write an error record
if (reason != null)
{
ErrorRecord errorRecord = new ErrorRecord(reason,
"PSSessionStateClosed",
ErrorCategory.OpenError, remoteRunspace);
Action<Cmdlet> errorWriter = (Cmdlet cmdlet) => cmdlet.WriteError(errorRecord);
if (writer.IsOpen)
{
writer.Write(errorWriter);
}
}
}
break;
}
}
/// <summary>
/// Creates the remote runspace objects when PSSession
/// parameter is specified
/// It now supports PSSession based on VM/container connection info as well.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
private List<RemoteRunspace> CreateRunspacesWhenRunspaceParameterSpecified()
{
List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>();
// validate the runspaces specified before processing them.
// The function will result in terminating errors, if any
// validation failure is encountered
ValidateRemoteRunspacesSpecified();
int rsIndex = 0;
foreach (PSSession remoteRunspaceInfo in _remoteRunspaceInfos)
{
if (remoteRunspaceInfo == null || remoteRunspaceInfo.Runspace == null)
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentNullException("PSSession"), "PSSessionArgumentNull",
ErrorCategory.InvalidArgument, null));
}
else
{
// clone the object based on what's specified in the input parameter
try
{
RemoteRunspace remoteRunspace = (RemoteRunspace)remoteRunspaceInfo.Runspace;
RunspaceConnectionInfo newConnectionInfo = null;
if (remoteRunspace.ConnectionInfo is VMConnectionInfo)
{
newConnectionInfo = remoteRunspace.ConnectionInfo.InternalCopy();
}
else if (remoteRunspace.ConnectionInfo is ContainerConnectionInfo)
{
ContainerConnectionInfo newContainerConnectionInfo = remoteRunspace.ConnectionInfo.InternalCopy() as ContainerConnectionInfo;
newContainerConnectionInfo.CreateContainerProcess();
newConnectionInfo = newContainerConnectionInfo;
}
else
{
// WSMan case
WSManConnectionInfo originalWSManConnectionInfo = remoteRunspace.ConnectionInfo as WSManConnectionInfo;
WSManConnectionInfo newWSManConnectionInfo = null;
if (originalWSManConnectionInfo != null)
{
newWSManConnectionInfo = originalWSManConnectionInfo.Copy();
newWSManConnectionInfo.EnableNetworkAccess = newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess;
newConnectionInfo = newWSManConnectionInfo;
}
else
{
Uri connectionUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(remoteRunspace.ConnectionInfo,
"ConnectionUri", null);
string shellUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<string>(remoteRunspace.ConnectionInfo,
"ShellUri", string.Empty);
newWSManConnectionInfo = new WSManConnectionInfo(connectionUri,
shellUri,
remoteRunspace.ConnectionInfo.Credential);
UpdateConnectionInfo(newWSManConnectionInfo);
newWSManConnectionInfo.EnableNetworkAccess = EnableNetworkAccess;
newConnectionInfo = newWSManConnectionInfo;
}
}
RemoteRunspacePoolInternal rrsPool = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal;
TypeTable typeTable = null;
if ((rrsPool != null) &&
(rrsPool.DataStructureHandler != null) &&
(rrsPool.DataStructureHandler.TransportManager != null))
{
typeTable = rrsPool.DataStructureHandler.TransportManager.Fragmentor.TypeTable;
}
// Create new remote runspace with name and Id.
int rsId;
string rsName = GetRunspaceName(rsIndex, out rsId);
RemoteRunspace newRemoteRunspace = new RemoteRunspace(
typeTable, newConnectionInfo, this.Host, this.SessionOption.ApplicationArguments,
rsName, rsId);
remoteRunspaces.Add(newRemoteRunspace);
}
catch (UriFormatException e)
{
PipelineWriter writer = _stream.ObjectWriter;
ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed",
ErrorCategory.InvalidArgument, remoteRunspaceInfo);
Action<Cmdlet> errorWriter = (Cmdlet cmdlet) => cmdlet.WriteError(errorRecord);
writer.Write(errorWriter);
}
}
++rsIndex;
}
return remoteRunspaces;
}
/// <summary>
/// Creates the remote runspace objects when the URI parameter
/// is specified.
/// </summary>
private List<RemoteRunspace> CreateRunspacesWhenUriParameterSpecified()
{
List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>();
// parse the Uri to obtain information about the runspace
// required
for (int i = 0; i < ConnectionUri.Length; i++)
{
try
{
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ConnectionUri = ConnectionUri[i];
connectionInfo.ShellUri = ConfigurationName;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfo.EnableNetworkAccess = EnableNetworkAccess;
// Create new remote runspace with name and Id.
int rsId;
string rsName = GetRunspaceName(i, out rsId);
RemoteRunspace remoteRunspace = new RemoteRunspace(
Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host,
this.SessionOption.ApplicationArguments, rsName, rsId);
Dbg.Assert(remoteRunspace != null,
"RemoteRunspace object created using URI is null");
remoteRunspaces.Add(remoteRunspace);
}
catch (UriFormatException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
}
catch (InvalidOperationException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
}
catch (ArgumentException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
}
catch (NotSupportedException e)
{
WriteErrorCreateRemoteRunspaceFailed(e, ConnectionUri[i]);
}
}
return remoteRunspaces;
}
/// <summary>
/// Creates the remote runspace objects when the ComputerName parameter
/// is specified.
/// </summary>
private List<RemoteRunspace> CreateRunspacesWhenComputerNameParameterSpecified()
{
List<RemoteRunspace> remoteRunspaces =
new List<RemoteRunspace>();
// Resolve all the machine names
string[] resolvedComputerNames;
ResolveComputerNames(ComputerName, out resolvedComputerNames);
ValidateComputerName(resolvedComputerNames);
// Do for each machine
for (int i = 0; i < resolvedComputerNames.Length; i++)
{
try
{
WSManConnectionInfo connectionInfo = null;
connectionInfo = new WSManConnectionInfo();
string scheme = UseSSL.IsPresent ? WSManConnectionInfo.HttpsScheme : WSManConnectionInfo.HttpScheme;
connectionInfo.ComputerName = resolvedComputerNames[i];
connectionInfo.Port = Port;
connectionInfo.AppName = ApplicationName;
connectionInfo.ShellUri = ConfigurationName;
connectionInfo.Scheme = scheme;
if (CertificateThumbprint != null)
{
connectionInfo.CertificateThumbprint = CertificateThumbprint;
}
else
{
connectionInfo.Credential = Credential;
}
connectionInfo.AuthenticationMechanism = Authentication;
UpdateConnectionInfo(connectionInfo);
connectionInfo.EnableNetworkAccess = EnableNetworkAccess;
// Create new remote runspace with name and Id.
int rsId;
string rsName = GetRunspaceName(i, out rsId);
RemoteRunspace runspace = new RemoteRunspace(
Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host,
this.SessionOption.ApplicationArguments, rsName, rsId);
remoteRunspaces.Add(runspace);
}
catch (UriFormatException e)
{
PipelineWriter writer = _stream.ObjectWriter;
ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed",
ErrorCategory.InvalidArgument, resolvedComputerNames[i]);
Action<Cmdlet> errorWriter = (Cmdlet cmdlet) => cmdlet.WriteError(errorRecord);
writer.Write(errorWriter);
}
}
return remoteRunspaces;
}
/// <summary>
/// Creates the remote runspace objects when the VMId or VMName parameter
/// is specified.
/// </summary>
private List<RemoteRunspace> CreateRunspacesWhenVMParameterSpecified()
{
int inputArraySize;
bool isVMIdSet = false;
int index;
string command;
Collection<PSObject> results;
List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>();
if (ParameterSetName == PSExecutionCmdlet.VMIdParameterSet)
{
isVMIdSet = true;
inputArraySize = this.VMId.Length;
this.VMName = new string[inputArraySize];
command = "Get-VM -Id $args[0]";
}
else
{
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.VMNameParameterSet),
"Expected ParameterSetName == VMId or VMName");
inputArraySize = this.VMName.Length;
this.VMId = new Guid[inputArraySize];
command = "Get-VM -Name $args";
}
for (index = 0; index < inputArraySize; index++)
{
try
{
results = this.InvokeCommand.InvokeScript(
command, false, PipelineResultTypes.None, null,
isVMIdSet ? this.VMId[index].ToString() : this.VMName[index]);
}
catch (CommandNotFoundException)
{
ThrowTerminatingError(
new ErrorRecord(
new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable),
nameof(PSRemotingErrorId.HyperVModuleNotAvailable),
ErrorCategory.NotInstalled,
null));
return null;
}
// handle invalid input
if (results.Count != 1)
{
if (isVMIdSet)
{
this.VMName[index] = string.Empty;
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle,
this.VMId[index].ToString(null))),
nameof(PSRemotingErrorId.InvalidVMIdNotSingle),
ErrorCategory.InvalidArgument,
null));
continue;
}
else
{
this.VMId[index] = Guid.Empty;
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle,
this.VMName[index])),
nameof(PSRemotingErrorId.InvalidVMNameNotSingle),
ErrorCategory.InvalidArgument,
null));
continue;
}
}
else
{
this.VMId[index] = (Guid)results[0].Properties["VMId"].Value;
this.VMName[index] = (string)results[0].Properties["VMName"].Value;
//
// VM should be in running state.
//
if ((VMState)results[0].Properties["State"].Value != VMState.Running)
{
WriteError(
new ErrorRecord(
new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState,
this.VMName[index])),
nameof(PSRemotingErrorId.InvalidVMState),
ErrorCategory.InvalidArgument,
null));
continue;
}
}
// create helper objects for VM GUIDs or names
RemoteRunspace runspace = null;
VMConnectionInfo connectionInfo;
int rsId;
string rsName = GetRunspaceName(index, out rsId);
try
{
connectionInfo = new VMConnectionInfo(this.Credential, this.VMId[index], this.VMName[index], this.ConfigurationName);
runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(),
connectionInfo, this.Host, null, rsName, rsId);
remoteRunspaces.Add(runspace);
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForVMFailed",
ErrorCategory.InvalidArgument,
null);
WriteError(errorRecord);
}
}
ResolvedComputerNames = this.VMName;
return remoteRunspaces;
}
/// <summary>
/// Creates the remote runspace objects when the ContainerId parameter is specified.
/// </summary>
private List<RemoteRunspace> CreateRunspacesWhenContainerParameterSpecified()
{
int index = 0;
List<string> resolvedNameList = new List<string>();
List<RemoteRunspace> remoteRunspaces = new List<RemoteRunspace>();
Dbg.Assert((ParameterSetName == PSExecutionCmdlet.ContainerIdParameterSet),
"Expected ParameterSetName == ContainerId");
foreach (var input in ContainerId)
{
//
// Create helper objects for container ID or name.
//
RemoteRunspace runspace = null;
ContainerConnectionInfo connectionInfo = null;
int rsId;
string rsName = GetRunspaceName(index, out rsId);
index++;
try
{
//
// Hyper-V container uses Hype-V socket as transport.
// Windows Server container uses named pipe as transport.
//
connectionInfo = ContainerConnectionInfo.CreateContainerConnectionInfo(input, RunAsAdministrator.IsPresent, this.ConfigurationName);
resolvedNameList.Add(connectionInfo.ComputerName);
connectionInfo.CreateContainerProcess();
runspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(),
connectionInfo, this.Host, null, rsName, rsId);
remoteRunspaces.Add(runspace);
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
continue;
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidArgument,
null);
WriteError(errorRecord);
continue;
}
catch (Exception e)
{
ErrorRecord errorRecord = new ErrorRecord(e,
"CreateRemoteRunspaceForContainerFailed",
ErrorCategory.InvalidOperation,
null);
WriteError(errorRecord);
continue;
}
}
ResolvedComputerNames = resolvedNameList.ToArray();
return remoteRunspaces;
}
/// <summary>
/// CreateRunspacesForSSHHostParameterSet.
/// </summary>
/// <returns></returns>
private List<RemoteRunspace> CreateRunspacesForSSHHostParameterSet()
{
// Resolve all the machine names
string[] resolvedComputerNames;
ResolveComputerNames(HostName, out resolvedComputerNames);
var remoteRunspaces = new List<RemoteRunspace>();
int index = 0;
foreach (var computerName in resolvedComputerNames)
{
ParseSshHostName(computerName, out string host, out string userName, out int port);
var sshConnectionInfo = new SSHConnectionInfo(
userName,
host,
this.KeyFilePath,
port,
Subsystem,
ConnectingTimeout);
var typeTable = TypeTable.LoadDefaultTypeFiles();
string rsName = GetRunspaceName(index, out int rsIdUnused);
index++;
remoteRunspaces.Add(RunspaceFactory.CreateRunspace(connectionInfo: sshConnectionInfo,
host: this.Host,
typeTable: typeTable,
applicationArguments: null,
name: rsName) as RemoteRunspace);
}
return remoteRunspaces;
}
private List<RemoteRunspace> CreateRunspacesForSSHHostHashParameterSet()
{
var sshConnections = ParseSSHConnectionHashTable();
var remoteRunspaces = new List<RemoteRunspace>();
int index = 0;
foreach (var sshConnection in sshConnections)
{
var sshConnectionInfo = new SSHConnectionInfo(
sshConnection.UserName,
sshConnection.ComputerName,
sshConnection.KeyFilePath,
sshConnection.Port,
sshConnection.Subsystem,
sshConnection.ConnectingTimeout);
var typeTable = TypeTable.LoadDefaultTypeFiles();
string rsName = GetRunspaceName(index, out int rsIdUnused);
index++;
remoteRunspaces.Add(RunspaceFactory.CreateRunspace(connectionInfo: sshConnectionInfo,
host: this.Host,
typeTable: typeTable,
applicationArguments: null,
name: rsName) as RemoteRunspace);
}
return remoteRunspaces;
}
/// <summary>
/// Helper method to create remote runspace based on UseWindowsPowerShell parameter set.
/// </summary>
/// <returns>Remote runspace that was created.</returns>
private List<RemoteRunspace> CreateRunspacesForUseWindowsPowerShellParameterSet()
{
var remoteRunspaces = new List<RemoteRunspace>();
NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential);
connectionInfo.AuthenticationMechanism = this.Authentication;
#if !UNIX
connectionInfo.PSVersion = new Version(5, 1);
#endif
var typeTable = TypeTable.LoadDefaultTypeFiles();
string runspaceName = GetRunspaceName(0, out int runspaceIdUnused);
remoteRunspaces.Add(RunspaceFactory.CreateRunspace(connectionInfo: connectionInfo,
host: this.Host,
typeTable: typeTable,
applicationArguments: null,
name: runspaceName) as RemoteRunspace);
return remoteRunspaces;
}
/// <summary>
/// Helper method to either get a user supplied runspace/session name
/// or to generate one along with a unique Id.
/// </summary>
/// <param name="rsIndex">Runspace name array index.</param>
/// <param name="rsId">Runspace Id.</param>
/// <returns>Runspace name.</returns>
private string GetRunspaceName(int rsIndex, out int rsId)
{
// Get a unique session/runspace Id and default Name.
string rsName = PSSession.GenerateRunspaceName(out rsId);
// If there is a friendly name for the runspace, we need to pass it to the
// runspace pool object, which in turn passes it on to the server during
// construction. This way the friendly name can be returned when querying
// the sever for disconnected sessions/runspaces.
if (Name != null && rsIndex < Name.Length)
{
rsName = Name[rsIndex];
}
return rsName;
}
/// <summary>
/// Internal dispose method which does the actual
/// dispose operations and finalize suppressions.
/// </summary>
/// <param name="disposing">Whether method is called
/// from Dispose or destructor</param>
protected void Dispose(bool disposing)
{
if (disposing)
{
_throttleManager.Dispose();
// wait for all runspace operations to be complete
_operationsComplete.WaitOne();
_operationsComplete.Dispose();
_throttleManager.ThrottleComplete -= HandleThrottleComplete;
_throttleManager = null;
foreach (RemoteRunspace remoteRunspace in _toDispose)
{
remoteRunspace.Dispose();
}
// Dispose all open operation objects, to remove runspace event callback.
foreach (List<IThrottleOperation> operationList in _allOperations)
{
foreach (OpenRunspaceOperation operation in operationList)
{
operation.Dispose();
}
}
_stream.Dispose();
}
}
/// <summary>
/// Handles the throttling complete event of the throttle manager.
/// </summary>
/// <param name="sender">Sender of this event.</param>
/// <param name="eventArgs"></param>
private void HandleThrottleComplete(object sender, EventArgs eventArgs)
{
// all operations are complete close the stream
_stream.ObjectWriter.Close();
_operationsComplete.Set();
}
/// <summary>
/// Writes an error record specifying that creation of remote runspace
/// failed.
/// </summary>
/// <param name="e">exception which is causing this error record
/// to be written</param>
/// <param name="uri">Uri which caused this exception.</param>
private void WriteErrorCreateRemoteRunspaceFailed(Exception e, Uri uri)
{
Dbg.Assert(e is UriFormatException || e is InvalidOperationException ||
e is ArgumentException || e is NotSupportedException,
"Exception has to be of type UriFormatException or InvalidOperationException or ArgumentException or NotSupportedException");
PipelineWriter writer = _stream.ObjectWriter;
ErrorRecord errorRecord = new ErrorRecord(e, "CreateRemoteRunspaceFailed",
ErrorCategory.InvalidArgument, uri);
Action<Cmdlet> errorWriter = (Cmdlet cmdlet) => cmdlet.WriteError(errorRecord);
writer.Write(errorWriter);
}
#endregion Private Methods
#region Private Members
private ThrottleManager _throttleManager = new ThrottleManager();
private readonly ObjectStream _stream = new ObjectStream();
// event that signals that all operations are
// complete (including closing if any)
private readonly ManualResetEvent _operationsComplete = new ManualResetEvent(true);
// the initial state is true because when no
// operations actually take place as in case of a
// parameter binding exception, then Dispose is
// called. Since Dispose waits on this handler
// it is set to true initially and is Reset() in
// BeginProcessing()
// list of runspaces to dispose
private readonly List<RemoteRunspace> _toDispose = new List<RemoteRunspace>();
// List of runspace connect operations. Need to keep for cleanup.
private readonly Collection<List<IThrottleOperation>> _allOperations = new Collection<List<IThrottleOperation>>();
// Default FQEID.
private readonly string _defaultFQEID = "PSSessionOpenFailed";
#endregion Private Members
}
#region Helper Classes
/// <summary>
/// Class that implements the IThrottleOperation in turn wrapping the
/// opening of a runspace asynchronously within it.
/// </summary>
internal class OpenRunspaceOperation : IThrottleOperation, IDisposable
{
// Member variables to ensure that the ThrottleManager gets StartComplete
// or StopComplete called only once per Start or Stop operation.
private bool _startComplete;
private bool _stopComplete;
private readonly object _syncObject = new object();
internal RemoteRunspace OperatedRunspace { get; }
internal OpenRunspaceOperation(RemoteRunspace runspace)
{
_startComplete = true;
_stopComplete = true;
OperatedRunspace = runspace;
OperatedRunspace.StateChanged += HandleRunspaceStateChanged;
}
/// <summary>
/// Opens the runspace asynchronously.
/// </summary>
internal override void StartOperation()
{
lock (_syncObject)
{
_startComplete = false;
}
OperatedRunspace.OpenAsync();
}
/// <summary>
/// Closes the runspace already opened asynchronously.
/// </summary>
internal override void StopOperation()
{
OperationStateEventArgs operationStateEventArgs = null;
lock (_syncObject)
{
// Ignore stop operation if start operation has completed.
if (_startComplete)
{
_stopComplete = true;
_startComplete = true;
operationStateEventArgs = new OperationStateEventArgs();
operationStateEventArgs.BaseEvent = new RunspaceStateEventArgs(OperatedRunspace.RunspaceStateInfo);
operationStateEventArgs.OperationState = OperationState.StopComplete;
}
else
{
_stopComplete = false;
}
}
if (operationStateEventArgs != null)
{
FireEvent(operationStateEventArgs);
}
else
{
OperatedRunspace.CloseAsync();
}
}
// OperationComplete event handler uses an internal collection of event handler
// callbacks for two reasons:
// a) To ensure callbacks are made in list order (first added, first called).
// b) To ensure all callbacks are fired by manually invoking callbacks and handling
// any exceptions thrown on this thread. (ThrottleManager will not respond if it doesn't
// get a start/stop complete callback).
private readonly List<EventHandler<OperationStateEventArgs>> _internalCallbacks = new List<EventHandler<OperationStateEventArgs>>();
internal override event EventHandler<OperationStateEventArgs> OperationComplete
{
add
{
lock (_internalCallbacks)
{
_internalCallbacks.Add(value);
}
}
remove
{
lock (_internalCallbacks)
{
_internalCallbacks.Remove(value);
}
}
}
/// <summary>
/// Handler for handling runspace state changed events. This method will be
/// registered in the StartOperation and StopOperation methods. This handler
/// will in turn invoke the OperationComplete event for all events that are
/// necessary - Opened, Closed, Disconnected, Broken. It will ignore all other state
/// changes.
/// </summary>
/// <remarks>
/// There are two problems that need to be handled.
/// 1) We need to make sure that the ThrottleManager StartComplete and StopComplete
/// operation events are called or the ThrottleManager will never end (will stop reponding).
/// 2) The HandleRunspaceStateChanged event handler remains in the Runspace
/// StateChanged event call chain until this object is disposed. We have to
/// disallow the HandleRunspaceStateChanged event from running and throwing
/// an exception since this prevents other event handlers in the chain from
/// being called.
/// </remarks>
/// <param name="source">Source of this event.</param>
/// <param name="stateEventArgs">object describing state information of the
/// runspace</param>
private void HandleRunspaceStateChanged(object source, RunspaceStateEventArgs stateEventArgs)
{
// Disregard intermediate states.
switch (stateEventArgs.RunspaceStateInfo.State)
{
case RunspaceState.Opening:
case RunspaceState.BeforeOpen:
case RunspaceState.Closing:
return;
}
OperationStateEventArgs operationStateEventArgs = null;
lock (_syncObject)
{
// We must call OperationComplete ony *once* for each Start/Stop operation.
if (!_stopComplete)
{
// Note that the StopComplete callback removes *both* the Start and Stop
// operations from their respective queues. So update the member vars
// accordingly.
_stopComplete = true;
_startComplete = true;
operationStateEventArgs = new OperationStateEventArgs();
operationStateEventArgs.BaseEvent = stateEventArgs;
operationStateEventArgs.OperationState = OperationState.StopComplete;
}
else if (!_startComplete)
{
_startComplete = true;
operationStateEventArgs = new OperationStateEventArgs();
operationStateEventArgs.BaseEvent = stateEventArgs;
operationStateEventArgs.OperationState = OperationState.StartComplete;
}
}
if (operationStateEventArgs != null)
{
// Fire callbacks in list order.
FireEvent(operationStateEventArgs);
}
}
private void FireEvent(OperationStateEventArgs operationStateEventArgs)
{
EventHandler<OperationStateEventArgs>[] copyCallbacks;
lock (_internalCallbacks)
{
copyCallbacks = new EventHandler<OperationStateEventArgs>[_internalCallbacks.Count];
_internalCallbacks.CopyTo(copyCallbacks);
}
foreach (var callbackDelegate in copyCallbacks)
{
// Ensure all callbacks get called to prevent ThrottleManager from not responding.
try
{
callbackDelegate.SafeInvoke(this, operationStateEventArgs);
}
catch (Exception)
{
}
}
}
/// <summary>
/// Implements IDisposable.
/// </summary>
public void Dispose()
{
// Must remove the event callback from the new runspace or it will block other event
// handling by throwing an exception on the event thread.
OperatedRunspace.StateChanged -= HandleRunspaceStateChanged;
GC.SuppressFinalize(this);
}
}
#endregion Helper Classes
}
| |
using System;
using System.Collections.Generic;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.Mount;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
public class RunnableProjectTemplate : ITemplate, IShortNameList, ITemplateWithTimestamp
{
private readonly JObject _raw;
public RunnableProjectTemplate(JObject raw, IGenerator generator, IFile configFile, IRunnableProjectConfig config, IFile localeConfigFile, IFile hostConfigFile)
{
config.SourceFile = configFile;
ConfigFile = configFile;
Generator = generator;
Source = configFile.MountPoint;
Config = config;
DefaultName = config.DefaultName;
Name = config.Name;
Identity = config.Identity ?? config.Name;
ShortNameList = config.ShortNameList ?? new List<string>();
Author = config.Author;
Tags = config.Tags ?? new Dictionary<string, ICacheTag>(StringComparer.OrdinalIgnoreCase);
CacheParameters = config.CacheParameters ?? new Dictionary<string, ICacheParameter>(StringComparer.OrdinalIgnoreCase);
Description = config.Description;
Classifications = config.Classifications;
GroupIdentity = config.GroupIdentity;
Precedence = config.Precedence;
LocaleConfigFile = localeConfigFile;
IsNameAgreementWithFolderPreferred = raw.ToBool("preferNameDirectory", false);
HostConfigMountPointId = hostConfigFile?.MountPoint?.Info?.MountPointId ?? Guid.Empty;
HostConfigPlace = hostConfigFile?.FullPath;
ThirdPartyNotices = raw.ToString("thirdPartyNotices");
_raw = raw;
BaselineInfo = config.BaselineInfo;
HasScriptRunningPostActions = config.HasScriptRunningPostActions;
if (config is ITemplateWithTimestamp withTimestamp)
{
ConfigTimestampUtc = withTimestamp.ConfigTimestampUtc;
}
}
public IDirectory TemplateSourceRoot
{
get
{
return ConfigFile?.Parent?.Parent;
}
}
public string Identity { get; }
public Guid GeneratorId => Generator.Id;
public string Author { get; }
public string Description { get; }
public IReadOnlyList<string> Classifications { get; }
public IRunnableProjectConfig Config { get; private set; }
public string DefaultName { get; }
public IGenerator Generator { get; }
public string GroupIdentity { get; }
public int Precedence { get; set; }
public string Name { get; }
public string ShortName
{
get
{
if (ShortNameList.Count > 0)
{
return ShortNameList[0];
}
return string.Empty;
}
set
{
if (ShortNameList.Count > 0)
{
throw new Exception("Can't set the short name when the ShortNameList already has entries.");
}
ShortNameList = new List<string>() { value };
}
}
public IReadOnlyList<string> ShortNameList { get; private set; }
public IMountPoint Source { get; }
public IReadOnlyDictionary<string, ICacheTag> Tags
{
get
{
return _tags;
}
set
{
_tags = value;
_parameters = null;
}
}
private IReadOnlyDictionary<string, ICacheTag> _tags;
public IReadOnlyDictionary<string, ICacheParameter> CacheParameters
{
get
{
return _cacheParameters;
}
set
{
_cacheParameters = value;
_parameters = null;
}
}
private IReadOnlyDictionary<string, ICacheParameter> _cacheParameters;
public IReadOnlyList<ITemplateParameter> Parameters
{
get
{
if (_parameters == null)
{
List<ITemplateParameter> parameters = new List<ITemplateParameter>();
foreach (KeyValuePair<string, ICacheTag> tagInfo in Tags)
{
ITemplateParameter param = new Parameter
{
Name = tagInfo.Key,
Documentation = tagInfo.Value.Description,
DefaultValue = tagInfo.Value.DefaultValue,
Choices = tagInfo.Value.ChoicesAndDescriptions,
DataType = "choice"
};
if (param is IAllowDefaultIfOptionWithoutValue paramWithNoValueDefault
&& tagInfo.Value is IAllowDefaultIfOptionWithoutValue tagValueWithNoValueDefault)
{
paramWithNoValueDefault.DefaultIfOptionWithoutValue = tagValueWithNoValueDefault.DefaultIfOptionWithoutValue;
parameters.Add(paramWithNoValueDefault as Parameter);
}
else
{
parameters.Add(param);
}
}
foreach (KeyValuePair<string, ICacheParameter> paramInfo in CacheParameters)
{
ITemplateParameter param = new Parameter
{
Name = paramInfo.Key,
Documentation = paramInfo.Value.Description,
DataType = paramInfo.Value.DataType,
DefaultValue = paramInfo.Value.DefaultValue,
};
if (param is IAllowDefaultIfOptionWithoutValue paramWithNoValueDefault
&& paramInfo.Value is IAllowDefaultIfOptionWithoutValue infoWithNoValueDefault)
{
paramWithNoValueDefault.DefaultIfOptionWithoutValue = infoWithNoValueDefault.DefaultIfOptionWithoutValue;
parameters.Add(paramWithNoValueDefault as Parameter);
}
else
{
parameters.Add(param);
}
}
_parameters = parameters;
}
return _parameters;
}
}
private IReadOnlyList<ITemplateParameter> _parameters;
public IFile ConfigFile { get; }
public IFileSystemInfo Configuration => ConfigFile;
public Guid ConfigMountPointId => Configuration.MountPoint.Info.MountPointId;
public string ConfigPlace => Configuration.FullPath;
public IFile LocaleConfigFile { get; }
public IFileSystemInfo LocaleConfiguration => LocaleConfigFile;
public Guid LocaleConfigMountPointId => LocaleConfiguration.MountPoint.Info.MountPointId;
public string LocaleConfigPlace => LocaleConfiguration.FullPath;
public bool IsNameAgreementWithFolderPreferred { get; }
public Guid HostConfigMountPointId { get; }
public string HostConfigPlace { get; }
public string ThirdPartyNotices { get; }
public IReadOnlyDictionary<string, IBaselineInfo> BaselineInfo { get; set; }
public bool HasScriptRunningPostActions { get; set; }
public DateTime? ConfigTimestampUtc { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System
{
public sealed partial class TimeZoneInfo
{
[Serializable]
public sealed class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback
{
private readonly DateTime _dateStart;
private readonly DateTime _dateEnd;
private readonly TimeSpan _daylightDelta;
private readonly TransitionTime _daylightTransitionStart;
private readonly TransitionTime _daylightTransitionEnd;
private readonly TimeSpan _baseUtcOffsetDelta; // delta from the default Utc offset (utcOffset = defaultUtcOffset + _baseUtcOffsetDelta)
private readonly bool _noDaylightTransitions;
public DateTime DateStart => _dateStart;
public DateTime DateEnd => _dateEnd;
public TimeSpan DaylightDelta => _daylightDelta;
public TransitionTime DaylightTransitionStart => _daylightTransitionStart;
public TransitionTime DaylightTransitionEnd => _daylightTransitionEnd;
internal TimeSpan BaseUtcOffsetDelta => _baseUtcOffsetDelta;
/// <summary>
/// Gets a value indicating that this AdjustmentRule fixes the time zone offset
/// from DateStart to DateEnd without any daylight transitions in between.
/// </summary>
internal bool NoDaylightTransitions => _noDaylightTransitions;
internal bool HasDaylightSaving =>
DaylightDelta != TimeSpan.Zero ||
(DaylightTransitionStart != default(TransitionTime) && DaylightTransitionStart.TimeOfDay != DateTime.MinValue) ||
(DaylightTransitionEnd != default(TransitionTime) && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1));
public bool Equals(AdjustmentRule other) =>
other != null &&
_dateStart == other._dateStart &&
_dateEnd == other._dateEnd &&
_daylightDelta == other._daylightDelta &&
_baseUtcOffsetDelta == other._baseUtcOffsetDelta &&
_daylightTransitionEnd.Equals(other._daylightTransitionEnd) &&
_daylightTransitionStart.Equals(other._daylightTransitionStart);
public override int GetHashCode() => _dateStart.GetHashCode();
private AdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
TimeSpan baseUtcOffsetDelta,
bool noDaylightTransitions)
{
ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta,
daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
_dateStart = dateStart;
_dateEnd = dateEnd;
_daylightDelta = daylightDelta;
_daylightTransitionStart = daylightTransitionStart;
_daylightTransitionEnd = daylightTransitionEnd;
_baseUtcOffsetDelta = baseUtcOffsetDelta;
_noDaylightTransitions = noDaylightTransitions;
}
public static AdjustmentRule CreateAdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd)
{
return new AdjustmentRule(
dateStart,
dateEnd,
daylightDelta,
daylightTransitionStart,
daylightTransitionEnd,
baseUtcOffsetDelta: TimeSpan.Zero,
noDaylightTransitions: false);
}
internal static AdjustmentRule CreateAdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
TimeSpan baseUtcOffsetDelta,
bool noDaylightTransitions)
{
return new AdjustmentRule(
dateStart,
dateEnd,
daylightDelta,
daylightTransitionStart,
daylightTransitionEnd,
baseUtcOffsetDelta,
noDaylightTransitions);
}
//
// When Windows sets the daylight transition start Jan 1st at 12:00 AM, it means the year starts with the daylight saving on.
// We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
//
internal bool IsStartDateMarkerForBeginningOfYear() =>
!NoDaylightTransitions &&
DaylightTransitionStart.Month == 1 && DaylightTransitionStart.Day == 1 && DaylightTransitionStart.TimeOfDay.Hour == 0 &&
DaylightTransitionStart.TimeOfDay.Minute == 0 && DaylightTransitionStart.TimeOfDay.Second == 0 &&
_dateStart.Year == _dateEnd.Year;
//
// When Windows sets the daylight transition end Jan 1st at 12:00 AM, it means the year ends with the daylight saving on.
// We have to special case this value and not adjust it when checking if any date is in the daylight saving period.
//
internal bool IsEndDateMarkerForEndOfYear() =>
!NoDaylightTransitions &&
DaylightTransitionEnd.Month == 1 && DaylightTransitionEnd.Day == 1 && DaylightTransitionEnd.TimeOfDay.Hour == 0 &&
DaylightTransitionEnd.TimeOfDay.Minute == 0 && DaylightTransitionEnd.TimeOfDay.Second == 0 &&
_dateStart.Year == _dateEnd.Year;
/// <summary>
/// Helper function that performs all of the validation checks for the factory methods and deserialization callback.
/// </summary>
private static void ValidateAdjustmentRule(
DateTime dateStart,
DateTime dateEnd,
TimeSpan daylightDelta,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
bool noDaylightTransitions)
{
if (dateStart.Kind != DateTimeKind.Unspecified && dateStart.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, nameof(dateStart));
}
if (dateEnd.Kind != DateTimeKind.Unspecified && dateEnd.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, nameof(dateEnd));
}
if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions)
{
throw new ArgumentException(SR.Argument_TransitionTimesAreIdentical, nameof(daylightTransitionEnd));
}
if (dateStart > dateEnd)
{
throw new ArgumentException(SR.Argument_OutOfOrderDateTimes, nameof(dateStart));
}
// This cannot use UtcOffsetOutOfRange to account for the scenario where Samoa moved across the International Date Line,
// which caused their current BaseUtcOffset to be +13. But on the other side of the line it was UTC-11 (+1 for daylight).
// So when trying to describe DaylightDeltas for those times, the DaylightDelta needs
// to be -23 (what it takes to go from UTC+13 to UTC-10)
if (daylightDelta.TotalHours < -23.0 || daylightDelta.TotalHours > 14.0)
{
throw new ArgumentOutOfRangeException(nameof(daylightDelta), daylightDelta, SR.ArgumentOutOfRange_UtcOffset);
}
if (daylightDelta.Ticks % TimeSpan.TicksPerMinute != 0)
{
throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(daylightDelta));
}
if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero)
{
throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateStart));
}
if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero)
{
throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateEnd));
}
Contract.EndContractBlock();
}
void IDeserializationCallback.OnDeserialization(object sender)
{
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs AdjustmentRule validation after being deserialized.
try
{
ValidateAdjustmentRule(_dateStart, _dateEnd, _daylightDelta,
_daylightTransitionStart, _daylightTransitionEnd, _noDaylightTransitions);
}
catch (ArgumentException e)
{
throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
info.AddValue("DateStart", _dateStart); // Do not rename (binary serialization)
info.AddValue("DateEnd", _dateEnd); // Do not rename (binary serialization)
info.AddValue("DaylightDelta", _daylightDelta); // Do not rename (binary serialization)
info.AddValue("DaylightTransitionStart", _daylightTransitionStart); // Do not rename (binary serialization)
info.AddValue("DaylightTransitionEnd", _daylightTransitionEnd); // Do not rename (binary serialization)
info.AddValue("BaseUtcOffsetDelta", _baseUtcOffsetDelta); // Do not rename (binary serialization)
info.AddValue("NoDaylightTransitions", _noDaylightTransitions); // Do not rename (binary serialization)
}
private AdjustmentRule(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
_dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime)); // Do not rename (binary serialization)
_dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime)); // Do not rename (binary serialization)
_daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan)); // Do not rename (binary serialization)
_daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime)); // Do not rename (binary serialization)
_daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime)); // Do not rename (binary serialization)
object o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan)); // Do not rename (binary serialization)
if (o != null)
{
_baseUtcOffsetDelta = (TimeSpan)o;
}
o = info.GetValueNoThrow("NoDaylightTransitions", typeof(bool)); // Do not rename (binary serialization)
if (o != null)
{
_noDaylightTransitions = (bool)o;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Querying;
namespace Umbraco.Cms.Core.Services
{
/// <summary>
/// Defines the Media Service, which is an easy access to operations involving <see cref="IMedia"/>
/// </summary>
public interface IMediaService : IContentServiceBase<IMedia>
{
int CountNotTrashed(string contentTypeAlias = null);
int Count(string mediaTypeAlias = null);
int CountChildren(int parentId, string mediaTypeAlias = null);
int CountDescendants(int parentId, string mediaTypeAlias = null);
IEnumerable<IMedia> GetByIds(IEnumerable<int> ids);
IEnumerable<IMedia> GetByIds(IEnumerable<Guid> ids);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMedia(string name, Guid parentId, string mediaTypeAlias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Gets an <see cref="IMedia"/> object by Id
/// </summary>
/// <param name="id">Id of the Content to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
IMedia GetById(int id);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
IQuery<IMedia> filter = null, Ordering ordering = null);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="ordering"></param>
/// <param name="filter"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
IQuery<IMedia> filter = null, Ordering ordering = null);
/// <summary>
/// Gets paged documents of a content
/// </summary>
/// <param name="contentTypeId">The page number.</param>
/// <param name="pageIndex">The page number.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="totalRecords">Total number of documents.</param>
/// <param name="filter">Search text filter.</param>
/// <param name="ordering">Ordering infos.</param>
IEnumerable<IMedia> GetPagedOfType(int contentTypeId, long pageIndex, int pageSize, out long totalRecords,
IQuery<IMedia> filter = null, Ordering ordering = null);
/// <summary>
/// Gets paged documents for specified content types
/// </summary>
/// <param name="contentTypeIds">The page number.</param>
/// <param name="pageIndex">The page number.</param>
/// <param name="pageSize">The page size.</param>
/// <param name="totalRecords">Total number of documents.</param>
/// <param name="filter">Search text filter.</param>
/// <param name="ordering">Ordering infos.</param>
IEnumerable<IMedia> GetPagedOfTypes(int[] contentTypeIds, long pageIndex, int pageSize, out long totalRecords,
IQuery<IMedia> filter = null, Ordering ordering = null);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root
/// </summary>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetRootMedia();
/// <summary>
/// Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin
/// </summary>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetPagedMediaInRecycleBin(long pageIndex, int pageSize, out long totalRecords,
IQuery<IMedia> filter = null, Ordering ordering = null);
/// <summary>
/// Moves an <see cref="IMedia"/> object to a new location
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to move</param>
/// <param name="parentId">Id of the Media's new Parent</param>
/// <param name="userId">Id of the User moving the Media</param>
/// <returns>True if moving succeeded, otherwise False</returns>
Attempt<OperationResult> Move(IMedia media, int parentId, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
Attempt<OperationResult> MoveToRecycleBin(IMedia media, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin
/// </summary>
/// <param name="userId">Optional Id of the User emptying the Recycle Bin</param>
OperationResult EmptyRecycleBin(int userId = Constants.Security.SuperUserId);
/// <summary>
/// Returns true if there is any media in the recycle bin
/// </summary>
bool RecycleBinSmells();
/// <summary>
/// Deletes all media of specified type. All children of deleted media is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional Id of the user deleting Media</param>
void DeleteMediaOfType(int mediaTypeId, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Deletes all media of the specified types. All Descendants of deleted media that is not of these types is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="mediaTypeIds">Ids of the <see cref="IMediaType"/>s</param>
/// <param name="userId">Optional Id of the user issuing the delete operation</param>
void DeleteMediaOfTypes(IEnumerable<int> mediaTypeIds, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Permanently deletes an <see cref="IMedia"/> object
/// </summary>
/// <remarks>
/// Please note that this method will completely remove the Media from the database,
/// but current not from the file system.
/// </remarks>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
Attempt<OperationResult> Delete(IMedia media, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Saves a single <see cref="IMedia"/> object
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Media</param>
Attempt<OperationResult> Save(IMedia media, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Saves a collection of <see cref="IMedia"/> objects
/// </summary>
/// <param name="medias">Collection of <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Media</param>
Attempt<OperationResult> Save(IEnumerable<IMedia> medias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Gets an <see cref="IMedia"/> object by its 'UniqueId'
/// </summary>
/// <param name="key">Guid key of the Media to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
IMedia GetById(Guid key);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Level
/// </summary>
/// <param name="level">The level to retrieve Media from</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetByLevel(int level);
/// <summary>
/// Gets a specific version of an <see cref="IMedia"/> item.
/// </summary>
/// <param name="versionId">Id of the version to retrieve</param>
/// <returns>An <see cref="IMedia"/> item</returns>
IMedia GetVersion(int versionId);
/// <summary>
/// Gets a collection of an <see cref="IMedia"/> objects versions by Id
/// </summary>
/// <param name="id"></param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetVersions(int id);
/// <summary>
/// Checks whether an <see cref="IMedia"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/></param>
/// <returns>True if the media has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersions(int id, DateTime versionDate, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Permanently deletes specific version(s) from an <see cref="IMedia"/> object.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersion(int id, int versionId, bool deletePriorVersions, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property.
/// </summary>
/// <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param>
/// <returns><see cref="IMedia"/></returns>
IMedia GetMediaByPath(string mediaPath);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetAncestors(int id);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media.
/// </summary>
/// <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetAncestors(IMedia media);
/// <summary>
/// Gets the parent of the current media as an <see cref="IMedia"/> item.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IMedia"/> object</returns>
IMedia GetParent(int id);
/// <summary>
/// Gets the parent of the current media as an <see cref="IMedia"/> item.
/// </summary>
/// <param name="media"><see cref="IMedia"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IMedia"/> object</returns>
IMedia GetParent(IMedia media);
/// <summary>
/// Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according
/// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="items"></param>
/// <param name="userId"></param>
/// <returns>True if sorting succeeded, otherwise False</returns>
bool Sort(IEnumerable<IMedia> items, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IMedia"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IMedia"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMediaWithIdentity(string name, int parentId, string mediaTypeAlias, int userId = Constants.Security.SuperUserId);
/// <summary>
/// Gets the content of a media as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
/// <returns>The content of the media.</returns>
Stream GetMediaFileContentStream(string filepath);
/// <summary>
/// Sets the content of a media.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
/// <param name="content">The content of the media.</param>
void SetMediaFileContent(string filepath, Stream content);
/// <summary>
/// Deletes a media file.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
void DeleteMediaFile(string filepath);
/// <summary>
/// Gets the size of a media.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
/// <returns>The size of the media.</returns>
long GetMediaFileSize(string filepath);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests.LegacyTests
{
public class AggregateTests
{
public class Aggregate004
{
public static int Accumulate(int e1, int e2)
{
return e1 + e2;
}
public static string Accumulate(string s1, string s2)
{
return s1 + s2;
}
private static int Aggregate001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst1 = q.Aggregate(Accumulate);
var rst2 = q.Aggregate(Accumulate);
return ((rst1 == rst2) ? 0 : 1);
}
private static int Aggregate002()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
var rst1 = q.Aggregate(Accumulate);
var rst2 = q.Aggregate(Accumulate);
return Verification.Allequal(rst1, rst2);
}
public static int Main()
{
int ret = RunTest(Aggregate001) + RunTest(Aggregate002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate01a
{
// Type: int, source is empty
public static int Accumulate(int e1, int e2)
{
return e1 + e2;
}
// overload: only func, source has no elements
public static int Test1a()
{
int[] source = { };
try
{
var actual = source.Aggregate(Accumulate);
return 1;
}
catch (InvalidOperationException)
{
return 0;
}
}
public static int Main()
{
return Test1a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate01b
{
// Type: int, source is empty
public static int Accumulate(int e1, int e2)
{
return e1 + e2;
}
// overload: only func, source has one element
public static int Test1b()
{
int[] source = { 5 };
int expected = 5;
var actual = source.Aggregate(Accumulate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate01c
{
// Type: int, source is empty
public static int Accumulate(int e1, int e2)
{
return e1 + e2;
}
// overload: only func, source has two elements
public static int Test1c()
{
int[] source = { 5, 6 };
int expected = 11;
var actual = source.Aggregate(Accumulate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate01d
{
// Type: int, source is empty
public static int Accumulate(int e1, int e2)
{
return e1 + e2;
}
// overload: only func, source has limited number of elements
public static int Test1d()
{
int[] source = { 5, 6, 0, -4 };
int expected = 7;
var actual = source.Aggregate(Accumulate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate02a
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed and func, source has no elements
public static int Test2a()
{
int[] source = { };
long seed = 2;
long expected = 2;
var actual = source.Aggregate(seed, Multiply);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate02b
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed and func, source has one element
public static int Test2b()
{
int[] source = { 5 };
long seed = 2;
long expected = 10;
var actual = source.Aggregate(seed, Multiply);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate02c
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed and func, source has two elements
public static int Test2c()
{
int[] source = { 5, 6 };
long seed = 2;
long expected = 60;
var actual = source.Aggregate(seed, Multiply);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate02d
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed and func, source has limited number of elements
public static int Test2d()
{
int[] source = { 5, 6, 2, -4 };
long seed = 2;
long expected = -480;
var actual = source.Aggregate(seed, Multiply);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate03a
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed, func and resultSelector, source has no elements
public static int Test3a()
{
int[] source = { };
long seed = 2;
double expected = 7;
Func<long, double> resultSelector = (x) => x + 5;
var actual = source.Aggregate(seed, Multiply, resultSelector);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate03b
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed, func and resultSelector, source has one element
public static int Test3b()
{
int[] source = { 5 };
long seed = 2;
long expected = 15;
Func<long, double> resultSelector = (x) => x + 5;
var actual = source.Aggregate(seed, Multiply, resultSelector);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate03c
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed, func and resultSelector, source has two elements
public static int Test3c()
{
int[] source = { 5, 6 };
long seed = 2;
long expected = 65;
Func<long, double> resultSelector = (x) => x + 5;
var actual = source.Aggregate(seed, Multiply, resultSelector);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Aggregate03d
{
// Type: int, source is empty
public static long Multiply(long e1, int e2)
{
return e1 * e2;
}
// overload: seed, func and resultSelector, source has limited number of elements
public static int Test3d()
{
int[] source = { 5, 6, 2, -4 };
long seed = 2;
long expected = -475;
Func<long, double> resultSelector = (x) => x + 5;
var actual = source.Aggregate(seed, Multiply, resultSelector);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test3d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
// 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;
namespace JitTest
{
internal enum Mood
{
good,
bad,
worse
}
internal class TestClass
{
private static String Format(TypedReference format, TypedReference _ref)
{
int length = __refvalue(format, String).Length;
char[] chars = __refvalue(format, String).ToCharArray();
String result = "";
int arg = 0;
for (int I = 0; I < length; I++)
{
if (chars[I] != '%')
result += chars[I];
else
{
I++;
if (I >= length)
throw new Exception();
bool FALSE = false;
bool TRUE = true;
TypedReference bLong = __makeref(FALSE);
if (chars[I] == 'l')
{
bLong = __makeref(TRUE);
I++;
if (I >= length)
throw new Exception();
}
if (arg++ == 1)
throw new Exception();
switch (chars[I])
{
case 'b':
if (__refvalue(bLong, bool))
throw new Exception();
if (__reftype(_ref) != typeof(bool))
throw new Exception();
if (__refvalue(_ref, bool))
result += "true";
else
result += "false";
break;
case 'd':
if (__refvalue(bLong, bool))
{
if (__reftype(_ref) != typeof(long))
throw new Exception();
result += __refvalue(_ref, long).ToString();
}
else
{
if (__reftype(_ref) != typeof(int))
throw new Exception();
result += __refvalue(_ref, int).ToString();
}
break;
case 'u':
if (__refvalue(bLong, bool))
{
if (__reftype(_ref) != typeof(UInt64))
throw new Exception();
result += __refvalue(_ref, ulong).ToString();
}
else
{
if (__reftype(_ref) != typeof(uint))
throw new Exception();
result += __refvalue(_ref, uint).ToString();
}
break;
case 'f':
if (__refvalue(bLong, bool))
{
if (__reftype(_ref) != typeof(double))
throw new Exception();
result += __refvalue(_ref, double).ToString();
}
else
{
if (__reftype(_ref) != typeof(float))
throw new Exception();
result += __refvalue(_ref, float).ToString();
}
break;
case 's':
if (__refvalue(bLong, bool))
throw new Exception();
if (__reftype(_ref) != typeof(String))
throw new Exception();
result += __refvalue(_ref, String) != null ? __refvalue(_ref, String) : "(null)";
break;
case 't':
if (__refvalue(bLong, bool))
throw new Exception();
if (__reftype(_ref) != typeof(DateTime))
throw new Exception();
result += __refvalue(_ref, DateTime).ToString();
break;
case 'p':
if (__refvalue(bLong, bool))
throw new Exception();
if (__reftype(_ref) != typeof(PlatformID))
throw new Exception();
result += __refvalue(_ref, PlatformID).ToString();
break;
case 'e':
if (__refvalue(bLong, bool))
throw new Exception();
if (__reftype(_ref) != typeof(Mood))
throw new Exception();
switch (__refvalue(_ref, Mood))
{
case Mood.good:
result += "good";
break;
case Mood.bad:
result += "bad";
break;
case Mood.worse:
result += "worse";
break;
default:
throw new Exception();
}
break;
default:
throw new Exception();
}
}
}
return result;
}
private static void Test(String format, TypedReference arg, String result)
{
String s = Format(__makeref(format), arg);
if (s != result)
{
throw new Exception();
}
}
private static void TestLocals()
{
int d = 10;
uint u = 11u;
long l = 12;
ulong ul = 13u;
float f = 14.0f;
double dbl = 15.0d;
bool b = true;
DateTime t = new DateTime(100, 10, 1);
PlatformID pid = PlatformID.Win32NT;
Mood mood = Mood.good;
Test("{%d}", __makeref(d), "{10}");
Test("{%u}", __makeref(u), "{11}");
Test("{%ld}", __makeref(l), "{12}");
Test("{%lu}", __makeref(ul), "{13}");
Test("{%f}", __makeref(f), "{14}");
Test("{%lf}", __makeref(dbl), "{15}");
Test("{%b}", __makeref(b), "{true}");
Test("{%t}", __makeref(t), "{" + t.ToString() + "}");
Test("{%p}", __makeref(pid), "{Win32NT}");
Test("{%e}", __makeref(mood), "{good}");
}
private int _m_d = 20;
private static uint s_m_u = 21u;
private long _m_l = 22;
private static ulong s_m_ul = 23u;
private float _m_f = 24.0f;
private double _m_dbl = 25.0d;
private bool _m_b = false;
private static DateTime s_m_t = new DateTime(100, 10, 1);
private PlatformID _m_pid = PlatformID.Win32NT;
private Mood _m_mood = Mood.good;
private void TestFields()
{
Test("{%d}", __makeref(_m_d), "{20}");
Test("{%u}", __makeref(s_m_u), "{21}");
Test("{%ld}", __makeref(_m_l), "{22}");
Test("{%lu}", __makeref(s_m_ul), "{23}");
Test("{%f}", __makeref(_m_f), "{24}");
Test("{%lf}", __makeref(_m_dbl), "{25}");
Test("{%b}", __makeref(_m_b), "{false}");
Test("{%t}", __makeref(s_m_t), "{" + s_m_t.ToString() + "}");
Test("{%p}", __makeref(_m_pid), "{Win32NT}");
Test("{%e}", __makeref(_m_mood), "{good}");
}
private static void DoTestArgSlots(ref int d, ref uint u, ref long l,
ref ulong ul, ref float f, ref double dbl, ref bool b,
ref DateTime t, ref PlatformID pid)
{
Test("{%d}", __makeref(d), "{20}");
Test("{%u}", __makeref(u), "{21}");
Test("{%ld}", __makeref(l), "{22}");
Test("{%lu}", __makeref(ul), "{23}");
Test("{%f}", __makeref(f), "{24}");
Test("{%lf}", __makeref(dbl), "{25}");
Test("{%b}", __makeref(b), "{false}");
Test("{%t}", __makeref(t), "{" + t.ToString() + "}");
Test("{%p}", __makeref(pid), "{2}");
}
private static void TestArgSlots()
{
int d = 20;
uint u = 21u;
long l = 22;
ulong ul = 23u;
float f = 24.0f;
double dbl = 25.0d;
bool b = false;
DateTime t = new DateTime(100, 10, 1);
PlatformID pid = PlatformID.Win32NT;
DoTestArgSlots(ref d, ref u, ref l, ref ul, ref f, ref dbl, ref b, ref t, ref pid);
}
private static void TestArrayElem()
{
int[] d = new int[] { 10 };
uint[] u = new uint[] { 11u };
long[] l = new long[] { 12 };
ulong[] ul = new ulong[] { 13u };
float[] f = new float[] { 14.0f };
double[] dbl = new double[] { 15.0d };
bool[] b = new bool[] { true };
DateTime[] t = new DateTime[200];
t[1] = new DateTime(100, 10, 1);
PlatformID[] pid = new PlatformID[] { PlatformID.Win32NT };
Mood[] mood = new Mood[] { Mood.good };
Test("{%d}", __makeref(d[0]), "{10}");
Test("{%u}", __makeref(u[0]), "{11}");
Test("{%ld}", __makeref(l[0]), "{12}");
Test("{%lu}", __makeref(ul[0]), "{13}");
Test("{%f}", __makeref(f[0]), "{14}");
Test("{%lf}", __makeref(dbl[0]), "{15}");
Test("{%b}", __makeref(b[0]), "{true}");
Test("{%t}", __makeref(t[1]), "{" + t[1].ToString() + "}");
Test("{%p}", __makeref(pid[0]), "{Win32NT}");
Test("{%e}", __makeref(mood[0]), "{good}");
}
private static int Main()
{
TestLocals();
new TestClass().TestFields();
TestArrayElem();
return 100;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors
{
public class NeighbourServicesConnector : INeighbourService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected IGridService m_GridService = null;
public NeighbourServicesConnector()
{
}
public NeighbourServicesConnector(IGridService gridServices)
{
Initialise(gridServices);
}
public virtual void Initialise(IGridService gridServices)
{
m_GridService = gridServices;
}
public virtual GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion)
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_GridService.GetRegionByPosition(thisRegion.ScopeID, (int)x, (int)y);
if ((regInfo != null) &&
// Don't remote-call this instance; that's a startup hickup
!((regInfo.ExternalHostName == thisRegion.ExternalHostName) && (regInfo.HttpPort == thisRegion.HttpPort)))
{
if (!DoHelloNeighbourCall(regInfo, thisRegion))
return null;
}
else
return null;
return regInfo;
}
public bool DoHelloNeighbourCall(GridRegion region, RegionInfo thisRegion)
{
string uri = region.ServerURI + "region/" + thisRegion.RegionID + "/";
// m_log.Debug(" >>> DoHelloNeighbourCall <<< " + uri);
WebRequest helloNeighbourRequest;
try
{
helloNeighbourRequest = WebRequest.Create(uri);
}
catch (Exception e)
{
m_log.WarnFormat(
"[NEIGHBOUR SERVICE CONNCTOR]: Unable to parse uri {0} to send HelloNeighbour from {1} to {2}. Exception {3}{4}",
uri, thisRegion.RegionName, region.RegionName, e.Message, e.StackTrace);
return false;
}
helloNeighbourRequest.Method = "POST";
helloNeighbourRequest.ContentType = "application/json";
helloNeighbourRequest.Timeout = 10000;
// Fill it in
OSDMap args = null;
try
{
args = thisRegion.PackRegionInfoData();
}
catch (Exception e)
{
m_log.WarnFormat(
"[NEIGHBOUR SERVICE CONNCTOR]: PackRegionInfoData failed for HelloNeighbour from {0} to {1}. Exception {2}{3}",
thisRegion.RegionName, region.RegionName, e.Message, e.StackTrace);
return false;
}
// Add the regionhandle of the destination region
args["destination_handle"] = OSD.FromString(region.RegionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
buffer = Util.UTF8NoBomEncoding.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat(
"[NEIGHBOUR SERVICE CONNCTOR]: Exception thrown on serialization of HelloNeighbour from {0} to {1}. Exception {2}{3}",
thisRegion.RegionName, region.RegionName, e.Message, e.StackTrace);
return false;
}
Stream os = null;
try
{ // send the Post
helloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
os = helloNeighbourRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
}
catch (Exception e)
{
m_log.WarnFormat(
"[NEIGHBOUR SERVICE CONNCTOR]: Unable to send HelloNeighbour from {0} to {1}. Exception {2}{3}",
thisRegion.RegionName, region.RegionName, e.Message, e.StackTrace);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");
try
{
using (WebResponse webResponse = helloNeighbourRequest.GetResponse())
{
if (webResponse == null)
{
m_log.DebugFormat(
"[REST COMMS]: Null reply on DoHelloNeighbourCall post from {0} to {1}",
thisRegion.RegionName, region.RegionName);
}
using (Stream s = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
}
}
}
}
catch (Exception e)
{
m_log.WarnFormat(
"[NEIGHBOUR SERVICE CONNCTOR]: Exception on reply of DoHelloNeighbourCall from {0} back to {1}. Exception {2}{3}",
region.RegionName, thisRegion.RegionName, e.Message, e.StackTrace);
return false;
}
return true;
}
}
}
| |
/*
* DataGridBoolColumn.cs - Implementation of "System.Windows.Forms.DataGridBoolColumn"
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
* Copyright (C) 2004 Free Software Foundation, Inc.
* Copyright (C) 2005 Boris Manojlovic.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
public class DataGridBoolColumn : DataGridColumnStyle
{
[TODO]
public DataGridBoolColumn()
{
throw new NotImplementedException(".ctor");
}
[TODO]
public DataGridBoolColumn(System.ComponentModel.PropertyDescriptor prop)
{
throw new NotImplementedException(".ctor");
}
[TODO]
public DataGridBoolColumn(System.ComponentModel.PropertyDescriptor prop, bool isDefault)
{
throw new NotImplementedException(".ctor");
}
[TODO]
protected internal override void Abort(int rowNum)
{
throw new NotImplementedException("Abort");
}
[TODO]
protected internal override bool Commit(System.Windows.Forms.CurrencyManager dataSource, int rowNum)
{
throw new NotImplementedException("Commit");
}
[TODO]
protected internal override void ConcedeFocus()
{
throw new NotImplementedException("ConcedeFocus");
}
[TODO]
protected internal override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, System.String instantText, bool cellIsVisible)
{
throw new NotImplementedException("Edit");
}
[TODO]
protected internal override void EnterNullValue()
{
throw new NotImplementedException("EnterNullValue");
}
[TODO]
protected internal override System.Object GetColumnValueAtRow(System.Windows.Forms.CurrencyManager lm, int row)
{
throw new NotImplementedException("GetColumnValueAtRow");
}
[TODO]
protected internal override int GetMinimumHeight()
{
throw new NotImplementedException("GetMinimumHeight");
}
[TODO]
protected internal override int GetPreferredHeight(System.Drawing.Graphics g, System.Object value)
{
throw new NotImplementedException("GetPreferredHeight");
}
[TODO]
protected internal override System.Drawing.Size GetPreferredSize(System.Drawing.Graphics g, System.Object value)
{
throw new NotImplementedException("GetPreferredSize");
}
[TODO]
protected internal override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum)
{
throw new NotImplementedException("Paint");
}
[TODO]
protected internal override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, bool alignToRight)
{
throw new NotImplementedException("Paint");
}
[TODO]
protected internal override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
throw new NotImplementedException("Paint");
}
[TODO]
protected internal override void SetColumnValueAtRow(System.Windows.Forms.CurrencyManager lm, int row, System.Object value)
{
throw new NotImplementedException("SetColumnValueAtRow");
}
[TODO]
public void add_AllowNullChanged(System.EventHandler value)
{
throw new NotImplementedException("add_AllowNullChanged");
}
[TODO]
public void add_FalseValueChanged(System.EventHandler value)
{
throw new NotImplementedException("add_FalseValueChanged");
}
[TODO]
public void add_TrueValueChanged(System.EventHandler value)
{
throw new NotImplementedException("add_TrueValueChanged");
}
[TODO]
public void remove_AllowNullChanged(System.EventHandler value)
{
throw new NotImplementedException("remove_AllowNullChanged");
}
[TODO]
public void remove_FalseValueChanged(System.EventHandler value)
{
throw new NotImplementedException("remove_FalseValueChanged");
}
[TODO]
public void remove_TrueValueChanged(System.EventHandler value)
{
throw new NotImplementedException("remove_TrueValueChanged");
}
[TODO]
public bool AllowNull
{
get
{
throw new NotImplementedException("AllowNull");
}
set
{
throw new NotImplementedException("AllowNull");
}
}
[TODO]
public System.Object FalseValue
{
get
{
throw new NotImplementedException("FalseValue");
}
set
{
throw new NotImplementedException("FalseValue");
}
}
[TODO]
public System.Object NullValue
{
get
{
throw new NotImplementedException("NullValue");
}
set
{
throw new NotImplementedException("NullValue");
}
}
[TODO]
public System.Object TrueValue
{
get
{
throw new NotImplementedException("TrueValue");
}
set
{
throw new NotImplementedException("TrueValue");
}
}
public System.EventHandler AllowNullChanged;
public System.EventHandler FalseValueChanged;
public System.EventHandler TrueValueChanged;
}
}//namespace
| |
using System;
using AutoMapper.Mappers;
namespace AutoMapper
{
using Internal;
using QueryableExtensions;
/// <summary>
/// Main entry point for AutoMapper, for both creating maps and performing maps.
/// </summary>
public static class Mapper
{
private static readonly Func<ConfigurationStore> _configurationInit =
() => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
private static ILazy<ConfigurationStore> _configuration = LazyFactory.Create(_configurationInit);
private static readonly Func<IMappingEngine> _mappingEngineInit =
() => new MappingEngine(_configuration.Value);
private static ILazy<IMappingEngine> _mappingEngine = LazyFactory.Create(_mappingEngineInit);
/// <summary>
/// When set, destination can have null values. Defaults to true.
/// This does not affect simple types, only complex ones.
/// </summary>
public static bool AllowNullDestinationValues
{
get { return Configuration.AllowNullDestinationValues; }
set { Configuration.AllowNullDestinationValues = value; }
}
/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// The source type is inferred from the source object.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TDestination>(object source)
{
return Engine.Map<TDestination>(source);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
return Engine.Map<TDestination>(source, opts);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TSource, TDestination>(TSource source)
{
return Engine.Map<TSource, TDestination>(source);
}
/// <summary>
/// Execute a mapping from the source object to the existing destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Dsetination type</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
{
return Engine.Map(source, destination);
}
/// <summary>
/// Execute a mapping from the source object to the existing destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="opts">Mapping options</param>
/// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
return Engine.Map(source, destination, opts);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
return Engine.Map(source, opts);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to create</param>
/// <returns>Mapped destination object</returns>
public static object Map(object source, Type sourceType, Type destinationType)
{
return Engine.Map(source, sourceType, destinationType);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects and supplied mapping options.
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to create</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
return Engine.Map(source, sourceType, destinationType, opts);
}
/// <summary>
/// Execute a mapping from the source object to existing destination object with explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static object Map(object source, object destination, Type sourceType, Type destinationType)
{
return Engine.Map(source, destination, sourceType, destinationType);
}
/// <summary>
/// Execute a mapping from the source object to existing destination object with supplied mapping options and explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
return Engine.Map(source, destination, sourceType, destinationType, opts);
}
/// <summary>
/// Create a map between the <typeparamref name="TSource"/> and <typeparamref name="TDestination"/> types and execute the map
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type to use</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination DynamicMap<TSource, TDestination>(TSource source)
{
return Engine.DynamicMap<TSource, TDestination>(source);
}
/// <summary>
/// Create a map between the <typeparamref name="TSource"/> and <typeparamref name="TDestination"/> types and execute the map to the existing destination object
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type to use</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
public static void DynamicMap<TSource, TDestination>(TSource source, TDestination destination)
{
Engine.DynamicMap<TSource, TDestination>(source, destination);
}
/// <summary>
/// Create a map between the <paramref name="source"/> object and <typeparamref name="TDestination"/> types and execute the map.
/// Source type is inferred from the source object .
/// </summary>
/// <typeparam name="TDestination">Destination type to use</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination DynamicMap<TDestination>(object source)
{
return Engine.DynamicMap<TDestination>(source);
}
/// <summary>
/// Create a map between the <paramref name="sourceType"/> and <paramref name="destinationType"/> types and execute the map.
/// Use this method when the source and destination types are not known until runtime.
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <returns>Mapped destination object</returns>
public static object DynamicMap(object source, Type sourceType, Type destinationType)
{
return Engine.DynamicMap(source, sourceType, destinationType);
}
/// <summary>
/// Create a map between the <paramref name="sourceType"/> and <paramref name="destinationType"/> types and execute the map to the existing destination object.
/// Use this method when the source and destination types are not known until runtime.
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination"></param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
public static void DynamicMap(object source, object destination, Type sourceType, Type destinationType)
{
Engine.DynamicMap(source, destination, sourceType, destinationType);
}
/// <summary>
/// Initializes the mapper with the supplied configuration. Runtime optimization complete after this method is called.
/// This is the preferred means to configure AutoMapper.
/// </summary>
/// <param name="action">Initialization callback</param>
public static void Initialize(Action<IConfiguration> action)
{
Reset();
action(Configuration);
Configuration.Seal();
}
/// <summary>
/// Creates a mapping configuration from the <typeparamref name="TSource"/> type to the <typeparamref name="TDestination"/> type
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <returns>Mapping expression for more configuration options</returns>
public static IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>()
{
return Configuration.CreateMap<TSource, TDestination>();
}
/// <summary>
/// Creates a mapping configuration from the <typeparamref name="TSource"/> type to the <typeparamref name="TDestination"/> type.
/// Specify the member list to validate against during configuration validation.
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="memberList">Member list to validate</param>
/// <returns>Mapping expression for more configuration options</returns>
public static IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(MemberList memberList)
{
return Configuration.CreateMap<TSource, TDestination>(memberList);
}
/// <summary>
/// Create a mapping configuration from the source type to the destination type.
/// Use this method when the source and destination type are known at runtime and not compile time.
/// </summary>
/// <param name="sourceType">Source type</param>
/// <param name="destinationType">Destination type</param>
/// <returns>Mapping expression for more configuration options</returns>
public static IMappingExpression CreateMap(Type sourceType, Type destinationType)
{
return Configuration.CreateMap(sourceType, destinationType);
}
/// <summary>
/// Creates a mapping configuration from the source type to the destination type.
/// Specify the member list to validate against during configuration validation.
/// </summary>
/// <param name="sourceType">Source type</param>
/// <param name="destinationType">Destination type</param>
/// <param name="memberList">Member list to validate</param>
/// <returns>Mapping expression for more configuration options</returns>
public static IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList)
{
return Configuration.CreateMap(sourceType, destinationType, memberList);
}
/// <summary>
/// Create a named profile for grouped mapping configuration
/// </summary>
/// <param name="profileName">Profile name</param>
/// <returns>Profile configuration options</returns>
public static IProfileExpression CreateProfile(string profileName)
{
return Configuration.CreateProfile(profileName);
}
/// <summary>
/// Create a named profile for grouped mapping configuration, and configure the profile
/// </summary>
/// <param name="profileName">Profile name</param>
/// <param name="profileConfiguration">Profile configuration callback</param>
public static void CreateProfile(string profileName, Action<IProfileExpression> profileConfiguration)
{
Configuration.CreateProfile(profileName, profileConfiguration);
}
/// <summary>
/// Add an existing profile
/// </summary>
/// <param name="profile">Profile to add</param>
public static void AddProfile(Profile profile)
{
Configuration.AddProfile(profile);
}
/// <summary>
/// Add an existing profile type. Profile will be instantiated and added to the configuration.
/// </summary>
/// <typeparam name="TProfile">Profile type</typeparam>
public static void AddProfile<TProfile>() where TProfile : Profile, new()
{
Configuration.AddProfile<TProfile>();
}
/// <summary>
/// Find the <see cref="TypeMap"/> for the configured source and destination type
/// </summary>
/// <param name="sourceType">Configured source type</param>
/// <param name="destinationType">Configured destination type</param>
/// <returns>Type map configuration</returns>
public static TypeMap FindTypeMapFor(Type sourceType, Type destinationType)
{
return ConfigurationProvider.FindTypeMapFor(sourceType, destinationType);
}
/// <summary>
/// Find the <see cref="TypeMap"/> for the configured source and destination type
/// </summary>
/// <typeparam name="TSource">Configured source type</typeparam>
/// <typeparam name="TDestination">Configured destination type</typeparam>
/// <returns>Type map configuration</returns>
public static TypeMap FindTypeMapFor<TSource, TDestination>()
{
return ConfigurationProvider.FindTypeMapFor(typeof(TSource), typeof(TDestination));
}
/// <summary>
/// Get all configured type maps created
/// </summary>
/// <returns>All configured type maps</returns>
public static TypeMap[] GetAllTypeMaps()
{
return ConfigurationProvider.GetAllTypeMaps();
}
/// <summary>
/// Dry run all configured type maps and throw <see cref="AutoMapperConfigurationException"/> for each problem
/// </summary>
public static void AssertConfigurationIsValid()
{
ConfigurationProvider.AssertConfigurationIsValid();
}
/// <summary>
/// Dry run single type map
/// </summary>
/// <param name="typeMap">Type map to check</param>
public static void AssertConfigurationIsValid(TypeMap typeMap)
{
ConfigurationProvider.AssertConfigurationIsValid(typeMap);
}
/// <summary>
/// Dry run all type maps in given profile
/// </summary>
/// <param name="profileName">Profile name of type maps to test</param>
public static void AssertConfigurationIsValid(string profileName)
{
ConfigurationProvider.AssertConfigurationIsValid(profileName);
}
/// <summary>
/// Dry run all type maps in given profile
/// </summary>
/// <typeparam name="TProfile">Profile type</typeparam>
public static void AssertConfigurationIsValid<TProfile>() where TProfile : Profile, new()
{
ConfigurationProvider.AssertConfigurationIsValid<TProfile>();
}
/// <summary>
/// Clear out all existing configuration
/// </summary>
public static void Reset()
{
MapperRegistry.Reset();
Extensions.ClearExpressionCache();
_configuration = LazyFactory.Create(_configurationInit);
_mappingEngine = LazyFactory.Create(_mappingEngineInit);
}
/// <summary>
/// Mapping engine used to perform mappings
/// </summary>
public static IMappingEngine Engine
{
get
{
return _mappingEngine.Value;
}
}
/// <summary>
/// Store for all configuration
/// </summary>
public static IConfiguration Configuration
{
get { return (IConfiguration) ConfigurationProvider; }
}
private static IConfigurationProvider ConfigurationProvider
{
get
{
return _configuration.Value;
}
}
/// <summary>
/// Globally ignore all members starting with a prefix
/// </summary>
/// <param name="startingwith">Prefix of members to ignore. Call this before all other maps created.</param>
public static void AddGlobalIgnore(string startingwith)
{
Configuration.AddGlobalIgnore(startingwith);
}
}
}
| |
namespace Azure.ResourceManager.Dns
{
public partial class DnsManagementClient
{
protected DnsManagementClient() { }
public DnsManagementClient(string subscriptionId, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.Dns.DnsManagementClientOptions options = null) { }
public DnsManagementClient(string subscriptionId, System.Uri endpoint, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.Dns.DnsManagementClientOptions options = null) { }
public virtual Azure.ResourceManager.Dns.DnsResourceReferenceOperations DnsResourceReference { get { throw null; } }
public virtual Azure.ResourceManager.Dns.RecordSetsOperations RecordSets { get { throw null; } }
public virtual Azure.ResourceManager.Dns.ZonesOperations Zones { get { throw null; } }
}
public partial class DnsManagementClientOptions : Azure.Core.ClientOptions
{
public DnsManagementClientOptions() { }
}
public partial class DnsResourceReferenceOperations
{
protected DnsResourceReferenceOperations() { }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.DnsResourceReferenceResult> GetByTargetResources(Azure.ResourceManager.Dns.Models.DnsResourceReferenceRequest parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.DnsResourceReferenceResult>> GetByTargetResourcesAsync(Azure.ResourceManager.Dns.Models.DnsResourceReferenceRequest parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class RecordSetsOperations
{
protected RecordSetsOperations() { }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.RecordSet> CreateOrUpdate(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, Azure.ResourceManager.Dns.Models.RecordSet parameters, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.RecordSet>> CreateOrUpdateAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, Azure.ResourceManager.Dns.Models.RecordSet parameters, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Delete(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.RecordSet> Get(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.RecordSet>> GetAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.Dns.Models.RecordSet> ListAllByDnsZone(string resourceGroupName, string zoneName, int? top = default(int?), string recordSetNameSuffix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.Dns.Models.RecordSet> ListAllByDnsZoneAsync(string resourceGroupName, string zoneName, int? top = default(int?), string recordSetNameSuffix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.Dns.Models.RecordSet> ListByDnsZone(string resourceGroupName, string zoneName, int? top = default(int?), string recordsetnamesuffix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.Dns.Models.RecordSet> ListByDnsZoneAsync(string resourceGroupName, string zoneName, int? top = default(int?), string recordsetnamesuffix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.Dns.Models.RecordSet> ListByType(string resourceGroupName, string zoneName, Azure.ResourceManager.Dns.Models.RecordType recordType, int? top = default(int?), string recordsetnamesuffix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.Dns.Models.RecordSet> ListByTypeAsync(string resourceGroupName, string zoneName, Azure.ResourceManager.Dns.Models.RecordType recordType, int? top = default(int?), string recordsetnamesuffix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.RecordSet> Update(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, Azure.ResourceManager.Dns.Models.RecordSet parameters, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.RecordSet>> UpdateAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, Azure.ResourceManager.Dns.Models.RecordType recordType, Azure.ResourceManager.Dns.Models.RecordSet parameters, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ZonesDeleteOperation : Azure.Operation<Azure.Response>
{
internal ZonesDeleteOperation() { }
public override bool HasCompleted { get { throw null; } }
public override bool HasValue { get { throw null; } }
public override string Id { get { throw null; } }
public override Azure.Response Value { get { throw null; } }
public override Azure.Response GetRawResponse() { throw null; }
public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class ZonesOperations
{
protected ZonesOperations() { }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.Zone> CreateOrUpdate(string resourceGroupName, string zoneName, Azure.ResourceManager.Dns.Models.Zone parameters, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.Zone>> CreateOrUpdateAsync(string resourceGroupName, string zoneName, Azure.ResourceManager.Dns.Models.Zone parameters, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.Zone> Get(string resourceGroupName, string zoneName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.Zone>> GetAsync(string resourceGroupName, string zoneName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.Dns.Models.Zone> List(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.Dns.Models.Zone> ListAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.ResourceManager.Dns.Models.Zone> ListByResourceGroup(string resourceGroupName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.ResourceManager.Dns.Models.Zone> ListByResourceGroupAsync(string resourceGroupName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.ResourceManager.Dns.ZonesDeleteOperation StartDelete(string resourceGroupName, string zoneName, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.ResourceManager.Dns.ZonesDeleteOperation> StartDeleteAsync(string resourceGroupName, string zoneName, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.ResourceManager.Dns.Models.Zone> Update(string resourceGroupName, string zoneName, Azure.ResourceManager.Dns.Models.ZoneUpdate parameters, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.Dns.Models.Zone>> UpdateAsync(string resourceGroupName, string zoneName, Azure.ResourceManager.Dns.Models.ZoneUpdate parameters, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.ResourceManager.Dns.Models
{
public partial class AaaaRecord
{
public AaaaRecord() { }
public string Ipv6Address { get { throw null; } set { } }
}
public partial class ARecord
{
public ARecord() { }
public string Ipv4Address { get { throw null; } set { } }
}
public partial class CaaRecord
{
public CaaRecord() { }
public int? Flags { get { throw null; } set { } }
public string Tag { get { throw null; } set { } }
public string Value { get { throw null; } set { } }
}
public partial class CnameRecord
{
public CnameRecord() { }
public string Cname { get { throw null; } set { } }
}
public partial class DnsResourceReference
{
internal DnsResourceReference() { }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.Dns.Models.SubResource> DnsResources { get { throw null; } }
public Azure.ResourceManager.Dns.Models.SubResource TargetResource { get { throw null; } }
}
public partial class DnsResourceReferenceRequest
{
public DnsResourceReferenceRequest() { }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.SubResource> TargetResources { get { throw null; } }
}
public partial class DnsResourceReferenceResult
{
internal DnsResourceReferenceResult() { }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.Dns.Models.DnsResourceReference> DnsResourceReferences { get { throw null; } }
}
public partial class MxRecord
{
public MxRecord() { }
public string Exchange { get { throw null; } set { } }
public int? Preference { get { throw null; } set { } }
}
public partial class NsRecord
{
public NsRecord() { }
public string Nsdname { get { throw null; } set { } }
}
public partial class PtrRecord
{
public PtrRecord() { }
public string Ptrdname { get { throw null; } set { } }
}
public partial class RecordSet
{
public RecordSet() { }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.AaaaRecord> AaaaRecords { get { throw null; } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.ARecord> ARecords { get { throw null; } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.CaaRecord> CaaRecords { get { throw null; } }
public Azure.ResourceManager.Dns.Models.CnameRecord CnameRecord { get { throw null; } set { } }
public string Etag { get { throw null; } set { } }
public string Fqdn { get { throw null; } }
public string Id { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.MxRecord> MxRecords { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.NsRecord> NsRecords { get { throw null; } }
public string ProvisioningState { get { throw null; } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.PtrRecord> PtrRecords { get { throw null; } }
public Azure.ResourceManager.Dns.Models.SoaRecord SoaRecord { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.SrvRecord> SrvRecords { get { throw null; } }
public Azure.ResourceManager.Dns.Models.SubResource TargetResource { get { throw null; } set { } }
public long? TTL { get { throw null; } set { } }
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.TxtRecord> TxtRecords { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class RecordSetListResult
{
internal RecordSetListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.Dns.Models.RecordSet> Value { get { throw null; } }
}
public enum RecordType
{
A = 0,
Aaaa = 1,
CAA = 2,
Cname = 3,
MX = 4,
NS = 5,
PTR = 6,
SOA = 7,
SRV = 8,
TXT = 9,
}
public partial class Resource
{
public Resource(string location) { }
public string Id { get { throw null; } }
public string Location { get { throw null; } set { } }
public string Name { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
public string Type { get { throw null; } }
}
public partial class SoaRecord
{
public SoaRecord() { }
public string Email { get { throw null; } set { } }
public long? ExpireTime { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public long? MinimumTtl { get { throw null; } set { } }
public long? RefreshTime { get { throw null; } set { } }
public long? RetryTime { get { throw null; } set { } }
public long? SerialNumber { get { throw null; } set { } }
}
public partial class SrvRecord
{
public SrvRecord() { }
public int? Port { get { throw null; } set { } }
public int? Priority { get { throw null; } set { } }
public string Target { get { throw null; } set { } }
public int? Weight { get { throw null; } set { } }
}
public partial class SubResource
{
public SubResource() { }
public string Id { get { throw null; } set { } }
}
public partial class TxtRecord
{
public TxtRecord() { }
public System.Collections.Generic.IList<string> Value { get { throw null; } }
}
public partial class Zone : Azure.ResourceManager.Dns.Models.Resource
{
public Zone(string location) : base (default(string)) { }
public string Etag { get { throw null; } set { } }
public long? MaxNumberOfRecordSets { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> NameServers { get { throw null; } }
public long? NumberOfRecordSets { get { throw null; } }
[System.ObsoleteAttribute("Private DNS is not allowed in this API anymore, use the privatedns API")]
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.SubResource> RegistrationVirtualNetworks { get { throw null; } }
[System.ObsoleteAttribute("Private DNS is not allowed in this API anymore, use the privatedns API")]
public System.Collections.Generic.IList<Azure.ResourceManager.Dns.Models.SubResource> ResolutionVirtualNetworks { get { throw null; } }
[System.ObsoleteAttribute("Private DNS is not allowed in this API anymore, use the privatedns API")]
public Azure.ResourceManager.Dns.Models.ZoneType? ZoneType { get { throw null; } }
}
public partial class ZoneListResult
{
internal ZoneListResult() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.Dns.Models.Zone> Value { get { throw null; } }
}
[System.ObsoleteAttribute("Enum is no longer support since privat dns is no longer supported (public only); please use the privatedns API")]
public enum ZoneType
{
Public = 0,
Private = 1,
}
public partial class ZoneUpdate
{
public ZoneUpdate() { }
public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace McDull.Windows.Forms
{
/// <summary>
/// Provides a user control that allows the user to edit HTML page.
/// </summary>
[Description("Provides a user control that allows the user to edit HTML page."), ClassInterface(ClassInterfaceType.AutoDispatch)]
public partial class HTMLTextBox : UserControl
{
/// <summary>
/// Constructor
/// </summary>
public HTMLTextBox()
{
dataUpdate = 0;
InitializeComponent();
InitializeControls();
}
#region Properties
/// <summary>
/// Gets or sets the current text in the HTMLTextBox
/// </summary>
public override string Text
{
get
{
return webBrowserBody.DocumentText;
}
set
{
webBrowserBody.DocumentText = value.Replace("\r\n", "<br>");
}
}
/// <summary>
/// Gets the collection of the image path in the HTMLTextBox
/// </summary>
public string[] Images
{
get
{
List<string> images = new List<string>();
foreach (HtmlElement element in webBrowserBody.Document.Images)
{
string image = element.GetAttribute("src");
if (!images.Contains(image))
{
images.Add(image);
}
}
return images.ToArray();
}
}
#endregion
#region Methods
/// <summary>
/// Initialize controls
/// </summary>
private void InitializeControls()
{
BeginUpdate();
// Tool Bar
foreach (FontFamily family in FontFamily.Families)
{
toolStripComboBoxName.Items.Add(family.Name);
}
toolStripComboBoxSize.Items.AddRange(FontSize.All.ToArray());
// Web Browser
webBrowserBody.DocumentText = string.Empty;
webBrowserBody.Document.Click += new HtmlElementEventHandler(webBrowserBody_DocumentClick);
webBrowserBody.Document.Focusing += new HtmlElementEventHandler(webBrowserBody_DocumentFocusing);
webBrowserBody.Document.ExecCommand("EditMode", false, null);
webBrowserBody.Document.ExecCommand("LiveResize", false, null);
EndUpdate();
}
/// <summary>
/// Refresh tool bar buttons
/// </summary>
private void RefreshToolBar()
{
BeginUpdate();
try
{
mshtml.IHTMLDocument2 document = (mshtml.IHTMLDocument2)webBrowserBody.Document.DomDocument;
toolStripComboBoxName.Text = document.queryCommandValue("FontName").ToString();
toolStripComboBoxSize.SelectedItem = FontSize.Find((int)document.queryCommandValue("FontSize"));
toolStripButtonBold.Checked = document.queryCommandState("Bold");
toolStripButtonItalic.Checked = document.queryCommandState("Italic");
toolStripButtonUnderline.Checked = document.queryCommandState("Underline");
toolStripButtonNumbers.Checked = document.queryCommandState("InsertOrderedList");
toolStripButtonBullets.Checked = document.queryCommandState("InsertUnorderedList");
toolStripButtonLeft.Checked = document.queryCommandState("JustifyLeft");
toolStripButtonCenter.Checked = document.queryCommandState("JustifyCenter");
toolStripButtonRight.Checked = document.queryCommandState("JustifyRight");
toolStripButtonFull.Checked = document.queryCommandState("JustifyFull");
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
}
finally
{
EndUpdate();
}
}
#endregion
#region Updating
private int dataUpdate;
private bool Updating
{
get
{
return dataUpdate != 0;
}
}
private void BeginUpdate()
{
++dataUpdate;
}
private void EndUpdate()
{
--dataUpdate;
}
#endregion
#region Tool Bar
private void toolStripComboBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("FontName", false, toolStripComboBoxName.Text);
}
private void toolStripComboBoxSize_SelectedIndexChanged(object sender, EventArgs e)
{
if (Updating)
{
return;
}
int size = (toolStripComboBoxSize.SelectedItem == null) ? 1 : (toolStripComboBoxSize.SelectedItem as FontSize).Value;
webBrowserBody.Document.ExecCommand("FontSize", false, size);
}
private void toolStripButtonBold_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("Bold", false, null);
RefreshToolBar();
}
private void toolStripButtonItalic_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("Italic", false, null);
RefreshToolBar();
}
private void toolStripButtonUnderline_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("Underline", false, null);
RefreshToolBar();
}
private void toolStripButtonColor_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
int fontcolor = (int)((mshtml.IHTMLDocument2)webBrowserBody.Document.DomDocument).queryCommandValue("ForeColor");
ColorDialog dialog = new ColorDialog();
dialog.Color = Color.FromArgb(0xff, fontcolor & 0xff, (fontcolor >> 8) & 0xff, (fontcolor >> 16) & 0xff);
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
string color = dialog.Color.Name;
if (!dialog.Color.IsNamedColor)
{
color = "#" + color.Remove(0, 2);
}
webBrowserBody.Document.ExecCommand("ForeColor", false, color);
}
RefreshToolBar();
}
private void toolStripButtonNumbers_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("InsertOrderedList", false, null);
RefreshToolBar();
}
private void toolStripButtonBullets_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("InsertUnorderedList", false, null);
RefreshToolBar();
}
private void toolStripButtonOutdent_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("Outdent", false, null);
RefreshToolBar();
}
private void toolStripButtonIndent_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("Indent", false, null);
RefreshToolBar();
}
private void toolStripButtonLeft_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("JustifyLeft", false, null);
RefreshToolBar();
}
private void toolStripButtonCenter_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("JustifyCenter", false, null);
RefreshToolBar();
}
private void toolStripButtonRight_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("JustifyRight", false, null);
RefreshToolBar();
}
private void toolStripButtonFull_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("JustifyFull", false, null);
RefreshToolBar();
}
private void toolStripButtonLine_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("InsertHorizontalRule", false, null);
RefreshToolBar();
}
private void toolStripButtonHyperlink_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("CreateLink", true, null);
RefreshToolBar();
}
private void toolStripButtonPicture_Click(object sender, EventArgs e)
{
if (Updating)
{
return;
}
webBrowserBody.Document.ExecCommand("InsertImage", true, null);
RefreshToolBar();
}
#endregion
#region Web Browser
private void webBrowserBody_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void webBrowserBody_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.IsInputKey)
{
return;
}
RefreshToolBar();
}
private void webBrowserBody_DocumentClick(object sender, HtmlElementEventArgs e)
{
RefreshToolBar();
}
private void webBrowserBody_DocumentFocusing(object sender, HtmlElementEventArgs e)
{
RefreshToolBar();
}
#endregion
#region Font Size
private class FontSize
{
private static List<FontSize> allFontSize = null;
public static List<FontSize> All
{
get
{
if (allFontSize == null)
{
allFontSize = new List<FontSize>();
allFontSize.Add(new FontSize(8, 1));
allFontSize.Add(new FontSize(10, 2));
allFontSize.Add(new FontSize(12, 3));
allFontSize.Add(new FontSize(14, 4));
allFontSize.Add(new FontSize(18, 5));
allFontSize.Add(new FontSize(24, 6));
allFontSize.Add(new FontSize(36, 7));
}
return allFontSize;
}
}
public static FontSize Find(int value)
{
if (value < 1)
{
return All[0];
}
if (value > 7)
{
return All[6];
}
return All[value - 1];
}
private FontSize(int display, int value)
{
displaySize = display;
valueSize = value;
}
private int valueSize;
public int Value
{
get
{
return valueSize;
}
}
private int displaySize;
public int Display
{
get
{
return displaySize;
}
}
public override string ToString()
{
return displaySize.ToString();
}
}
#endregion
#region ToolStripComboBox
private class ToolStripComboBoxEx : ToolStripComboBox
{
public override Size GetPreferredSize(Size constrainingSize)
{
Size size = base.GetPreferredSize(constrainingSize);
size.Width = Math.Max(Width, 0x20);
return size;
}
}
#endregion
}
}
| |
#region Licence
/****************************************************************************
Copyright 1999-2015 Vincent J. Jacquet. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
****************************************************************************/
#endregion
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace WmcSoft.ComponentModel.Design
{
public class SelectionService : ISelectionService
{
private readonly object _rootComponent;
private readonly ArrayList _selectedComponents;
public SelectionService(IServiceProvider serviceProvider, object rootComponent)
{
_rootComponent = rootComponent;
_selectedComponents = new ArrayList();
if (rootComponent != null) {
_selectedComponents.Add(rootComponent);
}
// Subscribe to the ComponentRemoved event
if (serviceProvider != null) {
var c = serviceProvider.GetService<IComponentChangeService>();
if (c != null) {
c.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved);
}
}
}
public ICollection GetSelectedComponents()
{
return _selectedComponents.ToArray();
}
public event EventHandler SelectionChanging {
add { Events.AddHandler(SelectionChangingEvent, value); }
remove { Events.RemoveHandler(SelectionChangingEvent, value); }
}
private static readonly object SelectionChangingEvent = new object();
/// <summary>
/// Fire the SelectionChanging event if anything is bound to it
/// </summary>
/// <param name="e"></param>
protected virtual void OnSelectionChanging(EventArgs e)
{
((EventHandler)_events[SelectionChangingEvent])?.Invoke(this, e);
}
public event EventHandler SelectionChanged {
add { Events.AddHandler(SelectionChangedEvent, value); }
remove { Events.RemoveHandler(SelectionChangedEvent, value); }
}
private static readonly object SelectionChangedEvent = new object();
/// <summary>
/// Fire the SelectionChanging event if anything is bound to it
/// </summary>
/// <param name="e"></param>
protected virtual void OnSelectionChanged(EventArgs e)
{
((EventHandler)_events[SelectionChangedEvent])?.Invoke(this, e);
}
public object PrimarySelection {
get {
if (_selectedComponents.Count > 0) {
return _selectedComponents[0];
}
return null;
}
}
public int SelectionCount {
get { return _selectedComponents.Count; }
}
public bool GetComponentSelected(object component)
{
return _selectedComponents.Contains(component);
}
public void SetSelectedComponents(ICollection components, SelectionTypes selectionType)
{
// Interpret the selection type
bool primary = (selectionType & SelectionTypes.Primary) == SelectionTypes.Primary;
bool toggle = (selectionType & SelectionTypes.Toggle) == SelectionTypes.Toggle;
bool add = (selectionType & SelectionTypes.Add) == SelectionTypes.Add;
bool remove = (selectionType & SelectionTypes.Remove) == SelectionTypes.Remove;
bool replace = (selectionType & SelectionTypes.Replace) == SelectionTypes.Replace;
// Components can be null, but not one of its items
if (components == null) {
components = new object[0];
}
foreach (object component in components) {
if (component == null) {
throw new ArgumentNullException(nameof(components));
}
}
if (primary && components.Count != 1) {
throw new ArgumentException(nameof(components));
}
// If the selection type is Click, we want to know if shift or control is being held
//bool control = false;
//bool shift = false;
//if ((selectionType & SelectionTypes.Click) == SelectionTypes.Click)
//{
// control = ((Control.ModifierKeys & Keys.Control) == Keys.Control);
// shift = ((Control.ModifierKeys & Keys.Shift) == Keys.Shift);
//}
// Raise selectionchanging event
//
OnSelectionChanging(EventArgs.Empty);
if (replace) {
// Simply replace our existing collection with the new one
_selectedComponents.Clear();
foreach (object component in components) {
if (component != null && !_selectedComponents.Contains(component)) {
_selectedComponents.Add(component);
}
}
} else if (primary) {
var enumerator = components.GetEnumerator();
using (enumerator as IDisposable) {
if (enumerator.MoveNext()) {
object component = enumerator.Current;
int index = _selectedComponents.IndexOf(component);
if (index >= 0) {
object temp = _selectedComponents[0];
_selectedComponents[0] = _selectedComponents[index];
_selectedComponents[index] = temp;
} else {
_selectedComponents.Clear();
_selectedComponents.Add(component);
}
}
}
} else {
// Add or remove each component to or from the selection
foreach (object component in components) {
if (_selectedComponents.Contains(component)) {
if (toggle || remove) {
_selectedComponents.Remove(component);
}
} else {
if (toggle || add) {
_selectedComponents.Add(component);
}
}
}
}
if (_selectedComponents.Count == 0 && _rootComponent != null)
_selectedComponents.Add(_rootComponent);
OnSelectionChanged(EventArgs.Empty);
}
public void SetSelectedComponents(ICollection components)
{
// Use the Replace selection type because this needs to replace anything already selected
SetSelectedComponents(components, SelectionTypes.Replace);
}
internal void OnComponentRemoved(object sender, ComponentEventArgs e)
{
if (_selectedComponents.Contains(e.Component)) {
OnSelectionChanging(EventArgs.Empty);
// Remove this component from the selected components
_selectedComponents.Remove(e.Component);
// Select root component if that leaves us with no selected components
if (SelectionCount == 0 && _rootComponent != null) {
_selectedComponents.Add(_rootComponent);
}
OnSelectionChanged(EventArgs.Empty);
}
}
#region Events
protected EventHandlerList Events {
get {
if (_events == null) {
_events = new EventHandlerList();
}
return _events;
}
}
[NonSerialized]
private EventHandlerList _events;
#endregion
}
}
| |
using LitJson;
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using AsyncRPGSharedLib.Navigation;
public class GameData
{
private const int IRC_MAX_NICK_LENGTH = 16;
// The id of the current character
private int m_characterID;
// The id of the current game
private int m_gameID;
// The name of the current game
private string m_gameName;
// IRC Settings
private bool m_ircEnabled;
private string m_ircServer;
private uint m_ircPort;
private string m_ircNick;
private string m_ircGameChannel;
private byte[] m_ircEncryptionKey;
private bool m_ircEncryptionEnabled;
// Character data for all characters in the game
private Dictionary<int, CharacterData> m_characters; // character_id -> Character Data
// List of relevant events that have happened to the player since they have been in the game
public List<GameEvent> m_eventList;
public uint m_eventCursor;
// Data specific to each room
private Dictionary<string, RoomData> m_roomDataCache; // room hash -> RoomData
private RoomKey m_currentRoomKey;
public GameData()
{
reset();
}
public void reset()
{
m_characterID = -1;
m_gameID = -1;
m_gameName = "";
m_ircEnabled = false;
m_ircServer= "";
m_ircPort = 0;
m_ircNick = "";
m_ircGameChannel= "";
m_ircEncryptionKey = null;
m_ircEncryptionEnabled = false;
m_characters = new Dictionary<int, CharacterData>();
//m_eventList = new List<GameEvent>();
m_eventCursor = 0;
m_roomDataCache = new Dictionary<string, RoomData>();
m_currentRoomKey = new RoomKey();
}
// Game Properties
public int GameID
{
get { return m_gameID; }
set { m_gameID = value; }
}
public string GameName
{
get { return m_gameName; }
set { m_gameName= value; }
}
// IRC Settings
public bool IRCEnabled
{
get { return m_ircEnabled; }
set { m_ircEnabled= value; }
}
public string IRCServer
{
get { return m_ircServer; }
set { m_ircServer = value; }
}
public uint IRCPort
{
get { return m_ircPort; }
set { m_ircPort= value; }
}
public string IRCGameChannel
{
get { return m_ircGameChannel; }
set { m_ircGameChannel= value; }
}
public string IRCNick
{
get { return m_ircNick; }
set { m_ircNick= value; }
}
public byte[] IRCEncryptionKey
{
get { return m_ircEncryptionEnabled ? m_ircEncryptionKey : null; }
}
// Room State
public RoomData CurrentRoom
{
get { return GetCachedRoomData(m_currentRoomKey); }
}
public RoomKey CurrentRoomKey
{
get { return m_currentRoomKey; }
set { m_currentRoomKey = new RoomKey(value); }
}
public bool HasRoomData(RoomKey roomKey)
{
return m_roomDataCache.ContainsKey(roomKey.GetHashKey());
}
public RoomData GetCachedRoomData(RoomKey roomKey)
{
RoomData roomData = null;
return m_roomDataCache.TryGetValue(roomKey.GetHashKey(), out roomData) ? roomData : null;
}
public void SetCachedRoomData(RoomKey roomKey, RoomData roomData)
{
string roomKeyString = roomKey.GetHashKey();
if (m_roomDataCache.ContainsKey(roomKeyString))
{
m_roomDataCache[roomKeyString] = roomData;
}
else
{
m_roomDataCache.Add(roomKeyString, roomData);
}
}
// Character State
public int CharacterID
{
get { return m_characterID; }
set { m_characterID= value; }
}
public Dictionary<int, CharacterData> CharacterMap
{
get { return m_characters; }
}
public CharacterData GetCharacterById(int character_id)
{
CharacterData characterData = null;
return m_characters.TryGetValue(character_id, out characterData) ? characterData : null;
}
public void SetCharacterById(int character_id, CharacterData characterState)
{
if (m_characters.ContainsKey(character_id))
{
m_characters[character_id] = characterState;
}
else
{
m_characters.Add(character_id, characterState);
}
}
// Game Event Handling
public int EventCount
{
get { return m_eventList.Count; }
}
public uint EventCursor
{
get { return m_eventCursor; }
}
public bool IsEventCursorAtFistEvent
{
get { return m_eventCursor == 0; }
}
public bool IsEventCursorAtLastEvent
{
get { return m_eventCursor >= m_eventList.Count; }
}
public bool ReverseEventCursor(GameWorldController gameWorldController)
{
bool success = false;
if (!IsEventCursorAtFistEvent)
{
m_eventCursor = m_eventCursor - 1;
m_eventList[(int)m_eventCursor].UndoEvent(gameWorldController);
success = true;
}
return success;
}
public bool AdvanceEventCursor(GameWorldController gameWorldController, GameEvent.OnEventCompleteDelegate onComplete)
{
bool success = false;
if (!IsEventCursorAtLastEvent)
{
GameEvent gameEvent= m_eventList[(int)m_eventCursor];
string chatString = gameEvent.ToChatString(gameWorldController);
gameEvent.ApplyEvent(gameWorldController, onComplete);
if (chatString.Length > 0)
{
gameWorldController.SendChatWindowText(chatString);
}
m_eventCursor = m_eventCursor + 1;
success = true;
}
return success;
}
// Server Response Parsers
public bool ParseFullGameStateResponse(JsonData response)
{
CharacterData character = null;
bool success = true;
// Parse the character data
{
m_characters = new Dictionary<int, CharacterData>();
JsonData characterObjects = response["characters"];
for (int characterListIndex= 0; characterListIndex < characterObjects.Count; characterListIndex++)
{
JsonData characterObject= characterObjects[characterListIndex];
CharacterData characterData = CharacterData.FromObject(characterObject);
// Use the existing game name and ID store on the game state
// This should have already been set by the time we made the request for the data.
characterData.game_id = this.m_gameID;
characterData.game_name = this.m_gameName;
SetCharacterById(characterData.character_id, characterData);
}
character = GetCharacterById(this.CharacterID);
success = character != null;
}
// Parse the IRC data
{
m_ircEnabled = (bool)response["irc_enabled"];
m_ircServer= (string)response["irc_server"];
m_ircPort = (uint)((int)response["irc_port"]);
m_ircGameChannel= "ARPG_" + this.GameID.ToString();
m_ircEncryptionKey = System.Convert.FromBase64String((string)response["irc_encryption_key"]);
m_ircEncryptionEnabled = (bool)response["irc_encryption_enabled"];
m_ircNick = character.character_name+"_"+character.character_id.ToString()+"_"+m_gameID.ToString();
m_ircNick = m_ircNick.Substring(0, Math.Min(IRC_MAX_NICK_LENGTH, m_ircNick.Length));
}
// Parse the room data for the current character and cache it
if (success)
{
success = ParseRoomDataResponse(response);
}
// Parse the game event list
if (success)
{
m_eventList = new List<GameEvent>();
// Append all of the events contained in the response
ParseEventResponse(response);
// Set the event cursor to the end of the event list
m_eventCursor = (uint)m_eventList.Count;
}
return success;
}
public bool ParseRoomDataResponse(JsonData response)
{
RoomData roomData = RoomData.FromObject(response);
bool success = false;
if (roomData != null)
{
m_currentRoomKey = roomData.RoomKey;
SetCachedRoomData(roomData.RoomKey, roomData);
success = true;
}
return success;
}
public void ParseEventResponse(JsonData response)
{
JsonData eventObjects = response["event_list"];
if (eventObjects != null)
{
for (int list_index = 0; list_index < eventObjects.Count; list_index++)
{
JsonData eventObject = eventObjects[list_index];
GameEvent gameEvent = GameEvent.FromObject(eventObject);
m_eventList.Add(gameEvent);
}
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using PartsUnlimited.Models;
namespace PartsUnlimited.Models.Migrations
{
[DbContext(typeof(PartsUnlimitedContext))]
[Migration("20151109193640_InitialMigration")]
partial class InitialMigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.Annotation("ProductVersion", "7.0.0-beta8-15964")
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedName")
.Annotation("Relational:Name", "RoleNameIndex");
b.Annotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("PartsUnlimited.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.Annotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("Name");
b.Property<string>("NormalizedEmail")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.Annotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedEmail")
.Annotation("Relational:Name", "EmailIndex");
b.Index("NormalizedUserName")
.Annotation("Relational:Name", "UserNameIndex");
b.Annotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("PartsUnlimited.Models.CartItem", b =>
{
b.Property<int>("CartItemId")
.ValueGeneratedOnAdd();
b.Property<string>("CartId")
.IsRequired();
b.Property<int>("Count");
b.Property<DateTime>("DateCreated");
b.Property<int>("ProductId");
b.HasKey("CartItemId");
});
modelBuilder.Entity("PartsUnlimited.Models.Category", b =>
{
b.Property<int>("CategoryId")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("ImageUrl");
b.Property<string>("Name")
.IsRequired();
b.HasKey("CategoryId");
});
modelBuilder.Entity("PartsUnlimited.Models.Order", b =>
{
b.Property<int>("OrderId")
.ValueGeneratedOnAdd();
b.Property<string>("Address")
.IsRequired()
.Annotation("MaxLength", 70);
b.Property<string>("City")
.IsRequired()
.Annotation("MaxLength", 40);
b.Property<string>("Country")
.IsRequired()
.Annotation("MaxLength", 40);
b.Property<string>("Email")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.Annotation("MaxLength", 160);
b.Property<DateTime>("OrderDate");
b.Property<string>("Phone")
.IsRequired()
.Annotation("MaxLength", 24);
b.Property<string>("PostalCode")
.IsRequired()
.Annotation("MaxLength", 10);
b.Property<bool>("Processed");
b.Property<string>("State")
.IsRequired()
.Annotation("MaxLength", 40);
b.Property<decimal>("Total");
b.Property<string>("Username")
.IsRequired();
b.HasKey("OrderId");
});
modelBuilder.Entity("PartsUnlimited.Models.OrderDetail", b =>
{
b.Property<int>("OrderDetailId")
.ValueGeneratedOnAdd();
b.Property<int>("OrderId");
b.Property<int>("ProductId");
b.Property<int>("Quantity");
b.Property<decimal>("UnitPrice");
b.HasKey("OrderDetailId");
});
modelBuilder.Entity("PartsUnlimited.Models.Product", b =>
{
b.Property<int>("ProductId")
.ValueGeneratedOnAdd();
b.Property<int>("CategoryId");
b.Property<DateTime>("Created");
b.Property<string>("Description")
.IsRequired();
b.Property<int>("Inventory");
b.Property<int>("LeadTime");
b.Property<decimal>("Price");
b.Property<string>("ProductArtUrl")
.IsRequired()
.Annotation("MaxLength", 1024);
b.Property<string>("ProductDetails")
.IsRequired();
b.Property<int>("RecommendationId");
b.Property<decimal>("SalePrice");
b.Property<string>("SkuNumber")
.IsRequired();
b.Property<string>("Title")
.IsRequired()
.Annotation("MaxLength", 160);
b.HasKey("ProductId");
});
modelBuilder.Entity("PartsUnlimited.Models.Raincheck", b =>
{
b.Property<int>("RaincheckId")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<int>("ProductId");
b.Property<int>("Quantity");
b.Property<double>("SalePrice");
b.Property<int>("StoreId");
b.HasKey("RaincheckId");
});
modelBuilder.Entity("PartsUnlimited.Models.Store", b =>
{
b.Property<int>("StoreId")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("StoreId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("PartsUnlimited.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("PartsUnlimited.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
b.HasOne("PartsUnlimited.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("PartsUnlimited.Models.CartItem", b =>
{
b.HasOne("PartsUnlimited.Models.Product")
.WithMany()
.ForeignKey("ProductId");
});
modelBuilder.Entity("PartsUnlimited.Models.OrderDetail", b =>
{
b.HasOne("PartsUnlimited.Models.Order")
.WithMany()
.ForeignKey("OrderId");
b.HasOne("PartsUnlimited.Models.Product")
.WithMany()
.ForeignKey("ProductId");
});
modelBuilder.Entity("PartsUnlimited.Models.Product", b =>
{
b.HasOne("PartsUnlimited.Models.Category")
.WithMany()
.ForeignKey("CategoryId");
});
modelBuilder.Entity("PartsUnlimited.Models.Raincheck", b =>
{
b.HasOne("PartsUnlimited.Models.Product")
.WithMany()
.ForeignKey("ProductId");
b.HasOne("PartsUnlimited.Models.Store")
.WithMany()
.ForeignKey("StoreId");
});
}
}
}
| |
#if !DISABLE_PLAYFABCLIENT_API
using PlayFab.ClientModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if !DISABLE_PLAYFABENTITY_API
using PlayFab.AuthenticationModels;
using PlayFab.DataModels;
#endif
namespace PlayFab.UUnit
{
public class PlayFabApiTest : UUnitTestCase
{
private const string TEST_STAT_NAME = "str";
private const string TEST_DATA_KEY = "testCounter";
private int _testInteger;
// Functional
private static bool TITLE_INFO_SET = false;
// Fixed values provided from testInputs
private static TestTitleData testTitleData;
private static PlayFabAuthenticationContext authenticationContext1, authenticationContext2, authenticationContext3;
private readonly PlayFabAuthenticationInstanceAPI authApi = new PlayFabAuthenticationInstanceAPI(PlayFabSettings.staticPlayer);
private readonly PlayFabClientInstanceAPI clientApi = new PlayFabClientInstanceAPI(PlayFabSettings.staticPlayer);
private readonly PlayFabDataInstanceAPI dataApi = new PlayFabDataInstanceAPI(PlayFabSettings.staticPlayer);
/// <summary>
/// PlayFab Title cannot be created from SDK tests, so you must provide your titleId to run unit tests.
/// (Also, we don't want lots of excess unused titles)
/// </summary>
public static void SetTitleInfo(TestTitleData testInputs)
{
TITLE_INFO_SET = true;
testTitleData = testInputs;
// Verify all the inputs won't cause crashes in the tests
TITLE_INFO_SET &= !string.IsNullOrEmpty(PlayFabSettings.staticSettings.TitleId)
&& !string.IsNullOrEmpty(testTitleData.userEmail);
}
public override void SetUp(UUnitTestContext testContext)
{
maxRetry = 1;
if (!TITLE_INFO_SET)
testContext.Skip(); // We cannot do client tests if the titleId is not given
}
public override void Tick(UUnitTestContext testContext)
{
// No work needed, async tests will end themselves
}
/// <summary>
/// CLIENT API
/// Try to deliberately log in with an inappropriate password,
/// and verify that the error displays as expected.
/// </summary>
[UUnitTest]
public void InvalidLogin(UUnitTestContext testContext)
{
// If the setup failed to log in a user, we need to create one.
var request = new LoginWithEmailAddressRequest
{
TitleId = PlayFabSettings.staticSettings.TitleId,
Email = testTitleData.userEmail,
Password = "INVALID",
};
var loginTask = clientApi.LoginWithEmailAddressAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(loginTask, testContext, InvalidLoginContinued, false, "Login should fail", true);
}
private void InvalidLoginContinued(PlayFabResult<LoginResult> loginResult, UUnitTestContext testContext, string failMessage)
{
testContext.NotNull(loginResult, failMessage);
testContext.IsNull(loginResult.Result, failMessage);
testContext.NotNull(loginResult.Error, failMessage);
testContext.True(loginResult.Error.GenerateErrorReport().Contains("RequestId") && loginResult.Error.ErrorMessage.Contains("password"), loginResult.Error.ErrorMessage + ", for: "+ testTitleData.userEmail + ", on: " + PlayFabSettings.staticSettings.TitleId);
}
/// <summary>
/// CLIENT API
/// Try to deliberately register a user with an invalid email and password
/// Verify that errorDetails are populated correctly.
/// </summary>
[UUnitTest]
public void InvalidRegistration(UUnitTestContext testContext)
{
var registerRequest = new RegisterPlayFabUserRequest
{
TitleId = PlayFabSettings.staticSettings.TitleId,
Username = "x",
Email = "x",
Password = "x",
};
var registerTask = clientApi.RegisterPlayFabUserAsync(registerRequest, null, testTitleData.extraHeaders);
ContinueWithContext(registerTask, testContext, InvalidRegistrationContinued, false, "Registration should fail", true);
}
private void InvalidRegistrationContinued(PlayFabResult<RegisterPlayFabUserResult> registerResult, UUnitTestContext testContext, string failMessage)
{
testContext.NotNull(registerResult, failMessage);
testContext.IsNull(registerResult.Result, failMessage);
testContext.NotNull(registerResult.Error, failMessage);
var expectedEmailMsg = "email address is not valid.";
var expectedPasswordMsg = "password must be between";
var fullReport = registerResult.Error.GenerateErrorReport();
testContext.True(fullReport.ToLower().Contains(expectedEmailMsg), "Expected an error about bad email address: " + fullReport);
testContext.True(fullReport.ToLower().Contains(expectedPasswordMsg), "Expected an error about bad password: " + fullReport);
}
/// <summary>
/// CLIENT API
/// Log in or create a user, track their PlayFabId
/// </summary>
[UUnitTest]
public void LoginOrRegister(UUnitTestContext testContext)
{
var loginRequest = new LoginWithCustomIDRequest
{
TitleId = PlayFabSettings.staticSettings.TitleId,
CustomId = PlayFabSettings.BuildIdentifier,
CreateAccount = true
};
var loginTask = clientApi.LoginWithCustomIDAsync(loginRequest, null, testTitleData.extraHeaders);
ContinueWithContext(loginTask, testContext, LoginOrRegisterContinued, true, "User login failed", true);
}
private void LoginOrRegisterContinued(PlayFabResult<LoginResult> loginResult, UUnitTestContext testContext, string failMessage)
{
testContext.True(clientApi.IsClientLoggedIn(), failMessage);
}
/// <summary>
/// CLIENT API
/// Test a sequence of calls that modifies saved data,
/// and verifies that the next sequential API call contains updated data.
/// Verify that the data is correctly modified on the next call.
/// Parameter types tested: string, Dictionary>string, string>, DateTime
/// </summary>
[UUnitTest]
public void UserDataApi(UUnitTestContext testContext)
{
var getRequest = new GetUserDataRequest();
var getDataTask1 = clientApi.GetUserDataAsync(getRequest, null, testTitleData.extraHeaders);
ContinueWithContext(getDataTask1, testContext, UserDataApiContinued1, true, "GetUserData1 call failed", false);
}
private void UserDataApiContinued1(PlayFabResult<GetUserDataResult> getDataResult1, UUnitTestContext testContext, string failMessage)
{
UserDataRecord testCounter;
if (!getDataResult1.Result.Data.TryGetValue(TEST_DATA_KEY, out testCounter))
testCounter = new UserDataRecord { Value = "0" };
int.TryParse(testCounter.Value, out _testInteger);
_testInteger = (_testInteger + 1) % 100; // This test is about the expected value changing - but not testing more complicated issues like bounds
var updateRequest = new UpdateUserDataRequest { Data = new Dictionary<string, string> { { TEST_DATA_KEY, _testInteger.ToString() } } };
var updateTask = clientApi.UpdateUserDataAsync(updateRequest, null, testTitleData.extraHeaders);
ContinueWithContext(updateTask, testContext, UserDataApiContinued2, true, "UpdateUserData call failed", false); // The update doesn't return anything interesting except versionID. It's better to just re-call GetUserData again below to verify the update
}
private void UserDataApiContinued2(PlayFabResult<UpdateUserDataResult> updateResult, UUnitTestContext testContext, string failMessage)
{
var getRequest = new GetUserDataRequest();
var getDataTask2 = clientApi.GetUserDataAsync(getRequest, null, testTitleData.extraHeaders);
ContinueWithContext(getDataTask2, testContext, UserDataApiContinued3, true, "GetUserData2 call failed", true);
}
private void UserDataApiContinued3(PlayFabResult<GetUserDataResult> getDataResult2, UUnitTestContext testContext, string failMessage)
{
int testCounterValueActual;
UserDataRecord testCounter;
getDataResult2.Result.Data.TryGetValue(TEST_DATA_KEY, out testCounter);
testContext.NotNull(testCounter, "The updated UserData was not found in the Api results");
int.TryParse(testCounter.Value, out testCounterValueActual);
testContext.IntEquals(_testInteger, testCounterValueActual);
var timeUpdated = testCounter.LastUpdated;
var testMin = DateTime.UtcNow - TimeSpan.FromMinutes(5);
var testMax = testMin + TimeSpan.FromMinutes(10);
testContext.True(testMin <= timeUpdated && timeUpdated <= testMax);
}
/// <summary>
/// CLIENT API
/// Tests several parallel requests and ensures they complete with no errors.
/// </summary>
[UUnitTest]
public void ParallelRequests(UUnitTestContext testContext)
{
var tasks = Enumerable.Range(0, 10)
.Select(_ => clientApi.GetUserDataAsync(new GetUserDataRequest(), _, testTitleData.extraHeaders))
.Select(ThrowIfApiError);
Task.WhenAll(tasks).ContinueWith(whenAll =>
{
if (!whenAll.IsCanceled && !whenAll.IsFaulted)
{
testContext.EndTest(UUnitFinishState.PASSED, null);
}
else
{
testContext.Fail("Parallel Requests failed " + whenAll.Exception.Flatten().Message);
}
});
}
/// <summary>
/// CLIENT API
/// Test a sequence of calls that modifies saved data,
/// and verifies that the next sequential API call contains updated data.
/// Verify that the data is saved correctly, and that specific types are tested
/// Parameter types tested: Dictionary>string, int>
/// </summary>
[UUnitTest]
public void PlayerStatisticsApi(UUnitTestContext testContext)
{
var getRequest = new GetPlayerStatisticsRequest();
var getStatTask1 = clientApi.GetPlayerStatisticsAsync(getRequest, null, testTitleData.extraHeaders);
ContinueWithContext(getStatTask1, testContext, PlayerStatisticsApiContinued1, true, "GetPlayerStatistics1 call failed", false);
}
private void PlayerStatisticsApiContinued1(PlayFabResult<GetPlayerStatisticsResult> getStatResult1, UUnitTestContext testContext, string failMessage)
{
foreach (var eachStat in getStatResult1.Result.Statistics)
if (eachStat.StatisticName == TEST_STAT_NAME)
_testInteger = eachStat.Value;
_testInteger = (_testInteger + 1) % 100; // This test is about the expected value changing (incrementing through from TEST_STAT_BASE to TEST_STAT_BASE * 2 - 1)
var updateRequest = new UpdatePlayerStatisticsRequest { Statistics = new List<StatisticUpdate> { new StatisticUpdate { StatisticName = TEST_STAT_NAME, Value = _testInteger } } };
var updateTask = clientApi.UpdatePlayerStatisticsAsync(updateRequest, null, testTitleData.extraHeaders);
ContinueWithContext(updateTask, testContext, PlayerStatisticsApiContinued2, true, "UpdatePlayerStatistics call failed", false);
}
private void PlayerStatisticsApiContinued2(PlayFabResult<UpdatePlayerStatisticsResult> updateResult, UUnitTestContext testContext, string failMessage)
{
var getRequest = new GetPlayerStatisticsRequest();
var getStatTask2 = clientApi.GetPlayerStatisticsAsync(getRequest, null, testTitleData.extraHeaders);
ContinueWithContext(getStatTask2, testContext, PlayerStatisticsApiContinued3, true, "GetPlayerStatistics2 call failed", true);
}
private void PlayerStatisticsApiContinued3(PlayFabResult<GetPlayerStatisticsResult> getStatResult2, UUnitTestContext testContext, string failMessage)
{
var testStatActual = int.MinValue;
foreach (var eachStat in getStatResult2.Result.Statistics)
if (eachStat.StatisticName == TEST_STAT_NAME)
testStatActual = eachStat.Value;
testContext.IntEquals(_testInteger, testStatActual);
}
/// <summary>
/// SERVER API
/// Get or create the given test character for the given user
/// Parameter types tested: Contained-Classes, string
/// </summary>
[UUnitTest]
public void UserCharacter(UUnitTestContext testContext)
{
var request = new ListUsersCharactersRequest { PlayFabId = PlayFabSettings.staticPlayer.PlayFabId };
var getCharsTask = clientApi.GetAllUsersCharactersAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(getCharsTask, testContext, null, true, "Failed to GetChars", true);
}
/// <summary>
/// CLIENT AND SERVER API
/// Test that leaderboard results can be requested
/// Parameter types tested: List of contained-classes
/// </summary>
[UUnitTest]
public void LeaderBoard(UUnitTestContext testContext)
{
var clientRequest = new GetLeaderboardRequest
{
MaxResultsCount = 3,
StatisticName = TEST_STAT_NAME,
};
var clientTask = clientApi.GetLeaderboardAsync(clientRequest, null, testTitleData.extraHeaders);
ContinueWithContext(clientTask, testContext, LeaderBoardContinued, true, "Failed to get client leaderboard", true);
}
private void LeaderBoardContinued(PlayFabResult<GetLeaderboardResult> clientResult, UUnitTestContext testContext, string failMessage)
{
testContext.True(clientResult.Result.Leaderboard.Count > 0, "Leaderboard does not contain enough entries.");
}
/// <summary>
/// CLIENT API
/// Test that AccountInfo can be requested
/// Parameter types tested: List of enum-as-strings converted to list of enums
/// </summary>
[UUnitTest]
public void AccountInfo(UUnitTestContext testContext)
{
var request = new GetAccountInfoRequest { PlayFabId = PlayFabSettings.staticPlayer.PlayFabId };
var accountTask = clientApi.GetAccountInfoAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(accountTask, testContext, LeaderBoardContinued, true, "Failed to get accountInfo", true);
}
private void LeaderBoardContinued(PlayFabResult<GetAccountInfoResult> accountResult, UUnitTestContext testContext, string failMessage)
{
testContext.True(Enum.IsDefined(typeof(UserOrigination), accountResult.Result.AccountInfo.TitleInfo.Origination.Value), "Origination Enum not valid");
}
/// <summary>
/// CLIENT API
/// Test that CloudScript can be properly set up and invoked
/// </summary>
[UUnitTest]
public void CloudScript(UUnitTestContext testContext)
{
var request = new ClientModels.ExecuteCloudScriptRequest { FunctionName = "helloWorld" };
var cloudTask = clientApi.ExecuteCloudScriptAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(cloudTask, testContext, CloudScriptContinued, true, "Failed to Execute CloudScript", true);
}
private void CloudScriptContinued(PlayFabResult<ClientModels.ExecuteCloudScriptResult> cloudResult, UUnitTestContext testContext, string failMessage)
{
string messageValue = null;
// Get the helloWorld return message
testContext.NotNull(cloudResult.Result.FunctionResult);
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var sjobj = serializer.DeserializeObject<Dictionary<string, object>>(serializer.SerializeObject(cloudResult.Result.FunctionResult));
if (sjobj != null)
messageValue = sjobj["messageValue"] as string;
testContext.StringEquals("Hello " + PlayFabSettings.staticPlayer.PlayFabId + "!", messageValue);
}
/// <summary>
/// CLIENT API
/// Test that CloudScript errors can be deciphered
/// </summary>
[UUnitTest]
public void CloudScriptError(UUnitTestContext testContext)
{
var request = new ClientModels.ExecuteCloudScriptRequest { FunctionName = "throwError" };
var cloudTask = clientApi.ExecuteCloudScriptAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(cloudTask, testContext, CloudScriptErrorContinued, true, "Failed to Execute CloudScript", true);
}
private void CloudScriptErrorContinued(PlayFabResult<ClientModels.ExecuteCloudScriptResult> cloudResult, UUnitTestContext testContext, string failMessage)
{
// Get the JavascriptException result
testContext.IsNull(cloudResult.Result.FunctionResult);
testContext.NotNull(cloudResult.Result.Error);
testContext.StringEquals(cloudResult.Result.Error.Error, "JavascriptException");
}
/// <summary>
/// CLIENT API
/// Test that the client can publish custom PlayStream events
/// </summary>
[UUnitTest]
public void WriteEvent(UUnitTestContext testContext)
{
var request = new WriteClientPlayerEventRequest
{
EventName = "ForumPostEvent",
Timestamp = DateTime.UtcNow,
Body = new Dictionary<string, object> {
{ "Subject", "My First Post" },
{ "Body", "My awesome Post." },
}
};
var writeTask = clientApi.WritePlayerEventAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(writeTask, testContext, null, true, "PlayStream WriteEvent failed", true);
}
#if !DISABLE_PLAYFABENTITY_API
/// <summary>
/// ENTITY API
/// Get the EntityToken for the client player
/// </summary>
[UUnitTest]
public void GetEntityToken(UUnitTestContext testContext)
{
var writeTask = authApi.GetEntityTokenAsync(new GetEntityTokenRequest(), null, testTitleData.extraHeaders);
ContinueWithContext(writeTask, testContext, null, true, "GetEntityToken failed", true);
}
/// <summary>
/// ENTITY API
/// Test a sequence of calls that modifies entity objects,
/// and verifies that the next sequential API call contains updated info.
/// Verify that the data is correctly modified on the next call.
/// Parameter types tested: string, Dictionary<string, string>, DateTime
/// </summary>
[UUnitTest]
public void ObjectApi(UUnitTestContext testContext)
{
var request = new GetObjectsRequest
{
Entity = new DataModels.EntityKey
{
Id = PlayFabSettings.staticPlayer.EntityId,
Type = PlayFabSettings.staticPlayer.EntityType,
},
EscapeObject = true
};
var eachTask = dataApi.GetObjectsAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(eachTask, testContext, GetObjects1Continued, true, "GetObjects1 failed", false);
}
private void GetObjects1Continued(PlayFabResult<GetObjectsResponse> result, UUnitTestContext testContext, string failMessage)
{
// testContext.IntEquals(result.Result.Objects.Count, 1);
// testContext.StringEquals(result.Result.Objects[0].ObjectName, TEST_DATA_KEY);
_testInteger = 0;
if (result.Result.Objects.Count == 1 && result.Result.Objects[TEST_DATA_KEY].ObjectName == TEST_DATA_KEY)
int.TryParse(result.Result.Objects[TEST_DATA_KEY].EscapedDataObject, out _testInteger);
var request = new SetObjectsRequest
{
Entity = new DataModels.EntityKey
{
Id = PlayFabSettings.staticPlayer.EntityId,
Type = PlayFabSettings.staticPlayer.EntityType,
},
Objects = new List<SetObject>
{
new SetObject
{
DataObject = _testInteger,
ObjectName = TEST_DATA_KEY
}
}
};
var eachTask = dataApi.SetObjectsAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(eachTask, testContext, SetObjectsContinued, true, "SetObjects failed", false);
}
private void SetObjectsContinued(PlayFabResult<SetObjectsResponse> result, UUnitTestContext testContext, string failMessage)
{
var request = new GetObjectsRequest
{
Entity = new DataModels.EntityKey
{
Id = PlayFabSettings.staticPlayer.EntityId,
Type = PlayFabSettings.staticPlayer.EntityType,
},
EscapeObject = true
};
var eachTask = dataApi.GetObjectsAsync(request, null, testTitleData.extraHeaders);
ContinueWithContext(eachTask, testContext, GetObjects2Continued, true, "GetObjects2 failed", false);
}
private void GetObjects2Continued(PlayFabResult<GetObjectsResponse> result, UUnitTestContext testContext, string failMessage)
{
testContext.IntEquals(result.Result.Objects.Count, 1);
testContext.StringEquals(result.Result.Objects[TEST_DATA_KEY].ObjectName, TEST_DATA_KEY);
if (!int.TryParse(result.Result.Objects[TEST_DATA_KEY].EscapedDataObject, out int actualValue))
actualValue = -1000;
testContext.IntEquals(_testInteger, actualValue, "Failed: " + _testInteger + "!=" + actualValue + ", Returned json: " + result.Result.Objects[TEST_DATA_KEY].EscapedDataObject);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
#endif
/// <summary>
/// CLIENT API
/// Test that Multiple login can be done with static methods
/// </summary>
[UUnitTest]
public void MultipleLoginWithStaticMethods(UUnitTestContext testContext)
{
// If the setup failed to log in a user, we need to create one.
var loginRequest1 = new LoginWithCustomIDRequest
{
TitleId = PlayFabSettings.staticSettings.TitleId,
CustomId = "test_SDK1",
CreateAccount = true,
};
var loginRequest2 = new LoginWithCustomIDRequest
{
TitleId = PlayFabSettings.staticSettings.TitleId,
CustomId = "test_SDK2",
CreateAccount = true,
};
var loginRequest3 = new LoginWithCustomIDRequest
{
TitleId = PlayFabSettings.staticSettings.TitleId,
CustomId = "test_SDK3",
CreateAccount = true,
};
var loginTask1 = clientApi.LoginWithCustomIDAsync(loginRequest1, null, testTitleData.extraHeaders).Result;
var loginTask2 = clientApi.LoginWithCustomIDAsync(loginRequest2, null, testTitleData.extraHeaders).Result;
var loginTask3 = clientApi.LoginWithCustomIDAsync(loginRequest3, null, testTitleData.extraHeaders).Result;
testContext.NotNull(loginTask1.Result, "Login Result is null for loginRequest1");
testContext.NotNull(loginTask2.Result, "Login Result is null for loginRequest2");
testContext.NotNull(loginTask3.Result, "Login Result is null for loginRequest3");
testContext.IsNull(loginTask1.Error, "Login error occured for loginRequest1: " + loginTask1.Error?.ErrorMessage ?? string.Empty);
testContext.IsNull(loginTask2.Error, "Login error occured for loginRequest2: " + loginTask2.Error?.ErrorMessage ?? string.Empty);
testContext.IsNull(loginTask3.Error, "Login error occured for loginRequest3: " + loginTask3.Error?.ErrorMessage ?? string.Empty);
testContext.NotNull(loginTask1.Result.AuthenticationContext, "AuthenticationContext is not set for loginRequest1,");
testContext.NotNull(loginTask2.Result.AuthenticationContext, "AuthenticationContext is not set for loginRequest2");
testContext.NotNull(loginTask3.Result.AuthenticationContext, "AuthenticationContext is not set for loginRequest3");
if (string.Equals(loginTask1.Result.AuthenticationContext.ClientSessionTicket, loginTask2.Result.AuthenticationContext.ClientSessionTicket))
{
testContext.Fail("Multiple Login Failed AuthenticationContexts are same for task1 and task2: " + loginTask1.Result.AuthenticationContext.ClientSessionTicket);
}
if (string.Equals(loginTask2.Result.AuthenticationContext.ClientSessionTicket, loginTask3.Result.AuthenticationContext.ClientSessionTicket))
{
testContext.Fail("Multiple Login Failed AuthenticationContexts are same for task2 and task3: " + loginTask2.Result.AuthenticationContext.ClientSessionTicket);
}
if (string.Equals(loginTask1.Result.AuthenticationContext.ClientSessionTicket, loginTask3.Result.AuthenticationContext.ClientSessionTicket))
{
testContext.Fail("Multiple Login Failed AuthenticationContexts are same for task1 and task3: " + loginTask1.Result.AuthenticationContext.ClientSessionTicket);
}
authenticationContext1 = loginTask1.Result.AuthenticationContext;
authenticationContext2 = loginTask2.Result.AuthenticationContext;
authenticationContext3 = loginTask3.Result.AuthenticationContext;
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Test that Multiple player can do api calls
/// </summary>
[UUnitTest]
public void MultiplePlayerApiCall(UUnitTestContext testContext)
{
if (authenticationContext1?.ClientSessionTicket == null || authenticationContext2?.ClientSessionTicket == null)
{
testContext.Skip("To run this test MultipleLoginWithStaticMethods test should be passed and store authenticationContext values");
}
var getPlayerProfileRequest = new GetPlayerProfileRequest()
{
AuthenticationContext = authenticationContext1,
PlayFabId = authenticationContext1.PlayFabId
};
var getPlayerProfileRequest2 = new GetPlayerProfileRequest()
{
AuthenticationContext = authenticationContext2,
PlayFabId = authenticationContext2.PlayFabId
};
var getPlayerProfileTask = clientApi.GetPlayerProfileAsync(getPlayerProfileRequest, null, testTitleData.extraHeaders).Result;
var getPlayerProfileTask2 = clientApi.GetPlayerProfileAsync(getPlayerProfileRequest2, null, testTitleData.extraHeaders).Result;
testContext.NotNull(getPlayerProfileTask.Result, "GetPlayerProfile Failed for getPlayerProfileRequest");
testContext.NotNull(getPlayerProfileTask2.Result, "GetPlayerProfile Failed for getPlayerProfileRequest2");
testContext.IsNull(getPlayerProfileTask.Error, "GetPlayerProfile error occured for getPlayerProfileRequest: " + getPlayerProfileTask.Error?.ErrorMessage ?? string.Empty);
testContext.IsNull(getPlayerProfileTask2.Error, "GetPlayerProfile error occured for getPlayerProfileRequest2: " + getPlayerProfileTask2.Error?.ErrorMessage ?? string.Empty);
testContext.EndTest(UUnitFinishState.PASSED, null);
}
/// <summary>
/// CLIENT API
/// Tests async api calls with multiple users
/// </summary>
[UUnitTest]
public void AsyncApiCallWithMultipleUser(UUnitTestContext testContext)
{
if (authenticationContext1?.ClientSessionTicket == null || authenticationContext2?.ClientSessionTicket == null || authenticationContext3?.ClientSessionTicket == null)
{
testContext.Skip("To run this test MultipleLoginWithStaticMethods test should be passed and store authenticationContext values");
}
var task1 = clientApi.GetUserDataAsync(new GetUserDataRequest() { AuthenticationContext = authenticationContext1 }, null, testTitleData.extraHeaders);
var task2 = clientApi.GetUserDataAsync(new GetUserDataRequest() { AuthenticationContext = authenticationContext2 }, null, testTitleData.extraHeaders);
var task3 = clientApi.GetUserDataAsync(new GetUserDataRequest() { AuthenticationContext = authenticationContext3 }, null, testTitleData.extraHeaders);
var tasks = new List<Task>() { task1, task2, task3 };
Task.WhenAll(tasks).ContinueWith(whenAll =>
{
if (!whenAll.IsCanceled && !whenAll.IsFaulted)
{
testContext.EndTest(UUnitFinishState.PASSED, null);
}
else
{
testContext.Fail("Async failed " + whenAll.Exception.Flatten().Message);
}
});
}
}
}
#endif
| |
// Copyright ?2004, 2011, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Collections;
using System.IO;
using System.Text;
using MySql.Data.Common;
using System.Data;
using MySql.Data.MySqlClient.Properties;
using System.Collections.Generic;
namespace MySql.Data.MySqlClient
{
internal abstract class Statement
{
protected MySqlCommand command;
protected string commandText;
private List<MySqlPacket> buffers;
private Statement(MySqlCommand cmd)
{
command = cmd;
buffers = new List<MySqlPacket>();
}
public Statement(MySqlCommand cmd, string text)
: this(cmd)
{
commandText = text;
}
#region Properties
public virtual string ResolvedCommandText
{
get { return commandText; }
}
protected Driver Driver
{
get { return command.Connection.driver; }
}
protected MySqlConnection Connection
{
get { return command.Connection; }
}
protected MySqlParameterCollection Parameters
{
get { return command.Parameters; }
}
#endregion
public virtual void Close(MySqlDataReader reader)
{
}
public virtual void Resolve(bool preparing)
{
}
public virtual void Execute()
{
// we keep a reference to this until we are done
BindParameters();
ExecuteNext();
}
public virtual bool ExecuteNext()
{
if (buffers.Count == 0)
return false;
MySqlPacket packet = (MySqlPacket)buffers[0];
//MemoryStream ms = stream.InternalBuffer;
Driver.SendQuery(packet);
buffers.RemoveAt(0);
return true;
}
protected virtual void BindParameters()
{
MySqlParameterCollection parameters = command.Parameters;
int index = 0;
while (true)
{
InternalBindParameters(ResolvedCommandText, parameters, null);
// if we are not batching, then we are done. This is only really relevant the
// first time through
if (command.Batch == null) return;
while (index < command.Batch.Count)
{
MySqlCommand batchedCmd = command.Batch[index++];
MySqlPacket packet = (MySqlPacket)buffers[buffers.Count - 1];
// now we make a guess if this statement will fit in our current stream
long estimatedCmdSize = batchedCmd.EstimatedSize();
if (((packet.Length - 4) + estimatedCmdSize) > Connection.driver.MaxPacketSize)
{
// it won't, so we setup to start a new run from here
parameters = batchedCmd.Parameters;
break;
}
// looks like we might have room for it so we remember the current end of the stream
buffers.RemoveAt(buffers.Count - 1);
//long originalLength = packet.Length - 4;
// and attempt to stream the next command
string text = ResolvedCommandText;
if (text.StartsWith("(", StringComparison.Ordinal))
packet.WriteStringNoNull(", ");
else
packet.WriteStringNoNull("; ");
InternalBindParameters(text, batchedCmd.Parameters, packet);
if ((packet.Length - 4) > Connection.driver.MaxPacketSize)
{
//TODO
//stream.InternalBuffer.SetLength(originalLength);
parameters = batchedCmd.Parameters;
break;
}
}
if (index == command.Batch.Count)
return;
}
}
private void InternalBindParameters(string sql, MySqlParameterCollection parameters,
MySqlPacket packet)
{
bool sqlServerMode = command.Connection.Settings.SqlServerMode;
if (packet == null)
{
packet = new MySqlPacket(Driver.Encoding);
packet.Version = Driver.Version;
packet.WriteByte(0);
}
MySqlTokenizer tokenizer = new MySqlTokenizer(sql);
tokenizer.ReturnComments = true;
tokenizer.SqlServerMode = sqlServerMode;
int pos = 0;
string token = tokenizer.NextToken();
int parameterCount = 0;
while (token != null)
{
// serialize everything that came before the token (i.e. whitespace)
packet.WriteStringNoNull(sql.Substring(pos, tokenizer.StartIndex - pos));
pos = tokenizer.StopIndex;
if (MySqlTokenizer.IsParameter(token))
{
if ((!parameters.containsUnnamedParameters && token.Length == 1 && parameterCount > 0) || parameters.containsUnnamedParameters && token.Length > 1)
throw new MySqlException(Resources.MixedParameterNamingNotAllowed);
parameters.containsUnnamedParameters = token.Length == 1;
if (SerializeParameter(parameters, packet, token, parameterCount))
token = null;
parameterCount++;
}
if (token != null)
{
if (sqlServerMode && tokenizer.Quoted && token.StartsWith("[", StringComparison.Ordinal))
token = String.Format("`{0}`", token.Substring(1, token.Length - 2));
packet.WriteStringNoNull(token);
}
token = tokenizer.NextToken();
}
buffers.Add(packet);
}
protected virtual bool ShouldIgnoreMissingParameter(string parameterName)
{
if (Connection.Settings.AllowUserVariables)
return true;
if (parameterName.StartsWith("@" + StoredProcedure.ParameterPrefix, StringComparison.OrdinalIgnoreCase))
return true;
if (parameterName.Length > 1 &&
(parameterName[1] == '`' || parameterName[1] == '\''))
return true;
return false;
}
/// <summary>
/// Serializes the given parameter to the given memory stream
/// </summary>
/// <remarks>
/// <para>This method is called by PrepareSqlBuffers to convert the given
/// parameter to bytes and write those bytes to the given memory stream.
/// </para>
/// </remarks>
/// <returns>True if the parameter was successfully serialized, false otherwise.</returns>
private bool SerializeParameter(MySqlParameterCollection parameters,
MySqlPacket packet, string parmName, int parameterIndex)
{
MySqlParameter parameter = null;
if (!parameters.containsUnnamedParameters)
parameter = parameters.GetParameterFlexible(parmName, false);
else
{
if (parameterIndex <= parameters.Count)
parameter = parameters[parameterIndex];
else
throw new MySqlException(Resources.ParameterIndexNotFound);
}
if (parameter == null)
{
// if we are allowing user variables and the parameter name starts with @
// then we can't throw an exception
if (parmName.StartsWith("@", StringComparison.Ordinal) && ShouldIgnoreMissingParameter(parmName))
return false;
throw new MySqlException(
String.Format(Resources.ParameterMustBeDefined, parmName));
}
parameter.Serialize(packet, false, Connection.Settings);
return true;
}
}
}
| |
//
// FreeformShapeTool.cs
//
// Author:
// Jonathan Pobst <[email protected]>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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 Cairo;
using Gtk;
using Pinta.Core;
using Mono.Unix;
namespace Pinta.Tools
{
public class FreeformShapeTool : BaseBrushTool
{
private Point last_point = point_empty;
protected ToolBarLabel fill_label;
protected ToolBarDropDownButton fill_button;
protected Gtk.SeparatorToolItem fill_sep;
private Path path;
private Color fill_color;
private Color outline_color;
public FreeformShapeTool ()
{
}
#region Properties
public override string Name { get { return Catalog.GetString ("Freeform Shape"); } }
public override string Icon { get { return "Tools.FreeformShape.png"; } }
public override string StatusBarText { get { return Catalog.GetString ("Left click to draw with primary color, right click to draw with secondary color."); } }
public override Gdk.Cursor DefaultCursor { get { return new Gdk.Cursor (PintaCore.Chrome.Canvas.Display, PintaCore.Resources.GetIcon ("Cursor.FreeformShape.png"), 9, 18); } }
public override Gdk.Key ShortcutKey { get { return Gdk.Key.O; } }
public override int Priority { get { return 47; } }
#endregion
#region ToolBar
protected override void OnBuildToolBar (Toolbar tb)
{
base.OnBuildToolBar(tb);
if (fill_sep == null)
fill_sep = new Gtk.SeparatorToolItem ();
tb.AppendItem (fill_sep);
if (fill_label == null)
fill_label = new ToolBarLabel (string.Format (" {0}: ", Catalog.GetString ("Fill Style")));
tb.AppendItem (fill_label);
if (fill_button == null) {
fill_button = new ToolBarDropDownButton ();
fill_button.AddItem (Catalog.GetString ("Outline Shape"), "ShapeTool.Outline.png", 0);
fill_button.AddItem (Catalog.GetString ("Fill Shape"), "ShapeTool.Fill.png", 1);
fill_button.AddItem (Catalog.GetString ("Fill and Outline Shape"), "ShapeTool.OutlineFill.png", 2);
}
tb.AppendItem (fill_button);
}
#endregion
#region Mouse Handlers
protected override void OnMouseDown (Gtk.DrawingArea canvas, Gtk.ButtonPressEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
surface_modified = false;
undo_surface = doc.CurrentUserLayer.Surface.Clone ();
path = null;
doc.ToolLayer.Clear ();
doc.ToolLayer.Hidden = false;
}
protected override void OnMouseMove (object o, Gtk.MotionNotifyEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
if ((args.Event.State & Gdk.ModifierType.Button1Mask) == Gdk.ModifierType.Button1Mask) {
outline_color = PintaCore.Palette.PrimaryColor;
fill_color = PintaCore.Palette.SecondaryColor;
} else if ((args.Event.State & Gdk.ModifierType.Button3Mask) == Gdk.ModifierType.Button3Mask) {
outline_color = PintaCore.Palette.SecondaryColor;
fill_color = PintaCore.Palette.PrimaryColor;
} else {
last_point = point_empty;
return;
}
int x = (int)point.X;
int y = (int)point.Y;
if (last_point.Equals (point_empty)) {
last_point = new Point (x, y);
return;
}
if (doc.Workspace.PointInCanvas (point))
surface_modified = true;
doc.ToolLayer.Clear ();
ImageSurface surf = doc.ToolLayer.Surface;
using (Context g = new Context (surf)) {
doc.Selection.Clip(g);
g.Antialias = UseAntialiasing ? Antialias.Subpixel : Antialias.None;
if (path != null) {
g.AppendPath (path);
(path as IDisposable).Dispose ();
} else {
g.MoveTo (x, y);
}
g.LineTo (x, y);
path = g.CopyPath ();
g.ClosePath ();
g.LineWidth = BrushWidth;
g.LineJoin = LineJoin.Round;
g.LineCap = LineCap.Round;
g.FillRule = FillRule.EvenOdd;
if (FillShape && StrokeShape) {
g.Color = fill_color;
g.FillPreserve ();
g.Color = outline_color;
g.Stroke ();
} else if (FillShape) {
g.Color = outline_color;
g.Fill ();
} else {
g.Color = outline_color;
g.Stroke ();
}
}
doc.Workspace.Invalidate ();
last_point = new Point (x, y);
}
protected override void OnMouseUp (Gtk.DrawingArea canvas, Gtk.ButtonReleaseEventArgs args, Cairo.PointD point)
{
Document doc = PintaCore.Workspace.ActiveDocument;
doc.ToolLayer.Hidden = true;
if (surface_modified)
PintaCore.History.PushNewItem (new SimpleHistoryItem (Icon, Name, undo_surface, doc.CurrentUserLayerIndex));
else if (undo_surface != null)
(undo_surface as IDisposable).Dispose ();
surface_modified = false;
ImageSurface surf = doc.CurrentUserLayer.Surface;
using (Context g = new Context (surf)) {
g.AppendPath (doc.Selection.SelectionPath);
g.FillRule = FillRule.EvenOdd;
g.Clip ();
g.Antialias = UseAntialiasing ? Antialias.Subpixel : Antialias.None;
if (path != null) {
g.AppendPath (path);
(path as IDisposable).Dispose ();
path = null;
}
g.ClosePath ();
g.LineWidth = BrushWidth;
g.LineJoin = LineJoin.Round;
g.LineCap = LineCap.Round;
g.FillRule = FillRule.EvenOdd;
if (FillShape && StrokeShape) {
g.Color = fill_color;
g.FillPreserve ();
g.Color = outline_color;
g.Stroke ();
} else if (FillShape) {
g.Color = outline_color;
g.Fill ();
} else {
g.Color = outline_color;
g.Stroke ();
}
}
doc.Workspace.Invalidate ();
}
#endregion
#region Private Methods
protected bool StrokeShape { get { return (int)fill_button.SelectedItem.Tag % 2 == 0; } }
protected bool FillShape { get { return (int)fill_button.SelectedItem.Tag >= 1; } }
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Implementation of a dynamic data collection based on generic Collection<T>,
/// implementing INotifyCollectionChanged to notify listeners
/// when items get added, removed or the whole list is refreshed.
/// </summary>
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
/// </summary>
public ObservableCollection() : base() { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class that contains
/// elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the collection.
/// </remarks>
/// <exception cref="ArgumentNullException"> collection is a null reference </exception>
public ObservableCollection(IEnumerable<T> collection) : base(CreateCopy(collection)) { }
private static List<T> CreateCopy(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
return new List<T>(collection);
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Move item at oldIndex to newIndex.
/// </summary>
public void Move(int oldIndex, int newIndex)
{
MoveItem(oldIndex, newIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
//------------------------------------------------------
#region INotifyPropertyChanged implementation
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
PropertyChanged += value;
}
remove
{
PropertyChanged -= value;
}
}
#endregion INotifyPropertyChanged implementation
//------------------------------------------------------
/// <summary>
/// Occurs when the collection changes, either by adding or removing an item.
/// </summary>
/// <remarks>
/// see <seealso cref="INotifyCollectionChanged"/>
/// </remarks>
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Called by base class Collection<T> when the list is being cleared;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void ClearItems()
{
CheckReentrancy();
base.ClearItems();
OnCountPropertyChanged();
OnIndexerPropertyChanged();
OnCollectionReset();
}
/// <summary>
/// Called by base class Collection<T> when an item is removed from list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void RemoveItem(int index)
{
CheckReentrancy();
T removedItem = this[index];
base.RemoveItem(index);
OnCountPropertyChanged();
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is added to list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void InsertItem(int index, T item)
{
CheckReentrancy();
base.InsertItem(index, item);
OnCountPropertyChanged();
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is set in list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void SetItem(int index, T item)
{
CheckReentrancy();
T originalItem = this[index];
base.SetItem(index, item);
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
}
/// <summary>
/// Called by base class ObservableCollection<T> when an item is to be moved within the list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected virtual void MoveItem(int oldIndex, int newIndex)
{
CheckReentrancy();
T removedItem = this[oldIndex];
base.RemoveItem(oldIndex);
base.InsertItem(newIndex, removedItem);
OnIndexerPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex);
}
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raise CollectionChanged event to any listeners.
/// Properties/methods modifying this ObservableCollection will raise
/// a collection changed event through this virtual method.
/// </summary>
/// <remarks>
/// When overriding this method, either call its base implementation
/// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
/// </remarks>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
using (BlockReentrancy())
{
CollectionChanged(this, e);
}
}
}
/// <summary>
/// Disallow reentrant attempts to change this collection. E.g. a event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
/// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope:
/// <code>
/// using (BlockReentrancy())
/// {
/// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index));
/// }
/// </code>
/// </remarks>
protected IDisposable BlockReentrancy()
{
_monitor.Enter();
return _monitor;
}
/// <summary> Check and assert for reentrant attempts to change this collection. </summary>
/// <exception cref="InvalidOperationException"> raised when changing the collection
/// while another collection change is still being notified to other listeners </exception>
protected void CheckReentrancy()
{
if (_monitor.Busy)
{
// we can allow changes if there's only one listener - the problem
// only arises if reentrant changes make the original event args
// invalid for later listeners. This keeps existing code working
// (e.g. Selector.SelectedItems).
if ((CollectionChanged != null) && (CollectionChanged.GetInvocationList().Length > 1))
throw new InvalidOperationException(SR.ObservableCollectionReentrancyNotAllowed);
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Helper to raise a PropertyChanged event for the Count property
/// </summary>
private void OnCountPropertyChanged()
{
OnPropertyChanged(EventArgsCache.CountPropertyChanged);
}
/// <summary>
/// Helper to raise a PropertyChanged event for the Indexer property
/// </summary>
private void OnIndexerPropertyChanged()
{
OnPropertyChanged(EventArgsCache.IndexerPropertyChanged);
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
}
/// <summary>
/// Helper to raise CollectionChanged event with action == Reset to any listeners
/// </summary>
private void OnCollectionReset()
{
OnCollectionChanged(EventArgsCache.ResetCollectionChanged);
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// this class helps prevent reentrant calls
private class SimpleMonitor : IDisposable
{
public void Enter()
{
++_busyCount;
}
public void Dispose()
{
--_busyCount;
}
public bool Busy { get { return _busyCount > 0; } }
private int _busyCount;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private readonly SimpleMonitor _monitor = new SimpleMonitor();
#endregion Private Fields
}
internal static class EventArgsCache
{
internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count");
internal static readonly PropertyChangedEventArgs IndexerPropertyChanged = new PropertyChangedEventArgs("Item[]");
internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyString
{
using System;
using System.Linq;
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>
/// EnumModel operations.
/// </summary>
public partial class EnumModel : IServiceOperations<AutoRestSwaggerBATService>, IEnumModel
{
/// <summary>
/// Initializes a new instance of the EnumModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public EnumModel(AutoRestSwaggerBATService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATService
/// </summary>
public AutoRestSwaggerBATService Client { get; private set; }
/// <summary>
/// Get enum value 'red color' from enumeration of 'red color', 'green-color',
/// 'blue_color'.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Colors?>> GetNotExpandableWithHttpMessagesAsync(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, "GetNotExpandable", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_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);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Colors?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Colors?>(_responseContent, this.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>
/// Sends value 'red color' from enumeration of 'red color', 'green-color',
/// 'blue_color'
/// </summary>
/// <param name='stringBody'>
/// Possible values for this parameter include: 'red color', 'green-color',
/// 'blue_color'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutNotExpandableWithHttpMessagesAsync(Colors? stringBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (stringBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "stringBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("stringBody", stringBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutNotExpandable", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_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 = null;
_requestContent = SafeJsonConvert.SerializeObject(stringBody, 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();
_httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
extern alias pt;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Python.Parsing;
using Microsoft.PythonTools;
using Microsoft.PythonTools.TestAdapter.Pytest;
using Microsoft.PythonTools.TestAdapter.UnitTest;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestAdapterTests.Mocks;
using TestUtilities;
using PythonConstants = pt::Microsoft.PythonTools.PythonConstants;
namespace TestAdapterTests {
[TestClass, Ignore]
public abstract partial class TestDiscovererTests {
private const string FrameworkPytest = "Pytest";
private const string FrameworkUnittest = "Unittest";
protected abstract PythonVersion Version { get; }
protected virtual string ImportErrorFormat => "ModuleNotFoundError: No module named '{0}'";
[ClassCleanup]
public static void ClassCleanup() {
TestEnvironment.Clear();
}
[TestInitialize]
public void CheckVersion() {
if (Version == null) {
Assert.Inconclusive("Required version of Python is not installed");
}
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void DiscoverPytest() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_pt.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicPytest", "test_pt.py"), testFilePath);
var expectedTests = new[] {
new TestInfo("test_pt_pass", "test_pt.py::test_pt::test_pt_pass", testFilePath, 1),
new TestInfo("test_pt_fail", "test_pt.py::test_pt::test_pt_fail", testFilePath, 4),
new TestInfo("test_method_pass", "test_pt.py::TestClassPT::test_method_pass", testFilePath, 8),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestUppercaseFileName() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_Uppercase.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Uppercase", "test_Uppercase.py"), testFilePath);
var expectedTests = new[] {
new TestInfo("test_A", "test_Uppercase.py::Test_UppercaseClass::test_A", testFilePath, 4),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestTimeoutError() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_timeout_pt.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Timeout", "test_timeout_pt.py"), testFilePath);
int waitTimeInSeconds = 1;
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath, waitTimeInSeconds)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new PytestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath }, discoveryContext, logger, discoverySink);
Assert.AreEqual(0, discoverySink.Tests.Count);
var errors = string.Join(Environment.NewLine, logger.GetErrors());
AssertUtil.Contains(
errors,
Strings.PythonTestDiscovererTimeoutErrorMessage
);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestSearchPath() {
// test_search_path.py has an import at global scope that requires search path to resolve
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ImportFromSearchPath"), testEnv.SourceFolderPath);
// <SourceFolderPath>/TestFolder/
// <SourceFolderPath>/TestFolder/test_search_path.py
// <SourceFolderPath>/SearchPath/
// <SourceFolderPath>/SearchPath/searchpathmodule.py
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "TestFolder", "test_search_path.py");
var searchPath = Path.Combine(testEnv.SourceFolderPath, "SearchPath");
var expectedTests = new[] {
new TestInfo("test_imported_module", "TestFolder\\test_search_path.py::SearchPathTests::test_imported_module", testFilePath, 5),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.WithSearchPath(searchPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestSyntaxErrorPartialResults() {
// one file has a valid passing test,
// the other has a test with a syntax error in it
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "SyntaxErrorPytest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_basic.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_syntax_error.py");
var expectedTests = new[] {
new TestInfo("test_success", "test_basic.py::test_basic::test_success", testFilePath1, 1),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath1, testFilePath2 }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestSyntaxErrorLogErrors() {
// one file has a valid passing test,
// the other has a test with a syntax error in it
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "SyntaxErrorPytest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_basic.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_syntax_error.py");
var expectedTests = new[] {
new TestInfo("test_success", "test_basic.py::test_basic::test_success", testFilePath1, 1),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new PytestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath1, testFilePath2 }, discoveryContext, logger, discoverySink);
var errors = string.Join(Environment.NewLine, logger.GetErrors());
AssertUtil.Contains(errors,
"SyntaxError: invalid syntax"
);
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void DiscoverPytestImportError() {
// one file has a valid passing test,
// the other has an unknown module import at global scope
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ImportErrorPytest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_basic.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_import_error.py");
var expectedTests = new[] {
new TestInfo("test_success", "test_basic.py::test_basic::test_success", testFilePath1, 1),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath1, testFilePath2 }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void DiscoverUnitTestImportError() {
// one file has a valid passing test,
// the other has an unknown module import at global scope
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ImportErrorUnittest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_no_error.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_import_error.py");
var expectedTests = new[] {
new TestInfo("test_no_error", "test_no_error.py::NoErrorTests::test_no_error", testFilePath1, 4),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath1, testFilePath2 }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnitTestSyntaxErrorPartialResults() {
// one file has a valid passing test,
// the other has an unknown module import at global scope
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "SyntaxErrorUnittest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_basic_ut.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_syntax_error_ut.py");
var expectedTests = new[] {
new TestInfo("test_ut_fail", "test_basic_ut.py::TestClassUT::test_ut_fail", testFilePath1, 4),
new TestInfo("test_ut_pass", "test_basic_ut.py::TestClassUT::test_ut_pass", testFilePath1, 7),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new UnittestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath1, testFilePath2 }, discoveryContext, logger, discoverySink);
ValidateDiscoveredTests(testEnv.TestFramework, discoverySink.Tests, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnitTestSyntaxErrorLogErrors() {
// one file has a valid passing test,
// the other has an unknown module import at global scope
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "SyntaxErrorUnittest"), testEnv.SourceFolderPath);
var testFilePath1 = Path.Combine(testEnv.SourceFolderPath, "test_basic_ut.py");
var testFilePath2 = Path.Combine(testEnv.SourceFolderPath, "test_syntax_error_ut.py");
var expectedTests = new[] {
new TestInfo("test_ut_fail", "test_basic_ut.py::TestClassUT::test_ut_fail", testFilePath1, 4),
new TestInfo("test_ut_pass", "test_basic_ut.py::TestClassUT::test_ut_pass", testFilePath1, 7),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath1)
.WithTestFile(testFilePath2)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new UnittestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath1, testFilePath2 }, discoveryContext, logger, discoverySink);
var errors = string.Join(Environment.NewLine, logger.GetErrors());
if (Version.Version > PythonLanguageVersion.V27) {
AssertUtil.Contains(errors,
"SyntaxError: invalid syntax"
);
} else {
Assert.Inconclusive("Python 2.7 unittest errors are not currently being printed to error logs");
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestConfigPythonFiles() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ConfigPythonFiles"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_pt.py");
var checkFilePath = Path.Combine(testEnv.SourceFolderPath, "check_pt.py");
var exampleFilePath = Path.Combine(testEnv.SourceFolderPath, "example_pt.py");
// pytest.ini declares that tests are only files named check_*.py and test_*.py
// so the test defined in example_pt.py should not be discovered
var expectedTests = new[] {
new TestInfo("test_1", "test_pt.py::test_pt::test_1", testFilePath, 1),
new TestInfo("test_2", "check_pt.py::check_pt::test_2", checkFilePath, 1),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(checkFilePath)
.WithTestFile(testFilePath)
.WithTestFile(exampleFilePath)
.ToXml()
);
DiscoverTests(testEnv, new[] { checkFilePath, testFilePath, exampleFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestConfigPythonFunctions() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ConfigPythonFunctions"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_misc_prefixes.py");
// pytest.ini declares that tests are only functions named check_* and verify_*
// so the test named test_* and example_* should not be discovered
var expectedTests = new[] {
new TestInfo("check_func", "test_misc_prefixes.py::test_misc_prefixes::check_func", testFilePath, 4),
new TestInfo("verify_func", "test_misc_prefixes.py::test_misc_prefixes::verify_func", testFilePath, 10),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestNotInstalled() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest, installFramework: false);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_pt.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicPytest", "test_pt.py"), testFilePath);
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new PytestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath }, discoveryContext, logger, discoverySink);
Assert.AreEqual(0, discoverySink.Tests.Count);
var errors = string.Join(Environment.NewLine, logger.GetErrors());
AssertUtil.Contains(errors, string.Format(ImportErrorFormat, "pytest"));
}
[TestMethod, Priority(UnitTestPriority.P0)]
[TestCategory("10s")]
public void DiscoverUnittest() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFile1Path = Path.Combine(testEnv.SourceFolderPath, "test_ut.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicUnittest", "test_ut.py"), testFile1Path);
var testFile2Path = Path.Combine(testEnv.SourceFolderPath, "test_runtest.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "BasicUnittest", "test_runtest.py"), testFile2Path);
var expectedTests = new[] {
new TestInfo("test_ut_fail", "test_ut.py::TestClassUT::test_ut_fail", testFile1Path, 4),
new TestInfo("test_ut_pass", "test_ut.py::TestClassUT::test_ut_pass", testFile1Path, 7),
new TestInfo("runTest", "test_runtest.py::TestClassRunTest::runTest", testFile2Path, 4),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFile1Path }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestConfiguration() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "ConfigUnittest"), testEnv.SourceFolderPath);
// We have 3 files
// product/prefix_not_included.py (should not be found, outside test folder)
// test/test_not_included.py (should not be found, incorrect filename pattern)
// test/prefix_included.py (should be found)
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test", "prefix_included.py");
var expectedTests = new[] {
new TestInfo("test_included", "test\\prefix_included.py::PrefixIncluded::test_included", testFilePath, 4),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(Path.Combine(testEnv.SourceFolderPath, "product"))
.WithTestFilesFromFolder(Path.Combine(testEnv.SourceFolderPath, "test"))
.WithUnitTestConfiguration("test", "prefix_*.py")
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestUppercaseFileName() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_Uppercase.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Uppercase", "test_Uppercase.py"), testFilePath);
var expectedTests = new[] {
new TestInfo("test_A", "test_Uppercase.py::Test_UppercaseClass::test_A", testFilePath, 4),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestTimeoutError() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_ut.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Timeout", "test_timeout_ut.py"), testFilePath);
int waitTimeInSeconds = 1;
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath, waitTimeInSeconds)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
var discoverer = new UnittestTestDiscoverer();
discoverer.DiscoverTests(new[] { testFilePath }, discoveryContext, logger, discoverySink);
Assert.AreEqual(0, discoverySink.Tests.Count);
var errors = string.Join(Environment.NewLine, logger.GetErrors());
AssertUtil.Contains(
errors,
Strings.PythonTestDiscovererTimeoutErrorMessage
);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestDecoratorsIgnoreLineNumbers() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_decorators_ut.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Decorators", "test_decorators_ut.py"), testFilePath);
// disable line checking until we fix https://github.com/microsoft/PTVS/issues/5497
var expectedTests = new[] {
new TestInfo("test_ut_fail", "test_decorators_ut.py::TestClassDecoratorsUT::test_ut_fail", testFilePath, -1),
new TestInfo("test_ut_pass", "test_decorators_ut.py::TestClassDecoratorsUT::test_ut_pass", testFilePath, -1),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[Ignore] //until we fix https://github.com/microsoft/PTVS/issues/5497
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestDecoratorsCorrectLineNumbers() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_decorators_ut.py");
File.Copy(TestData.GetPath("TestData", "TestDiscoverer", "Decorators", "test_decorators_ut.py"), testFilePath);
var expectedTests = new[] {
new TestInfo("test_ut_fail", "test_decorators_ut.py::TestClassDecoratorsUT::test_ut_fail", testFilePath, 5),
//bschnurr note: currently unittest/_discovery.py is returning decorators line number
new TestInfo("test_ut_pass", "test_decorators_ut.py::TestClassDecoratorsUT::test_ut_pass", testFilePath, 9),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestRelativeImport() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "RelativeImport"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "relativeimportpackage\\test_relative_import.py");
var expectedTests = new[] {
new TestInfo(
"test_relative_import",
"relativeimportpackage\\test_relative_import.py::RelativeImportTests::test_relative_import",
testFilePath,
5
),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnittestInheritance() {
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "Inheritance"), testEnv.SourceFolderPath);
var baseTestFilePath = Path.Combine(testEnv.SourceFolderPath, "test_base.py");
var derivedTestFilePath = Path.Combine(testEnv.SourceFolderPath, "test_derived.py");
var expectedTests = new[] {
new TestInfo("test_base_pass", "test_base.py::BaseClassTests::test_base_pass", baseTestFilePath, 4),
new TestInfo("test_base_fail", "test_base.py::BaseClassTests::test_base_fail", baseTestFilePath, 7),
// TODO: investigate potential bug in product code,
// file name incorrect for these two, should be in baseTestFilePath
new TestInfo("test_base_pass", "test_derived.py::DerivedClassTests::test_base_pass", derivedTestFilePath, 4),
new TestInfo("test_base_fail", "test_derived.py::DerivedClassTests::test_base_fail", derivedTestFilePath, 7),
new TestInfo("test_derived_pass", "test_derived.py::DerivedClassTests::test_derived_pass", derivedTestFilePath, 5),
new TestInfo("test_derived_fail", "test_derived.py::DerivedClassTests::test_derived_fail", derivedTestFilePath, 8),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFilesFromFolder(testEnv.SourceFolderPath)
.ToXml()
);
DiscoverTests(testEnv, new[] { baseTestFilePath, derivedTestFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverUnitTestWarnings() {
// one file has a valid passing test,
// the other has an unknown module import at global scope
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkUnittest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "Warnings"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_warnings.py");
var expectedTests = new[] {
new TestInfo("test_A", "test_warnings.py::Test_WarnClass::test_A", testFilePath, 6),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
[TestMethod, Priority(UnitTestPriority.P1)]
[TestCategory("10s")]
public void DiscoverPytestWarnings() {
// one file has a valid passing test,
// the other has an unknown module import at global scope
var testEnv = TestEnvironment.GetOrCreate(Version, FrameworkPytest);
FileUtils.CopyDirectory(TestData.GetPath("TestData", "TestDiscoverer", "Warnings"), testEnv.SourceFolderPath);
var testFilePath = Path.Combine(testEnv.SourceFolderPath, "test_warnings.py");
var expectedTests = new[] {
new TestInfo("test_A", "test_warnings.py::Test_WarnClass::test_A", testFilePath, 6),
};
var runSettings = new MockRunSettings(
new MockRunSettingsXmlBuilder(testEnv.TestFramework, testEnv.InterpreterPath, testEnv.ResultsFolderPath, testEnv.SourceFolderPath)
.WithTestFile(testFilePath)
.ToXml()
);
DiscoverTests(testEnv, new[] { testFilePath }, runSettings, expectedTests);
}
private static void DiscoverTests(TestEnvironment testEnv, string[] sources, MockRunSettings runSettings, TestInfo[] expectedTests) {
var discoveryContext = new MockDiscoveryContext(runSettings);
var discoverySink = new MockTestCaseDiscoverySink();
var logger = new MockMessageLogger();
ITestDiscoverer discoverer = null;
switch (testEnv.TestFramework) {
case FrameworkPytest:
discoverer = new PytestTestDiscoverer();
break;
case FrameworkUnittest:
discoverer = new UnittestTestDiscoverer();
break;
default:
Assert.Fail($"unknown testframework: {testEnv.TestFramework.ToString()}");
break;
}
discoverer.DiscoverTests(sources, discoveryContext, logger, discoverySink);
ValidateDiscoveredTests(testEnv.TestFramework, discoverySink.Tests, expectedTests);
}
private static void ValidateDiscoveredTests(string testFramework, IList<TestCase> actualTests, TestInfo[] expectedTests) {
PrintTestCases(actualTests);
Assert.AreEqual(expectedTests.Length, actualTests.Count);
foreach (var expectedTest in expectedTests) {
var actualTestCase = actualTests.SingleOrDefault(tc => tc.FullyQualifiedName == expectedTest.FullyQualifiedName);
Assert.IsNotNull(actualTestCase, expectedTest.FullyQualifiedName);
switch (testFramework) {
case FrameworkPytest:
Assert.AreEqual(new Uri(PythonConstants.PytestExecutorUriString), actualTestCase.ExecutorUri);
break;
case FrameworkUnittest:
Assert.AreEqual(new Uri(PythonConstants.UnitTestExecutorUriString), actualTestCase.ExecutorUri);
break;
default:
Assert.Fail($"Unexpected test framework: {testFramework}");
break;
}
Assert.AreEqual(expectedTest.DisplayName, actualTestCase.DisplayName, expectedTest.FullyQualifiedName);
Assert.IsTrue(IsSameFile(expectedTest.FilePath, actualTestCase.CodeFilePath), expectedTest.FullyQualifiedName);
if (expectedTest.LineNumber > 0) {
Assert.AreEqual(expectedTest.LineNumber, actualTestCase.LineNumber, expectedTest.FullyQualifiedName);
}
}
}
private static bool IsSameFile(string a, string b) {
return String.Compare(new FileInfo(a).FullName, new FileInfo(b).FullName, StringComparison.CurrentCultureIgnoreCase) == 0;
}
private static void PrintTestCases(IEnumerable<TestCase> testCases) {
Console.WriteLine("Discovered test cases:");
Console.WriteLine("----------------------");
foreach (var tst in testCases) {
Console.WriteLine($"FullyQualifiedName: {tst.FullyQualifiedName}");
Console.WriteLine($"Source: {tst.Source}");
Console.WriteLine($"Display: {tst.DisplayName}");
Console.WriteLine($"CodeFilePath: {tst.CodeFilePath}");
Console.WriteLine($"LineNumber: {tst.LineNumber.ToString()}");
Console.WriteLine($"PytestId: {tst.GetPropertyValue<string>(Microsoft.PythonTools.TestAdapter.Pytest.Constants.PytestIdProperty, null)}");
Console.WriteLine("");
}
}
}
[TestClass]
[Ignore]
public class TestDiscovererTests27 : TestDiscovererTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
protected override PythonVersion Version => PythonPaths.Python27_x64 ?? PythonPaths.Python27;
protected override string ImportErrorFormat => "ImportError: No module named {0}";
}
[TestClass]
public class TestDiscovererTests35 : TestDiscovererTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
protected override PythonVersion Version => PythonPaths.Python35_x64 ?? PythonPaths.Python35;
protected override string ImportErrorFormat => "ImportError: No module named '{0}'";
}
[TestClass]
public class TestDiscovererTestsLatest : TestDiscovererTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
protected override PythonVersion Version => PythonPaths.LatestVersion;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.GoogleMaps;
using System.Reflection;
namespace XFGoogleMapSample
{
public partial class CustomPinsPage : ContentPage
{
bool _dirty;
// default marker colors
readonly Tuple<string, Color>[] _colors =
{
new Tuple<string, Color>("Green", Color.Green),
new Tuple<string, Color>("Pink", Color.Pink),
new Tuple<string, Color>("Aqua", Color.Aqua)
};
// bundle(Android:Asset, iOS:Bundle) images
readonly string[] _bundles =
{
"image01.png",
"image02.png",
"image03.png"
};
// PCL side embedded resources
readonly string[] _streams =
{
"marker01.png",
"marker02.png",
"marker03.png"
};
// The pin
readonly Pin _pinTokyo = new Pin()
{
Type = PinType.Place,
Label = "Tokyo SKYTREE",
Address = "Sumida-ku, Tokyo, Japan",
Position = new Position(35.71d, 139.81d)
};
// The second pin
readonly Pin _pinTokyo2 = new Pin()
{
Icon = BitmapDescriptorFactory.DefaultMarker(Color.Gray),
Type = PinType.Place,
Label = "Second Pin",
Position = new Position(35.71d, 139.815d),
ZIndex = 5
};
public CustomPinsPage()
{
InitializeComponent();
// Switch contols as toggle
var switches = new Switch[] { switchPinColor, switchPinBundle, switchPinStream };
foreach (var sw in switches)
{
sw.Toggled += (sender, e) =>
{
if (!e.Value || _dirty)
return;
_dirty = true;
foreach (var s in switches)
{
if (!object.ReferenceEquals(s, sender))
s.IsToggled = false;
}
_dirty = false;
UpdatePinIcon();
};
}
// Default colors
foreach (var c in _colors)
{
buttonPinColor.Items.Add(c.Item1);
}
buttonPinColor.SelectedIndexChanged += (_, e) =>
{
buttonPinColor.BackgroundColor = _colors[buttonPinColor.SelectedIndex].Item2;
UpdatePinIcon();
};
buttonPinColor.SelectedIndex = 0;
// Bundle Images
foreach (var bundle in _bundles)
{
buttonPinBundle.Items.Add(bundle);
}
buttonPinBundle.SelectedIndexChanged += (_, e) =>
{
UpdatePinIcon();
};
buttonPinBundle.SelectedIndex = 0;
// Stream Images
foreach (var stream in _streams)
{
buttonPinStream.Items.Add(stream);
}
buttonPinStream.SelectedIndexChanged += (_, e) =>
{
UpdatePinIcon();
};
buttonPinStream.SelectedIndex = 0;
// Set to null
buttonPinSetToNull.Clicked += (sender, e) =>
{
_pinTokyo.Icon = null;
foreach (var sw in switches)
{
sw.IsToggled = false;
}
};
// Pin Draggable
switchIsDraggable.Toggled += (sender, e) =>
{
_pinTokyo.IsDraggable = switchIsDraggable.IsToggled;
};
switchFlat.Toggled += (sender, e) =>
{
_pinTokyo.Flat = switchFlat.IsToggled;
};
// Pin Rotation
sliderRotation.ValueChanged += (sender, e) =>
{
_pinTokyo.Rotation = (float)e.NewValue;
if (_pinTokyo.Rotation>= 0 && _pinTokyo.Rotation <= 60)
{
_pinTokyo.InfoWindowAnchor = new Point(0.5, 0.0);
}
if (_pinTokyo.Rotation > 60 && _pinTokyo.Rotation <= 120)
{
_pinTokyo.InfoWindowAnchor = new Point(0.0, 0.5);
}
if (_pinTokyo.Rotation > 120 && _pinTokyo.Rotation <= 210)
{
_pinTokyo.InfoWindowAnchor = new Point(0.5, 1.0);
}
if (_pinTokyo.Rotation > 210 && _pinTokyo.Rotation < 270)
{
_pinTokyo.InfoWindowAnchor = new Point(1.0, 0.25);
}
if (_pinTokyo.Rotation > 270 && _pinTokyo.Rotation < 360)
{
_pinTokyo.InfoWindowAnchor = new Point(0.5, 0.0);
}
};
// ZIndex
buttonMoveToFront.Clicked += (sender, e) =>
{
map.SelectedPin = null;
_pinTokyo.ZIndex = _pinTokyo2.ZIndex + 1;
};
buttonMoveToBack.Clicked += (sender, e) =>
{
map.SelectedPin = null;
_pinTokyo.ZIndex = _pinTokyo2.ZIndex - 1;
};
map.PinDragStart += (_, e) => labelDragStatus.Text = $"DragStart - {PrintPin(e.Pin)}";
map.PinDragging += (_, e) => labelDragStatus.Text = $"Dragging - {PrintPin(e.Pin)}";
map.PinDragEnd += (_, e) => labelDragStatus.Text = $"DragEnd - {PrintPin(e.Pin)}";
switchIsDraggable.IsToggled = true;
switchPinColor.IsToggled = true;
_pinTokyo.IsDraggable = true;
map.Pins.Add(_pinTokyo);
map.Pins.Add(_pinTokyo2);
map.SelectedPin = _pinTokyo;
map.MoveToRegion(MapSpan.FromCenterAndRadius(_pinTokyo.Position, Distance.FromMeters(5000)), true);
}
private string PrintPin(Pin pin)
{
return $"{pin.Label}({pin.Position.Latitude.ToString("0.000")},{pin.Position.Longitude.ToString("0.000")})";
}
protected override void OnAppearing()
{
base.OnAppearing();
}
void UpdatePinIcon()
{
if (switchPinColor.IsToggled)
{
_pinTokyo.Icon = BitmapDescriptorFactory.DefaultMarker(_colors[buttonPinColor.SelectedIndex].Item2);
}
else if (switchPinBundle.IsToggled)
{
_pinTokyo.Icon = BitmapDescriptorFactory.FromBundle(buttonPinBundle.Items[buttonPinBundle.SelectedIndex]);
}
else if (switchPinStream.IsToggled)
{
var assembly = typeof(CustomPinsPage).GetTypeInfo().Assembly;
var file = buttonPinStream.Items[buttonPinStream.SelectedIndex];
var stream = assembly.GetManifestResourceStream($"XFGoogleMapSample.{file}");
_pinTokyo.Icon = BitmapDescriptorFactory.FromStream(stream);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
/// <summary>
/// Wraps IGridCache implementation to simplify async mode testing.
/// </summary>
internal class CacheTestAsyncWrapper<TK, TV> : ICache<TK, TV>
{
private readonly ICache<TK, TV> _cache;
/// <summary>
/// Initializes a new instance of the <see cref="CacheTestAsyncWrapper{K, V}"/> class.
/// </summary>
/// <param name="cache">The cache to be wrapped.</param>
public CacheTestAsyncWrapper(ICache<TK, TV> cache)
{
Debug.Assert(cache != null);
_cache = cache;
}
/** <inheritDoc /> */
public string Name
{
get { return _cache.Name; }
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _cache.Ignite; }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return _cache.GetConfiguration();
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return _cache.IsEmpty();
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _cache.IsKeepBinary; }
}
/** <inheritDoc /> */
public bool IsAllowAtomicOpsInTx {
get { return _cache.IsAllowAtomicOpsInTx; }
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
return _cache.WithSkipStore().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
return _cache.WithExpiryPolicy(plc).WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
return _cache.WithKeepBinary<TK1, TV1>().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithAllowAtomicOpsInTx()
{
return _cache.WithAllowAtomicOpsInTx().WrapAsync();
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LoadCacheAsync(p, args).WaitResult();
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
_cache.LocalLoadCacheAsync(p, args).WaitResult();
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LocalLoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
_cache.LoadAll(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return _cache.LoadAllAsync(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
return _cache.ContainsKeyAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
return _cache.ContainsKeyAsync(key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys);
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
return _cache.LocalPeek(key, modes);
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
return _cache.TryLocalPeek(key, out value, modes);
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return _cache[key]; }
set { _cache[key] = value; }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
return _cache.GetAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
return _cache.GetAsync(key);
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
return _cache.TryGet(key, out value);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
return _cache.TryGetAsync(key);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys).GetResult();
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys);
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
_cache.PutAsync(key, val).WaitResult();
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
return _cache.PutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
return _cache.GetAndRemoveAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
return _cache.GetAndRemoveAsync(key);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
return _cache.ReplaceAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
return _cache.ReplaceAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal).GetResult();
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal);
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
_cache.PutAllAsync(vals).WaitResult();
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
return _cache.PutAllAsync(vals);
}
/** <inheritDoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
_cache.LocalEvict(keys);
}
/** <inheritDoc /> */
public void Clear()
{
_cache.ClearAsync().WaitResult();
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return _cache.ClearAsync();
}
/** <inheritDoc /> */
public void Clear(TK key)
{
_cache.ClearAsync(key).WaitResult();
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
return _cache.ClearAsync(key);
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
_cache.ClearAllAsync(keys).WaitResult();
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
return _cache.ClearAllAsync(keys);
}
/** <inheritDoc /> */
public void LocalClear(TK key)
{
_cache.LocalClear(key);
}
/** <inheritDoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
_cache.LocalClearAll(keys);
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
return _cache.RemoveAsync(key).GetResult();
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
return _cache.RemoveAsync(key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
return _cache.RemoveAsync(key, val).GetResult();
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
return _cache.RemoveAsync(key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
Task task = _cache.RemoveAllAsync(keys);
task.WaitResult();
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
return _cache.RemoveAllAsync(keys);
}
/** <inheritDoc /> */
public void RemoveAll()
{
Task task = _cache.RemoveAllAsync();
task.WaitResult();
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return _cache.RemoveAllAsync();
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return _cache.GetLocalSize(modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes).GetResult();
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
public IFieldsQueryCursor Query(SqlFieldsQuery qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
[Obsolete]
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return _cache.QueryFields(qry);
}
/** <inheritDoc /> */
IContinuousQueryHandle ICache<TK, TV>.QueryContinuous(ContinuousQuery<TK, TV> qry)
{
return _cache.QueryContinuous(qry);
}
/** <inheritDoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
return _cache.QueryContinuous(qry, initialQry);
}
/** <inheritDoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(params CachePeekMode[] peekModes)
{
return _cache.GetLocalEntries(peekModes);
}
/** <inheritDoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg).GetResult();
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg);
}
/** <inheritDoc /> */
public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg).GetResult();
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg);
}
/** <inheritDoc /> */
public ICacheLock Lock(TK key)
{
return _cache.Lock(key);
}
/** <inheritDoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
return _cache.LockAll(keys);
}
/** <inheritDoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
return _cache.IsLocalLocked(key, byCurrentThread);
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return _cache.GetMetrics();
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
return _cache.GetMetrics(clusterGroup);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return _cache.GetLocalMetrics();
}
/** <inheritDoc /> */
public Task Rebalance()
{
return _cache.Rebalance();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
return _cache.WithNoRetries();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithPartitionRecover()
{
return _cache.WithPartitionRecover();
}
/** <inheritDoc /> */
public ICollection<int> GetLostPartitions()
{
return _cache.GetLostPartitions();
}
/** <inheritDoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return _cache.GetEnumerator();
}
/** <inheritDoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IQueryMetrics GetQueryMetrics()
{
return _cache.GetQueryMetrics();
}
public void ResetQueryMetrics()
{
_cache.ResetQueryMetrics();
}
}
/// <summary>
/// Extension methods for IGridCache.
/// </summary>
public static class CacheExtensions
{
/// <summary>
/// Wraps specified instance into GridCacheTestAsyncWrapper.
/// </summary>
public static ICache<TK, TV> WrapAsync<TK, TV>(this ICache<TK, TV> cache)
{
return new CacheTestAsyncWrapper<TK, TV>(cache);
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Xamarin.Forms.Platform;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms
{
[ContentProperty("Root")]
[RenderWith(typeof(_TableViewRenderer))]
public class TableView : View, ITableViewController, IElementConfiguration<TableView>
{
public static readonly BindableProperty RowHeightProperty = BindableProperty.Create("RowHeight", typeof(int), typeof(TableView), -1);
public static readonly BindableProperty HasUnevenRowsProperty = BindableProperty.Create("HasUnevenRows", typeof(bool), typeof(TableView), false);
readonly Lazy<PlatformConfigurationRegistry<TableView>> _platformConfigurationRegistry;
readonly TableSectionModel _tableModel;
TableIntent _intent = TableIntent.Data;
TableModel _model;
public TableView() : this(null)
{
}
public TableView(TableRoot root)
{
VerticalOptions = HorizontalOptions = LayoutOptions.FillAndExpand;
Model = _tableModel = new TableSectionModel(this, root);
_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<TableView>>(() => new PlatformConfigurationRegistry<TableView>(this));
}
public bool HasUnevenRows
{
get { return (bool)GetValue(HasUnevenRowsProperty); }
set { SetValue(HasUnevenRowsProperty, value); }
}
public TableIntent Intent
{
get { return _intent; }
set
{
if (_intent == value)
return;
OnPropertyChanging();
_intent = value;
OnPropertyChanged();
}
}
public TableRoot Root
{
get { return _tableModel.Root; }
set
{
if (_tableModel.Root != null)
{
_tableModel.Root.SectionCollectionChanged -= OnSectionCollectionChanged;
_tableModel.Root.PropertyChanged -= OnTableModelRootPropertyChanged;
}
_tableModel.Root = value ?? new TableRoot();
SetInheritedBindingContext(_tableModel.Root, BindingContext);
Root.SelectMany(r => r).ForEach(cell => cell.Parent = this);
_tableModel.Root.SectionCollectionChanged += OnSectionCollectionChanged;
_tableModel.Root.PropertyChanged += OnTableModelRootPropertyChanged;
OnModelChanged();
}
}
public int RowHeight
{
get { return (int)GetValue(RowHeightProperty); }
set { SetValue(RowHeightProperty, value); }
}
internal TableModel Model
{
get { return _model; }
set
{
_model = value;
OnModelChanged();
}
}
ITableModel ITableViewController.Model
{
get
{
return Model;
}
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
if (Root != null)
SetInheritedBindingContext(Root, BindingContext);
}
protected virtual void OnModelChanged()
{
foreach (Cell cell in Root.SelectMany(r => r))
cell.Parent = this;
if (ModelChanged != null)
ModelChanged(this, EventArgs.Empty);
}
[Obsolete("Use OnMeasure")]
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
var minimumSize = new Size(40, 40);
double width = Math.Min(Device.Info.ScaledScreenSize.Width, Device.Info.ScaledScreenSize.Height);
var request = new Size(width, Math.Max(Device.Info.ScaledScreenSize.Width, Device.Info.ScaledScreenSize.Height));
return new SizeRequest(request, minimumSize);
}
internal event EventHandler ModelChanged;
event EventHandler ITableViewController.ModelChanged
{
add { ModelChanged += value; }
remove { ModelChanged -= value; }
}
public IPlatformElementConfiguration<T, TableView> On<T>() where T : IConfigPlatform
{
return _platformConfigurationRegistry.Value.On<T>();
}
void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
OnModelChanged();
}
void OnSectionCollectionChanged(object sender, ChildCollectionChangedEventArgs childCollectionChangedEventArgs)
{
if (childCollectionChangedEventArgs.Args.NewItems != null)
childCollectionChangedEventArgs.Args.NewItems.Cast<Cell>().ForEach(cell => cell.Parent = this);
OnModelChanged();
}
void OnTableModelRootPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == TableSectionBase.TitleProperty.PropertyName)
OnModelChanged();
}
internal class TableSectionModel : TableModel
{
static readonly BindableProperty PathProperty = BindableProperty.Create("Path", typeof(Tuple<int, int>), typeof(Cell), null);
readonly TableView _parent;
TableRoot _root;
public TableSectionModel(TableView tableParent, TableRoot tableRoot)
{
_parent = tableParent;
Root = tableRoot ?? new TableRoot();
}
public TableRoot Root
{
get { return _root; }
set
{
if (_root == value)
return;
RemoveEvents(_root);
_root = value;
ApplyEvents(_root);
}
}
public override Cell GetCell(int section, int row)
{
var cell = (Cell)GetItem(section, row);
SetPath(cell, new Tuple<int, int>(section, row));
return cell;
}
public override object GetItem(int section, int row)
{
return _root[section][row];
}
public override int GetRowCount(int section)
{
return _root[section].Count;
}
public override int GetSectionCount()
{
return _root.Count;
}
public override string GetSectionTitle(int section)
{
return _root[section].Title;
}
protected override void OnRowSelected(object item)
{
base.OnRowSelected(item);
((Cell)item).OnTapped();
}
internal static Tuple<int, int> GetPath(Cell item)
{
if (item == null)
throw new ArgumentNullException("item");
return (Tuple<int, int>)item.GetValue(PathProperty);
}
void ApplyEvents(TableRoot tableRoot)
{
tableRoot.CollectionChanged += _parent.CollectionChanged;
tableRoot.SectionCollectionChanged += _parent.OnSectionCollectionChanged;
}
void RemoveEvents(TableRoot tableRoot)
{
if (tableRoot == null)
return;
tableRoot.CollectionChanged -= _parent.CollectionChanged;
tableRoot.SectionCollectionChanged -= _parent.OnSectionCollectionChanged;
}
static void SetPath(Cell item, Tuple<int, int> index)
{
if (item == null)
return;
item.SetValue(PathProperty, index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml.Schema;
using System.Xml.XPath;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_Misc", Desc = "")]
public class TC_SchemaSet_Misc : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_Misc(ITestOutputHelper output)
{
_output = output;
}
public bool bWarningCallback;
public bool bErrorCallback;
public int errorCount;
public int warningCount;
public bool WarningInnerExceptionSet = false;
public bool ErrorInnerExceptionSet = false;
public void Initialize()
{
bWarningCallback = bErrorCallback = false;
errorCount = warningCount = 0;
WarningInnerExceptionSet = ErrorInnerExceptionSet = false;
}
//hook up validaton callback
public void ValidationCallback(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
_output.WriteLine("WARNING: ");
bWarningCallback = true;
warningCount++;
WarningInnerExceptionSet = (args.Exception.InnerException != null);
_output.WriteLine("\nInnerExceptionSet : " + WarningInnerExceptionSet + "\n");
}
else if (args.Severity == XmlSeverityType.Error)
{
_output.WriteLine("ERROR: ");
bErrorCallback = true;
errorCount++;
ErrorInnerExceptionSet = (args.Exception.InnerException != null);
_output.WriteLine("\nInnerExceptionSet : " + ErrorInnerExceptionSet + "\n");
}
_output.WriteLine(args.Message); // Print the error to the screen.
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - Bug110823 - SchemaSet.Add is holding onto some of the schema files after adding", Priority = 1)]
[InlineData()]
[Theory]
public void v1()
{
XmlSchemaSet xss = new XmlSchemaSet();
xss.XmlResolver = new XmlUrlResolver();
using (XmlTextReader xtr = new XmlTextReader(Path.Combine(TestData._Root, "bug110823.xsd")))
{
xss.Add(XmlSchema.Read(xtr, null));
}
}
//[Variation(Desc = "v2 - Bug115049 - XSD: content model validation for an invalid root element should be adandoned", Priority = 2)]
[InlineData()]
[Theory]
public void v2()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(null, Path.Combine(TestData._Root, "bug115049.xsd"));
ss.Compile();
//create reader
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.Schemas.Add(ss);
XmlReader vr = XmlReader.Create(Path.Combine(TestData._Root, "bug115049.xml"), settings);
while (vr.Read()) ;
CError.Compare(errorCount, 1, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v4 - 243300 - We are not correctly handling xs:anyType as xsi:type in the instance", Priority = 2)]
[InlineData()]
[Theory]
public void v4()
{
string xml = @"<a xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xsi:type='xsd:anyType'>1242<b/></a>";
Initialize();
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlReader vr = XmlReader.Create(new StringReader(xml), settings, (string)null);
while (vr.Read()) ;
CError.Compare(errorCount, 0, "Error Count mismatch!");
CError.Compare(warningCount, 1, "Warning Count mismatch!");
return;
}
/* Parameters = file name , is custom xml namespace System.Xml.Tests */
//[Variation(Desc = "v20 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v10.xsd", 2, false })]
[InlineData("bug264908_v10.xsd", 2, false)]
//[Variation(Desc = "v19 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v9.xsd", 5, true })]
[InlineData("bug264908_v9.xsd", 5, true)]
//[Variation(Desc = "v18 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v8.xsd", 5, false })]
[InlineData("bug264908_v8.xsd", 5, false)]
//[Variation(Desc = "v17 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v7.xsd", 4, false })]
[InlineData("bug264908_v7.xsd", 4, false)]
//[Variation(Desc = "v16 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v6.xsd", 4, true })]
[InlineData("bug264908_v6.xsd", 4, true)]
//[Variation(Desc = "v15 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v5.xsd", 4, false })]
[InlineData("bug264908_v5.xsd", 4, false)]
//[Variation(Desc = "v14 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v4.xsd", 4, true })]
[InlineData("bug264908_v4.xsd", 4, true)]
//[Variation(Desc = "v13 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v3.xsd", 1, true })]
[InlineData("bug264908_v3.xsd", 1, true)]
//[Variation(Desc = "v12 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v2.xsd", 1, true })]
[InlineData("bug264908_v2.xsd", 1, true)]
//[Variation(Desc = "v11 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v1.xsd", 3, true })]
[InlineData("bug264908_v1.xsd", 3, true)]
[Theory]
public void v10(object param0, object param1, object param2)
{
string xmlFile = param0.ToString();
int count = (int)param1;
bool custom = (bool)param2;
string attName = "blah";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(null, Path.Combine(TestData._Root, xmlFile));
ss.Compile();
//test the count
CError.Compare(ss.Count, count, "Count of SchemaSet not matched!");
//make sure the correct schema is in the set
if (custom)
{
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
return;
}
Assert.True(false);
}
return;
}
//[Variation(Desc = "v21 - Bug 319346 - Chameleon add of a schema into the xml namespace", Priority = 1)]
[InlineData()]
[Theory]
public void v20()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
string attName = "blah";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(xmlns, Path.Combine(TestData._Root, "bug264908_v11.xsd"));
ss.Compile();
//test the count
CError.Compare(ss.Count, 3, "Count of SchemaSet not matched!");
//make sure the correct schema is in the set
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
return;
}
Assert.True(false);
}
//[Variation(Desc = "v22 - Bug 338038 - Component should be additive into the Xml namespace", Priority = 1)]
[InlineData()]
[Theory]
public void v21()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
string attName = "blah1";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v1.xsd"));
ss.Compile();
//test the count
CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!");
//make sure the correct schema is in the set
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
return;
}
Assert.True(false);
}
//[Variation(Desc = "v23 - Bug 338038 - Conflicting components in custome xml namespace System.Xml.Tests be caught", Priority = 1)]
[InlineData()]
[Theory]
public void v22()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v2.xsd"));
try
{
ss.Compile();
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!");
return;
}
Assert.True(false);
}
//[Variation(Desc = "v24 - Bug 338038 - Change type of xml:lang to decimal in custome xml namespace System.Xml.Tests", Priority = 1)]
[InlineData()]
[Theory]
public void v24()
{
string attName = "lang";
string newtype = "decimal";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd"));
ss.Compile();
CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!");
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == attName)
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, newtype, "Incorrect type for xml:lang");
return;
}
}
Assert.True(false);
}
//[Variation(Desc = "v25 - Bug 338038 - Conflicting definitions for xml attributes in two schemas", Priority = 1)]
[InlineData()]
[Theory]
public void v25()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd"));
ss.Compile();
try
{
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3b.xsd"));
ss.Compile();
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.Message);
CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!");
return;
}
Assert.True(false);
}
//[Variation(Desc = "v26 - Bug 338038 - Change type of xml:lang to decimal and xml:base to short in two steps", Priority = 1)]
[InlineData()]
[Theory]
public void v26()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4b.xsd"));
ss.Compile();
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == "lang")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "decimal", "Incorrect type for xml:lang");
}
if (a.QualifiedName.Name == "base")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "short", "Incorrect type for xml:base");
}
}
CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!");
return;
}
//[Variation(Desc = "v27 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests", Priority = 1)]
[InlineData()]
[Theory]
public void v27()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd"));
ss.Compile();
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == "blah")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang");
}
}
CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!");
return;
}
//[Variation(Desc = "v28 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests, remove default ns schema", Priority = 1)]
[InlineData()]
[Theory]
public void v28()
{
string xmlns = @"http://www.w3.org/XML/1998/namespace";
XmlSchema schema = null;
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd"));
ss.Compile();
foreach (XmlSchema s in ss.Schemas(xmlns))
{
schema = s;
}
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd"));
ss.Compile();
ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd"));
ss.Compile();
ss.Remove(schema);
ss.Compile();
foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values)
{
if (a.QualifiedName.Name == "blah")
{
CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang");
}
}
CError.Compare(ss.Count, 5, "Count of SchemaSet not matched!");
return;
}
//Regressions - Bug Fixes
public void Callback1(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
_output.WriteLine("WARNING Recieved");
bWarningCallback = true;
warningCount++;
CError.Compare(args.Exception.InnerException == null, false, "Inner Exception not set");
}
}
//[Variation(Desc = "v100 - Bug 320502 - XmlSchemaSet: while throwing a warning for invalid externals we do not set the inner exception", Priority = 1)]
[InlineData()]
[Theory]
public void v100()
{
string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:include schemaLocation='bogus'/></xs:schema>";
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(Callback1);
ss.Add(null, new XmlTextReader(new StringReader(xsd)));
ss.Compile();
CError.Compare(warningCount, 1, "Warning Count mismatch!");
return;
}
//[Variation(Desc = "v101 - Bug 339706 - XmlSchemaSet: Compile on the set fails when a compiled schema containing notation is already present", Priority = 1)]
[InlineData()]
[Theory]
public void v101()
{
string xsd1 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:notation name='a' public='a'/></xs:schema>";
string xsd2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='root'/></xs:schema>";
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(Callback1);
ss.Add(null, new XmlTextReader(new StringReader(xsd1)));
ss.Compile();
ss.Add(null, new XmlTextReader(new StringReader(xsd2)));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v102 - Bug 337850 - XmlSchemaSet: Type already declared error when redefined schema is added to the set before the redefining schema.", Priority = 1)]
[InlineData()]
[Theory]
public void v102()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(null, Path.Combine(TestData._Root, "schZ013c.xsd"));
ss.Add(null, Path.Combine(TestData._Root, "schZ013a.xsd"));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v104 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled SOM.", Priority = 1, Params = new object[] { false })]
[InlineData(false)]
//[Variation(Desc = "v103 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled set.", Priority = 1, Params = new object[] { true })]
[InlineData(true)]
[Theory]
public void v103(object param0)
{
bool addset = (bool)param0;
Initialize();
XmlSchemaSet ss1 = new XmlSchemaSet();
ss1.XmlResolver = new XmlUrlResolver();
ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss1.Add(null, Path.Combine(TestData._Root, "Misc103_x.xsd"));
ss1.Compile();
CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!");
XmlSchemaSet ss2 = new XmlSchemaSet();
ss2.XmlResolver = new XmlUrlResolver();
ss2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema s = ss2.Add(null, Path.Combine(TestData._Root, "Misc103_a.xsd"));
ss2.Compile();
CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!");
if (addset)
{
ss1.Add(ss2);
CError.Compare(ss1.GlobalElements.Count, 7, "Schema Set 1 GlobalElements Count mismatch!");
CError.Compare(ss1.GlobalAttributes.Count, 2, "Schema Set 1 GlobalAttributes Count mismatch!");
CError.Compare(ss1.GlobalTypes.Count, 6, "Schema Set 1 GlobalTypes Count mismatch!");
}
else
{
ss1.Add(s);
CError.Compare(ss1.GlobalElements.Count, 2, "Schema Set 1 GlobalElements Count mismatch!");
CError.Compare(ss1.GlobalAttributes.Count, 0, "Schema Set 1 GlobalAttributes Count mismatch!");
CError.Compare(ss1.GlobalTypes.Count, 2, "Schema Set 1 GlobalTypes Count mismatch!");
}
/***********************************************/
XmlSchemaSet ss3 = new XmlSchemaSet();
ss3.XmlResolver = new XmlUrlResolver();
ss3.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss3.Add(null, Path.Combine(TestData._Root, "Misc103_c.xsd"));
ss3.Compile();
ss1.Add(ss3);
CError.Compare(ss1.GlobalElements.Count, 8, "Schema Set 1 GlobalElements Count mismatch!");
return;
}
//[Variation(Desc = "v103 - Reference to a component from no namespace System.Xml.Tests an explicit import of no namespace System.Xml.Tests throw a validation warning", Priority = 1)]
[InlineData()]
[Theory]
public void v105()
{
Initialize();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(null, Path.Combine(TestData._Root, "Misc105.xsd"));
CError.Compare(warningCount, 1, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v106 - Adding a compiled SoS(schema for schema) to a set causes type collision error", Priority = 1)]
[InlineData()]
[Theory]
public void v106()
{
Initialize();
XmlSchemaSet ss1 = new XmlSchemaSet();
ss1.XmlResolver = new XmlUrlResolver();
ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlReaderSettings settings = new XmlReaderSettings();
#pragma warning disable 0618
settings.ProhibitDtd = false;
#pragma warning restore 0618
XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "XMLSchema.xsd"), settings);
ss1.Add(null, r);
ss1.Compile();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
foreach (XmlSchema s in ss1.Schemas())
{
ss.Add(s);
}
ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd"));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v107 - XsdValidatingReader: InnerException not set on validation warning of a schemaLocation not loaded.", Priority = 1)]
[InlineData()]
[Theory]
public void v107()
{
string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='a bug356711_a.xsd' xmlns:a='a'></root>";
Initialize();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd"));
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.Schemas.Add(schemaSet);
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.ValidationType = ValidationType.Schema;
XmlReader vr = XmlReader.Create(new StringReader(strXml), settings);
while (vr.Read()) ;
CError.Compare(warningCount, 1, "Warning Count mismatch!");
CError.Compare(WarningInnerExceptionSet, true, "Inner Exception not set!");
return;
}
//[Variation(Desc = "v108 - XmlSchemaSet.Add() should not trust compiled state of the schema being added", Priority = 1)]
[InlineData()]
[Theory]
public void v108()
{
string strSchema1 = @"
<xs:schema targetNamespace='http://bar'
xmlns='http://bar' xmlns:x='http://foo'
elementFormDefault='qualified'
attributeFormDefault='unqualified'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:import namespace='http://foo'/>
<xs:element name='bar'>
<xs:complexType>
<xs:sequence>
<xs:element ref='x:foo'/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
";
string strSchema2 = @"<xs:schema targetNamespace='http://foo'
xmlns='http://foo' xmlns:x='http://bar'
elementFormDefault='qualified'
attributeFormDefault='unqualified'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:import namespace='http://bar'/>
<xs:element name='foo'>
<xs:complexType>
<xs:sequence>
<xs:element ref='x:bar'/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
Initialize();
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
ValidationEventHandler handler = new ValidationEventHandler(ValidationCallback);
set.ValidationEventHandler += handler;
XmlSchema s1 = null;
using (XmlReader r = XmlReader.Create(new StringReader(strSchema1)))
{
s1 = XmlSchema.Read(r, handler);
set.Add(s1);
}
set.Compile();
// Now load set 2
set = new XmlSchemaSet();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema s2 = null;
using (XmlReader r = XmlReader.Create(new StringReader(strSchema2)))
{
s2 = XmlSchema.Read(r, handler);
}
XmlSchemaImport import = (XmlSchemaImport)s2.Includes[0];
import.Schema = s1;
import = (XmlSchemaImport)s1.Includes[0];
import.Schema = s2;
set.Add(s1);
set.Reprocess(s1);
set.Add(s2);
set.Reprocess(s2);
set.Compile();
s2 = null;
using (XmlReader r = XmlReader.Create(new StringReader(strSchema2)))
{
s2 = XmlSchema.Read(r, handler);
}
set = new XmlSchemaSet();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
import = (XmlSchemaImport)s2.Includes[0];
import.Schema = s1;
import = (XmlSchemaImport)s1.Includes[0];
import.Schema = s2;
set.Add(s1);
set.Reprocess(s1);
set.Add(s2);
set.Reprocess(s2);
set.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch");
return;
}
//[Variation(Desc = "v109 - 386243, Adding a chameleon schema agsinst to no namaespace throws unexpected warnings", Priority = 1)]
[InlineData()]
[Theory]
public void v109()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
ss.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v110 - 386246, ArgumentException 'item arleady added' error on a chameleon add done twice", Priority = 1)]
[InlineData()]
[Theory]
public void v110()
{
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema s1 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
XmlSchema s2 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v111 - 380805, Chameleon include compiled in one set added to another", Priority = 1)]
[InlineData()]
[Theory]
public void v111()
{
Initialize();
XmlSchemaSet newSet = new XmlSchemaSet();
newSet.XmlResolver = new XmlUrlResolver();
newSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema chameleon = newSet.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd"));
newSet.Compile();
CError.Compare(newSet.GlobalTypes.Count, 10, "GlobalTypes count mismatch!");
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
sc.Add(chameleon);
sc.Add(null, Path.Combine(TestData._Root, "baseEmployee.xsd"));
sc.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v112 - 382035, schema set tables not cleared as expected on reprocess", Priority = 1)]
[InlineData()]
[Theory]
public void v112()
{
Initialize();
XmlSchemaSet set2 = new XmlSchemaSet();
set2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema includedSchema = set2.Add(null, Path.Combine(TestData._Root, "bug382035a1.xsd"));
set2.Compile();
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema mainSchema = set.Add(null, Path.Combine(TestData._Root, "bug382035a.xsd"));
set.Compile();
XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "bug382035a1.xsd"));
XmlSchema reParsedInclude = XmlSchema.Read(r, new ValidationEventHandler(ValidationCallback));
((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude;
set.Reprocess(mainSchema);
set.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "v113 - Set InnerException on XmlSchemaValidationException while parsing typed values", Priority = 1)]
[InlineData()]
[Theory]
public void v113()
{
string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema' xsi:type='xs:int'>a</root>";
Initialize();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.ValidationType = ValidationType.Schema;
XmlReader vr = XmlReader.Create(new StringReader(strXml), settings);
while (vr.Read()) ;
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch!");
CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!");
return;
}
//[Variation(Desc = "v114 - XmlSchemaSet: InnerException not set on parse errors during schema compilation", Priority = 1)]
[InlineData()]
[Theory]
public void v114()
{
string strXsd = @"<xs:schema elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='date' type='date'/>
<xs:simpleType name='date'>
<xs:restriction base='xs:int'>
<xs:enumeration value='a'/>
</xs:restriction>
</xs:simpleType>
</xs:schema>";
Initialize();
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(XmlSchema.Read(new StringReader(strXsd), new ValidationEventHandler(ValidationCallback)));
ss.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch!");
CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!");
return;
}
//[Variation(Desc = "v116 - 405327 NullReferenceExceptions while accessing obsolete properties in the SOM", Priority = 1)]
[InlineData()]
[Theory]
public void v116()
{
#pragma warning disable 0618
XmlSchemaAttribute attribute = new XmlSchemaAttribute();
Object attributeType = attribute.AttributeType;
XmlSchemaElement element = new XmlSchemaElement();
Object elementType = element.ElementType;
XmlSchemaType schemaType = new XmlSchemaType();
Object BaseSchemaType = schemaType.BaseSchemaType;
#pragma warning restore 0618
}
//[Variation(Desc = "v117 - 398474 InnerException not set on XmlSchemaException, when xs:pattern has an invalid regular expression", Priority = 1)]
[InlineData()]
[Theory]
public void v117()
{
string strXsdv117 =
@"<?xml version='1.0' encoding='utf-8' ?>
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='doc'>
<xs:complexType>
<xs:sequence>
<xs:element name='value' maxOccurs='unbounded'>
<xs:simpleType>
<xs:restriction base='xs:string'>
<xs:pattern value='(?r:foo)'/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
Initialize();
using (StringReader reader = new StringReader(strXsdv117))
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
ss.Add(XmlSchema.Read(reader, ValidationCallback));
ss.Compile();
CError.Compare(ErrorInnerExceptionSet, true, "\nInner Exception not set\n");
}
return;
}
//[Variation(Desc = "v118 - 424904 Not getting unhandled attributes on particle", Priority = 1)]
[InlineData()]
[Theory]
public void v118()
{
using (XmlReader r = new XmlTextReader(Path.Combine(TestData._Root, "Bug424904.xsd")))
{
XmlSchema s = XmlSchema.Read(r, null);
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.Add(s);
set.Compile();
XmlQualifiedName name = new XmlQualifiedName("test2", "http://foo");
XmlSchemaComplexType test2type = s.SchemaTypes[name] as XmlSchemaComplexType;
XmlSchemaParticle p = test2type.ContentTypeParticle;
XmlAttribute[] att = p.UnhandledAttributes;
Assert.False(att == null || att.Length < 1);
}
}
//[Variation(Desc = "v120 - 397633 line number and position not set on the validation error for an invalid xsi:type value", Priority = 1)]
[InlineData()]
[Theory]
public void v120()
{
using (XmlReader schemaReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xsd")))
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.Add("", schemaReader);
sc.Compile();
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = sc;
using (XmlReader docValidatingReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings))
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(docValidatingReader);
doc.Validate(null);
}
catch (XmlSchemaValidationException ex)
{
if (ex.LineNumber == 1 && ex.LinePosition == 2 && !String.IsNullOrEmpty(ex.SourceUri))
{
return;
}
}
}
}
Assert.True(false);
}
//[Variation(Desc = "v120a.XmlDocument.Load non-validating reader.Expect IOE.")]
[InlineData()]
[Theory]
public void v120a()
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
using (XmlReader reader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings))
{
XmlDocument doc = new XmlDocument();
try
{
doc.Load(reader);
doc.Validate(null);
}
catch (XmlSchemaValidationException ex)
{
_output.WriteLine(ex.Message);
return;
}
}
Assert.True(false);
}
//[Variation(Desc = "444196: XmlReader.MoveToNextAttribute returns incorrect results")]
[InlineData()]
[Theory]
public void v124()
{
Initialize();
string XamlPresentationNamespace =
"http://schemas.microsoft.com/winfx/2006/xaml/presentation";
string XamlToParse =
"<pfx0:DrawingBrush TileMode=\"Tile\" Viewbox=\"foobar\" />";
string xml =
" <xs:schema " +
" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
" targetNamespace=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
" elementFormDefault=\"qualified\" " +
" attributeFormDefault=\"unqualified\"" +
" >" +
"" +
" <xs:element name=\"DrawingBrush\" type=\"DrawingBrushType\" />" +
"" +
" <xs:complexType name=\"DrawingBrushType\">" +
" <xs:attribute name=\"Viewbox\" type=\"xs:string\" />" +
" <xs:attribute name=\"TileMode\" type=\"xs:string\" />" +
" </xs:complexType>" +
" </xs:schema>";
XmlSchema schema = XmlSchema.Read(new StringReader(xml), null);
schema.TargetNamespace = XamlPresentationNamespace;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.Add(schema);
schemaSet.Compile();
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = schemaSet;
NameTable nameTable = new NameTable();
XmlNamespaceManager namespaces = new XmlNamespaceManager(nameTable);
namespaces.AddNamespace("pfx0", XamlPresentationNamespace);
namespaces.AddNamespace(string.Empty, XamlPresentationNamespace);
XmlParserContext parserContext = new XmlParserContext(nameTable, namespaces, null, null, null, null, null, null, XmlSpace.None);
using (XmlReader xmlReader = XmlReader.Create(new StringReader(XamlToParse), readerSettings, parserContext))
{
xmlReader.Read();
xmlReader.MoveToAttribute(0);
xmlReader.MoveToNextAttribute();
xmlReader.MoveToNextAttribute();
xmlReader.MoveToNextAttribute();
xmlReader.MoveToAttribute(0);
if (xmlReader.MoveToNextAttribute())
return;
}
Assert.True(false);
}
//[Variation(Desc = "615444 XmlSchema.Write ((XmlWriter)null) throws InvalidOperationException instead of ArgumenNullException")]
[Fact]
public void v125()
{
XmlSchema xs = new XmlSchema();
try
{
xs.Write((XmlWriter)null);
}
catch (InvalidOperationException) { return; }
Assert.True(false);
}
//[Variation(Desc = "Dev10_40561 Redefine Chameleon: Unexpected qualified name on local particle")]
[InlineData()]
[Theory]
public void Dev10_40561()
{
Initialize();
string xml = @"<?xml version='1.0' encoding='utf-8'?><e1 xmlns='ns-a'> <c23 xmlns='ns-b'/></e1>";
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
string path = Path.Combine(TestData.StandardPath, "xsd10", "SCHEMA", "schN11_a.xsd");
set.Add(null, path);
set.Compile();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = set;
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
{
try
{
while (reader.Read()) ;
_output.WriteLine("XmlSchemaValidationException was not thrown");
Assert.True(false);
}
catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); }
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
[Fact]
public void GetBuiltinSimpleTypeWorksAsEcpected()
{
Initialize();
string xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine +
" <xs:simpleType>" + Environment.NewLine +
" <xs:restriction base=\"xs:anySimpleType\" />" + Environment.NewLine +
" </xs:simpleType>" + Environment.NewLine +
"</xs:schema>";
XmlSchema schema = new XmlSchema();
XmlSchemaSimpleType stringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String);
schema.Items.Add(stringType);
StringWriter sw = new StringWriter();
schema.Write(sw);
CError.Compare(sw.ToString(), xml, "Mismatch");
return;
}
//[Variation(Desc = "Dev10_40509 Assert and NRE when validate the XML against the XSD")]
[InlineData()]
[Theory]
public void Dev10_40509()
{
Initialize();
string xml = Path.Combine(TestData._Root, "bug511217.xml");
string xsd = Path.Combine(TestData._Root, "bug511217.xsd");
XmlSchemaSet s = new XmlSchemaSet();
s.XmlResolver = new XmlUrlResolver();
XmlReader r = XmlReader.Create(xsd);
s.Add(null, r);
s.Compile();
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
using (XmlReader docValidatingReader = XmlReader.Create(xml, rs))
{
XmlDocument doc = new XmlDocument();
doc.Load(docValidatingReader);
doc.Schemas = s;
doc.Validate(null);
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "Dev10_40511 XmlSchemaSet::Compile throws XmlSchemaException for valid schema")]
[InlineData()]
[Theory]
public void Dev10_40511()
{
Initialize();
string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:simpleType name='textType'>
<xs:restriction base='xs:string'>
<xs:minLength value='1' />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name='statusCodeType'>
<xs:restriction base='textType'>
<xs:length value='6' />
</xs:restriction>
</xs:simpleType>
</xs:schema>";
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.Add("xs", XmlReader.Create(new StringReader(xsd)));
sc.Compile();
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "Dev10_40495 Undefined ComplexType error when loading schemas from in memory strings")]
[InlineData()]
[Theory]
public void Dev10_40495()
{
Initialize();
const string schema1Str = @"<xs:schema xmlns:tns=""http://BizTalk_Server_Project2.Schema1"" xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" targetNamespace=""http://BizTalk_Server_Project2.Schema1"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:include schemaLocation=""S3"" />
<xs:include schemaLocation=""S2"" />
<xs:element name=""Root"">
<xs:complexType>
<xs:sequence>
<xs:element name=""FxTypeElement"">
<xs:complexType>
<xs:complexContent mixed=""false"">
<xs:extension base=""tns:FxType"">
<xs:attribute name=""Field"" type=""xs:string"" />
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
const string schema2Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:complexType name=""FxType"">
<xs:attribute name=""Fx2"" type=""xs:string"" />
</xs:complexType>
</xs:schema>";
const string schema3Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:complexType name=""TestType"">
<xs:attribute name=""Fx2"" type=""xs:string"" />
</xs:complexType>
</xs:schema>";
XmlSchema schema1 = XmlSchema.Read(new StringReader(schema1Str), null);
XmlSchema schema2 = XmlSchema.Read(new StringReader(schema2Str), null);
XmlSchema schema3 = XmlSchema.Read(new StringReader(schema3Str), null);
//schema1 has some xs:includes in it. Since all schemas are string based, XmlSchema on its own cannot load automatically
//load these included schemas. We will resolve these schema locations schema1 and make them point to the correct
//in memory XmlSchema objects
((XmlSchemaExternal)schema1.Includes[0]).Schema = schema3;
((XmlSchemaExternal)schema1.Includes[1]).Schema = schema2;
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
if (schemaSet.Add(schema1) != null)
{
//This compile will complain about Undefined complex Type tns:FxType and schemaSet_ValidationEventHandler will be
//called with this error.
schemaSet.Compile();
schemaSet.Reprocess(schema1);
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "Dev10_64765 XmlSchemaValidationException.SourceObject is always null when using XPathNavigator.CheckValidity method")]
[InlineData()]
[Theory]
public void Dev10_64765()
{
Initialize();
string xsd =
"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
"<xsd:element name='some'>" +
"</xsd:element>" +
"</xsd:schema>";
string xml = "<root/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
ValidateXPathNavigator(xml, CompileSchemaSet(xsd));
return;
}
private void ValidateXPathNavigator(string xml, XmlSchemaSet schemaSet)
{
XPathDocument doc = new XPathDocument(new StringReader(xml));
XPathNavigator nav = doc.CreateNavigator();
ValidateXPathNavigator(nav, schemaSet);
}
private void ValidateXPathNavigator(XPathNavigator nav, XmlSchemaSet schemaSet)
{
_output.WriteLine(nav.CheckValidity(schemaSet, OnValidationEvent) ? "Validation succeeded." : "Validation failed.");
}
private XmlSchemaSet CompileSchemaSet(string xsd)
{
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.Add(XmlSchema.Read(new StringReader(xsd), OnValidationEvent));
schemaSet.ValidationEventHandler += OnValidationEvent;
schemaSet.Compile();
return schemaSet;
}
private void OnValidationEvent(object sender, ValidationEventArgs e)
{
XmlSchemaValidationException exception = e.Exception as XmlSchemaValidationException;
if (exception == null || exception.SourceObject == null)
{
CError.Compare(exception != null, "exception == null");
CError.Compare(exception.SourceObject != null, "SourceObject == null");
return;
}
CError.Compare(exception.SourceObject.GetType().ToString(), "MS.Internal.Xml.Cache.XPathDocumentNavigator", "SourceObject.GetType");
_output.WriteLine("Exc: " + exception);
}
//[Variation(Desc = "Dev10_40563 XmlSchemaSet: Assert Failure with Chk Build.")]
[InlineData()]
[Theory]
public void Dev10_40563()
{
Initialize();
string xsd =
"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
"<xsd:element name='some'>" +
"</xsd:element>" +
"</xsd:schema>";
XmlSchemaSet ss = new XmlSchemaSet();
ss.XmlResolver = new XmlUrlResolver();
ss.Add("http://www.w3.org/2001/XMLSchema", XmlReader.Create(new StringReader(xsd)));
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.Schemas = ss;
string input = "<root xml:space='default'/>";
using (XmlReader r1 = XmlReader.Create(new StringReader(input), rs))
{
using (XmlReader r2 = XmlReader.Create(new StringReader(input), rs))
{
while (r1.Read()) ;
while (r2.Read()) ;
}
}
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 0, "Error Count mismatch!");
return;
}
//[Variation(Desc = "TFS_470020 Schema with substitution groups does not throw when content model is ambiguous")]
[InlineData()]
[Theory]
public void TFS_470020()
{
Initialize();
string xml = @"<?xml version='1.0' encoding='utf-8' ?>
<e3>
<e2>1</e2>
<e2>1</e2>
</e3>";
string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'>
<xs:element name='e1' type='xs:int'/>
<xs:element name='e2' type='xs:int' substitutionGroup='e1'/>
<xs:complexType name='t3'>
<xs:sequence>
<xs:element ref='e1' minOccurs='0' maxOccurs='1'/>
<xs:element name='e2' type='xs:int' minOccurs='0' maxOccurs='1'/>
</xs:sequence>
</xs:complexType>
<xs:element name='e3' type='t3'/>
</xs:schema>";
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.Add(null, XmlReader.Create(new StringReader(xsd)));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
doc.Schemas = set;
doc.Validate(ValidationCallback);
CError.Compare(warningCount, 0, "Warning Count mismatch!");
CError.Compare(errorCount, 1, "Error Count mismatch!");
return;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.KeyVault;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.KeyVault
{
/// <summary>
/// Vault operations
/// </summary>
internal partial class VaultOperations : IServiceOperations<KeyVaultManagementClient>, IVaultOperations
{
/// <summary>
/// Initializes a new instance of the VaultOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VaultOperations(KeyVaultManagementClient client)
{
this._client = client;
}
private KeyVaultManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient.
/// </summary>
public KeyVaultManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates a new Azure key vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='vaultName'>
/// Required. Name of the vault
/// </param>
/// <param name='parameters'>
/// Required. Parameters to create or update the vault
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Vault information.
/// </returns>
public async Task<VaultGetResponse> CreateOrUpdateAsync(string resourceGroupName, string vaultName, VaultCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.KeyVault";
url = url + "/vaults/";
url = url + Uri.EscapeDataString(vaultName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject vaultCreateOrUpdateParametersValue = new JObject();
requestDoc = vaultCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
vaultCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.VaultUri != null)
{
propertiesValue["vaultUri"] = parameters.Properties.VaultUri;
}
propertiesValue["tenantId"] = parameters.Properties.TenantId.ToString();
if (parameters.Properties.Sku != null)
{
JObject skuValue = new JObject();
propertiesValue["sku"] = skuValue;
if (parameters.Properties.Sku.Family != null)
{
skuValue["family"] = parameters.Properties.Sku.Family;
}
if (parameters.Properties.Sku.Name != null)
{
skuValue["name"] = parameters.Properties.Sku.Name;
}
}
if (parameters.Properties.AccessPolicies != null)
{
if (parameters.Properties.AccessPolicies is ILazyCollection == false || ((ILazyCollection)parameters.Properties.AccessPolicies).IsInitialized)
{
JArray accessPoliciesArray = new JArray();
foreach (AccessPolicyEntry accessPoliciesItem in parameters.Properties.AccessPolicies)
{
JObject accessPolicyEntryValue = new JObject();
accessPoliciesArray.Add(accessPolicyEntryValue);
accessPolicyEntryValue["tenantId"] = accessPoliciesItem.TenantId.ToString();
if (accessPoliciesItem.ObjectId != null)
{
accessPolicyEntryValue["objectId"] = accessPoliciesItem.ObjectId;
}
if (accessPoliciesItem.ApplicationId != null)
{
accessPolicyEntryValue["applicationId"] = accessPoliciesItem.ApplicationId.Value.ToString();
}
if (accessPoliciesItem.PermissionsRawJsonString != null)
{
accessPolicyEntryValue["permissions"] = JObject.Parse(accessPoliciesItem.PermissionsRawJsonString);
}
}
propertiesValue["accessPolicies"] = accessPoliciesArray;
}
}
propertiesValue["enabledForDeployment"] = parameters.Properties.EnabledForDeployment;
if (parameters.Properties.EnabledForDiskEncryption != null)
{
propertiesValue["enabledForDiskEncryption"] = parameters.Properties.EnabledForDiskEncryption.Value;
}
if (parameters.Properties.EnabledForTemplateDeployment != null)
{
propertiesValue["enabledForTemplateDeployment"] = parameters.Properties.EnabledForTemplateDeployment.Value;
}
vaultCreateOrUpdateParametersValue["location"] = parameters.Location;
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
vaultCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Vault vaultInstance = new Vault();
result.Vault = vaultInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue2["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue2["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue2 = propertiesValue2["sku"];
if (skuValue2 != null && skuValue2.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue2["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray2 = propertiesValue2["accessPolicies"];
if (accessPoliciesArray2 != null && accessPoliciesArray2.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray2))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue2["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue2["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue2["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes the specified Azure key vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Vault information.
/// </returns>
public async Task<VaultGetResponse> DeleteAsync(string resourceGroupName, string vaultName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.KeyVault";
url = url + "/vaults/";
url = url + Uri.EscapeDataString(vaultName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultGetResponse result = null;
// Deserialize Response
result = new VaultGetResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the specified Azure key vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Vault information.
/// </returns>
public async Task<VaultGetResponse> GetAsync(string resourceGroupName, string vaultName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.KeyVault";
url = url + "/vaults/";
url = url + Uri.EscapeDataString(vaultName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Vault vaultInstance = new Vault();
result.Vault = vaultInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray = propertiesValue["accessPolicies"];
if (accessPoliciesArray != null && accessPoliciesArray.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List operation gets information about the vaults associated
/// either with the subscription if no resource group is specified or
/// within the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Optional. An optional argument which specifies the name of the
/// resource group that constrains the set of vaults that are returned.
/// </param>
/// <param name='top'>
/// Required. Maximum number of results to return.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of vaults
/// </returns>
public async Task<VaultListResponse> ListAsync(string resourceGroupName, int top, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("top", top);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/";
if (resourceGroupName != null)
{
url = url + "resourceGroups/" + Uri.EscapeDataString(resourceGroupName) + "/";
}
url = url + "resources";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
odataFilter.Add("resourceType eq 'Microsoft.KeyVault/vaults' ");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
queryParameters.Add("$top=" + Uri.EscapeDataString(top.ToString()));
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Vault vaultInstance = new Vault();
result.Vaults.Add(vaultInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray = propertiesValue["accessPolicies"];
if (accessPoliciesArray != null && accessPoliciesArray.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the next set of vaults based on the previously returned
/// NextLink value.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of vaults
/// </returns>
public async Task<VaultListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Vault vaultInstance = new Vault();
result.Vaults.Add(vaultInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray = propertiesValue["accessPolicies"];
if (accessPoliciesArray != null && accessPoliciesArray.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
string objectIdInstance = ((string)objectIdValue);
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.ComponentModel;
using System.Security.Principal;
using System.Security.AccessControl;
namespace System.DirectoryServices
{
[Flags]
public enum ActiveDirectoryRights
{
Delete = 0x10000,
ReadControl = 0x20000,
WriteDacl = 0x40000,
WriteOwner = 0x80000,
Synchronize = 0x100000,
AccessSystemSecurity = 0x1000000,
GenericRead = ReadControl | ListChildren | ReadProperty | ListObject,
GenericWrite = ReadControl | Self | WriteProperty,
GenericExecute = ReadControl | ListChildren,
GenericAll = Delete | ReadControl | WriteDacl | WriteOwner | CreateChild | DeleteChild | ListChildren | Self | ReadProperty | WriteProperty | DeleteTree | ListObject | ExtendedRight,
CreateChild = 0x1,
DeleteChild = 0x2,
ListChildren = 0x4,
Self = 0x8,
ReadProperty = 0x10,
WriteProperty = 0x20,
DeleteTree = 0x40,
ListObject = 0x80,
ExtendedRight = 0x100
}
public enum ActiveDirectorySecurityInheritance
{
None = 0,
All = 1,
Descendents = 2,
SelfAndChildren = 3,
Children = 4
}
public enum PropertyAccess
{
Read = 0,
Write = 1
}
public class ActiveDirectorySecurity : DirectoryObjectSecurity
{
private readonly SecurityMasks _securityMaskUsedInRetrieval = SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl;
#region Constructors
public ActiveDirectorySecurity()
{
}
internal ActiveDirectorySecurity(byte[] sdBinaryForm, SecurityMasks securityMask)
: base(new CommonSecurityDescriptor(true, true, sdBinaryForm, 0))
{
_securityMaskUsedInRetrieval = securityMask;
}
#endregion
#region Public methods
//
// DiscretionaryAcl related methods
//
public void AddAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.AddAccessRule(rule);
}
public void SetAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.SetAccessRule(rule);
}
public void ResetAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.ResetAccessRule(rule);
}
public void RemoveAccess(IdentityReference identity, AccessControlType type)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
//
// Create a new rule
//
ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(
identity,
ActiveDirectoryRights.GenericRead, // will be ignored
type,
ActiveDirectorySecurityInheritance.None);
base.RemoveAccessRuleAll(rule);
}
public bool RemoveAccessRule(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleSpecific(ActiveDirectoryAccessRule rule)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.RemoveAccessRuleSpecific(rule);
}
public override bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
return base.ModifyAccessRule(modification, rule, out modified);
}
public override void PurgeAccessRules(IdentityReference identity)
{
if (!DaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifyDacl);
}
base.PurgeAccessRules(identity);
}
//
// SystemAcl related methods
//
public void AddAuditRule(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.AddAuditRule(rule);
}
public void SetAuditRule(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.SetAuditRule(rule);
}
public void RemoveAudit(IdentityReference identity)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
//
// Create a new rule
//
ActiveDirectoryAuditRule rule = new ActiveDirectoryAuditRule(
identity,
ActiveDirectoryRights.GenericRead, // will be ignored
AuditFlags.Success | AuditFlags.Failure,
ActiveDirectorySecurityInheritance.None);
base.RemoveAuditRuleAll(rule);
}
public bool RemoveAuditRule(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleSpecific(ActiveDirectoryAuditRule rule)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.RemoveAuditRuleSpecific(rule);
}
public override bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
return base.ModifyAuditRule(modification, rule, out modified);
}
public override void PurgeAuditRules(IdentityReference identity)
{
if (!SaclRetrieved())
{
throw new InvalidOperationException(SR.CannotModifySacl);
}
base.PurgeAuditRules(identity);
}
#endregion
#region Factories
public sealed override AccessRule AccessRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
{
return new ActiveDirectoryAccessRule(
identityReference,
accessMask,
type,
Guid.Empty,
isInherited,
inheritanceFlags,
propagationFlags,
Guid.Empty);
}
public sealed override AccessRule AccessRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type,
Guid objectGuid,
Guid inheritedObjectGuid)
{
return new ActiveDirectoryAccessRule(
identityReference,
accessMask,
type,
objectGuid,
isInherited,
inheritanceFlags,
propagationFlags,
inheritedObjectGuid);
}
public sealed override AuditRule AuditRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags)
{
return new ActiveDirectoryAuditRule(
identityReference,
accessMask,
flags,
Guid.Empty,
isInherited,
inheritanceFlags,
propagationFlags,
Guid.Empty);
}
public sealed override AuditRule AuditRuleFactory(
IdentityReference identityReference,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags flags,
Guid objectGuid,
Guid inheritedObjectGuid)
{
return new ActiveDirectoryAuditRule(
identityReference,
accessMask,
flags,
objectGuid,
isInherited,
inheritanceFlags,
propagationFlags,
inheritedObjectGuid);
}
internal bool IsModified()
{
ReadLock();
try
{
return (OwnerModified || GroupModified || AccessRulesModified || AuditRulesModified);
}
finally
{
ReadUnlock();
}
}
private bool DaclRetrieved()
{
return ((_securityMaskUsedInRetrieval & SecurityMasks.Dacl) != 0);
}
private bool SaclRetrieved()
{
return ((_securityMaskUsedInRetrieval & SecurityMasks.Sacl) != 0);
}
#endregion
#region some overrides
public override Type AccessRightType => typeof(ActiveDirectoryRights);
public override Type AccessRuleType => typeof(ActiveDirectoryAccessRule);
public override Type AuditRuleType => typeof(ActiveDirectoryAuditRule);
#endregion
}
internal sealed class ActiveDirectoryRightsTranslator
{
#region Access mask to rights translation
internal static int AccessMaskFromRights(ActiveDirectoryRights adRights) => (int)adRights;
internal static ActiveDirectoryRights RightsFromAccessMask(int accessMask)
{
return (ActiveDirectoryRights)accessMask;
}
#endregion
}
internal sealed class PropertyAccessTranslator
{
#region PropertyAccess to access mask translation
internal static int AccessMaskFromPropertyAccess(PropertyAccess access)
{
int accessMask = 0;
if (access < PropertyAccess.Read || access > PropertyAccess.Write)
{
throw new InvalidEnumArgumentException("access", (int)access, typeof(PropertyAccess));
}
switch (access)
{
case PropertyAccess.Read:
{
accessMask = ActiveDirectoryRightsTranslator.AccessMaskFromRights(ActiveDirectoryRights.ReadProperty);
break;
}
case PropertyAccess.Write:
{
accessMask = ActiveDirectoryRightsTranslator.AccessMaskFromRights(ActiveDirectoryRights.WriteProperty);
break;
}
default:
//
// This should not happen. Indicates a problem with the
// internal logic.
//
Debug.Fail("Invalid PropertyAccess value");
throw new ArgumentException("access");
}
return accessMask;
}
#endregion
}
internal sealed class ActiveDirectoryInheritanceTranslator
{
#region ActiveDirectorySecurityInheritance to Inheritance/Propagation flags translation
//
// InheritanceType InheritanceFlags PropagationFlags
// ------------------------------------------------------------------------------
// None None None
// All ContainerInherit None
// Descendents ContainerInherit InheritOnly
// SelfAndChildren ContainerInherit NoPropogateInherit
// Children ContainerInherit InheritOnly | NoPropagateInherit
//
internal static InheritanceFlags[] ITToIF = new InheritanceFlags[] {
InheritanceFlags.None,
InheritanceFlags.ContainerInherit,
InheritanceFlags.ContainerInherit,
InheritanceFlags.ContainerInherit,
InheritanceFlags.ContainerInherit
};
internal static PropagationFlags[] ITToPF = new PropagationFlags[] {
PropagationFlags.None,
PropagationFlags.None,
PropagationFlags.InheritOnly,
PropagationFlags.NoPropagateInherit,
PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit
};
internal static InheritanceFlags GetInheritanceFlags(ActiveDirectorySecurityInheritance inheritanceType)
{
if (inheritanceType < ActiveDirectorySecurityInheritance.None || inheritanceType > ActiveDirectorySecurityInheritance.Children)
{
throw new InvalidEnumArgumentException("inheritanceType", (int)inheritanceType, typeof(ActiveDirectorySecurityInheritance));
}
return ITToIF[(int)inheritanceType];
}
internal static PropagationFlags GetPropagationFlags(ActiveDirectorySecurityInheritance inheritanceType)
{
if (inheritanceType < ActiveDirectorySecurityInheritance.None || inheritanceType > ActiveDirectorySecurityInheritance.Children)
{
throw new InvalidEnumArgumentException("inheritanceType", (int)inheritanceType, typeof(ActiveDirectorySecurityInheritance));
}
return ITToPF[(int)inheritanceType];
}
internal static ActiveDirectorySecurityInheritance GetEffectiveInheritanceFlags(InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
ActiveDirectorySecurityInheritance inheritanceType = ActiveDirectorySecurityInheritance.None;
if ((inheritanceFlags & InheritanceFlags.ContainerInherit) != 0)
{
switch (propagationFlags)
{
case PropagationFlags.None:
{
inheritanceType = ActiveDirectorySecurityInheritance.All;
break;
}
case PropagationFlags.InheritOnly:
{
inheritanceType = ActiveDirectorySecurityInheritance.Descendents;
break;
}
case PropagationFlags.NoPropagateInherit:
{
inheritanceType = ActiveDirectorySecurityInheritance.SelfAndChildren;
break;
}
case PropagationFlags.InheritOnly | PropagationFlags.NoPropagateInherit:
{
inheritanceType = ActiveDirectorySecurityInheritance.Children;
break;
}
default:
//
// This should not happen. Indicates a problem with the
// internal logic.
//
Debug.Fail("Invalid PropagationFlags value");
throw new ArgumentException("propagationFlags");
}
}
return inheritanceType;
}
#endregion
}
public class ActiveDirectoryAccessRule : ObjectAccessRule
{
#region Constructors
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty
)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
Guid objectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
objectType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public ActiveDirectoryAccessRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AccessControlType type,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
type,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
internal ActiveDirectoryAccessRule(
IdentityReference identity,
int accessMask,
AccessControlType type,
Guid objectType,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
Guid inheritedObjectType
)
: base(identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
objectType,
inheritedObjectType,
type)
{
}
#endregion constructors
#region Public properties
public ActiveDirectoryRights ActiveDirectoryRights
{
get => ActiveDirectoryRightsTranslator.RightsFromAccessMask(base.AccessMask);
}
public ActiveDirectorySecurityInheritance InheritanceType
{
get => ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(InheritanceFlags, PropagationFlags);
}
#endregion
}
public sealed class ListChildrenAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public ListChildrenAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.ListChildren,
type,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty
)
{
}
public ListChildrenAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.ListChildren,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ListChildrenAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.ListChildren,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class CreateChildAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
Guid.Empty, // all child objects
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
childType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public CreateChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public CreateChildAccessRule(
IdentityReference identity, AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.CreateChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class DeleteChildAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
Guid.Empty, // all child objects
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
childType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public DeleteChildAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
Guid.Empty, // all child objects
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public DeleteChildAccessRule(
IdentityReference identity, AccessControlType type,
Guid childType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteChild,
type,
childType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class PropertyAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
Guid.Empty, // all properties
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertyType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertyType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
Guid.Empty, // all properties
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertyType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertyType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
Guid.Empty, // all properties
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public PropertyAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertyType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertyType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class PropertySetAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public PropertySetAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertySetType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertySetType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public PropertySetAccessRule(
IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertySetType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertySetType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public PropertySetAccessRule(IdentityReference identity,
AccessControlType type,
PropertyAccess access,
Guid propertySetType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)PropertyAccessTranslator.AccessMaskFromPropertyAccess(access),
type,
propertySetType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class ExtendedRightAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
Guid.Empty, // all extended rights
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
Guid extendedRightType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
extendedRightType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
Guid.Empty, // all extended rights
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
Guid extendedRightType,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
extendedRightType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ExtendedRightAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
Guid.Empty, // all extended rights
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public ExtendedRightAccessRule(IdentityReference identity,
AccessControlType type,
Guid extendedRightType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.ExtendedRight,
type,
extendedRightType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public sealed class DeleteTreeAccessRule : ActiveDirectoryAccessRule
{
#region Constructors
public DeleteTreeAccessRule(
IdentityReference identity,
AccessControlType type)
: base(
identity,
(int)ActiveDirectoryRights.DeleteTree,
type,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public DeleteTreeAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteTree,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public DeleteTreeAccessRule(
IdentityReference identity,
AccessControlType type,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: base(
identity,
(int)ActiveDirectoryRights.DeleteTree,
type,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
#endregion constructors
}
public class ActiveDirectoryAuditRule : ObjectAuditRule
{
#region Constructors
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
Guid.Empty,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty
)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
Guid objectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
objectType,
false,
InheritanceFlags.None,
PropagationFlags.None,
Guid.Empty)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
Guid.Empty)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
Guid.Empty,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
public ActiveDirectoryAuditRule(
IdentityReference identity,
ActiveDirectoryRights adRights,
AuditFlags auditFlags,
Guid objectType,
ActiveDirectorySecurityInheritance inheritanceType,
Guid inheritedObjectType)
: this(
identity,
ActiveDirectoryRightsTranslator.AccessMaskFromRights(adRights),
auditFlags,
objectType,
false,
ActiveDirectoryInheritanceTranslator.GetInheritanceFlags(inheritanceType),
ActiveDirectoryInheritanceTranslator.GetPropagationFlags(inheritanceType),
inheritedObjectType)
{
}
internal ActiveDirectoryAuditRule(
IdentityReference identity,
int accessMask,
AuditFlags auditFlags,
Guid objectGuid,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
Guid inheritedObjectType
)
: base(identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
objectGuid,
inheritedObjectType,
auditFlags)
{
}
#endregion constructors
#region Public properties
public ActiveDirectoryRights ActiveDirectoryRights
{
get => ActiveDirectoryRightsTranslator.RightsFromAccessMask(AccessMask);
}
public ActiveDirectorySecurityInheritance InheritanceType
{
get => ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(InheritanceFlags, PropagationFlags);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Aga.Controls.Tree
{
internal class NormalInputState : InputState
{
private bool _mouseDownFlag = false;
public NormalInputState(TreeViewAdv tree) : base(tree)
{
}
public override void KeyDown(KeyEventArgs args)
{
if (Tree.CurrentNode == null && Tree.Root.Nodes.Count > 0)
Tree.CurrentNode = Tree.Root.Nodes[0];
if (Tree.CurrentNode != null)
{
switch (args.KeyCode)
{
case Keys.Right:
if (!Tree.CurrentNode.IsExpanded)
Tree.CurrentNode.IsExpanded = true;
else if (Tree.CurrentNode.Nodes.Count > 0)
Tree.SelectedNode = Tree.CurrentNode.Nodes[0];
args.Handled = true;
break;
case Keys.Left:
if (Tree.CurrentNode.IsExpanded)
Tree.CurrentNode.IsExpanded = false;
else if (Tree.CurrentNode.Parent != Tree.Root)
Tree.SelectedNode = Tree.CurrentNode.Parent;
args.Handled = true;
break;
case Keys.Down:
NavigateForward(1);
args.Handled = true;
break;
case Keys.Up:
NavigateBackward(1);
args.Handled = true;
break;
case Keys.PageDown:
NavigateForward(Math.Max(1, Tree.CurrentPageSize - 1));
args.Handled = true;
break;
case Keys.PageUp:
NavigateBackward(Math.Max(1, Tree.CurrentPageSize - 1));
args.Handled = true;
break;
case Keys.Home:
if (Tree.RowMap.Count > 0)
FocusRow(Tree.RowMap[0]);
args.Handled = true;
break;
case Keys.End:
if (Tree.RowMap.Count > 0)
FocusRow(Tree.RowMap[Tree.RowMap.Count-1]);
args.Handled = true;
break;
case Keys.Subtract:
Tree.CurrentNode.Collapse();
args.Handled = true;
args.SuppressKeyPress = true;
break;
case Keys.Add:
Tree.CurrentNode.Expand();
args.Handled = true;
args.SuppressKeyPress = true;
break;
case Keys.Multiply:
Tree.CurrentNode.ExpandAll();
args.Handled = true;
args.SuppressKeyPress = true;
break;
case Keys.A:
if (args.Modifiers == Keys.Control)
Tree.SelectAllNodes();
break;
}
}
}
public override void MouseDown(TreeNodeAdvMouseEventArgs args)
{
if (args.Node != null)
{
Tree.ItemDragMode = true;
Tree.ItemDragStart = args.Location;
if (args.Button == MouseButtons.Left || args.Button == MouseButtons.Right)
{
Tree.BeginUpdate();
try
{
Tree.CurrentNode = args.Node;
if (args.Node.IsSelected)
_mouseDownFlag = true;
else
{
_mouseDownFlag = false;
DoMouseOperation(args);
}
}
finally
{
Tree.EndUpdate();
}
}
}
else
{
Tree.ItemDragMode = false;
MouseDownAtEmptySpace(args);
}
}
public override void MouseUp(TreeNodeAdvMouseEventArgs args)
{
Tree.ItemDragMode = false;
if (_mouseDownFlag && args.Node != null)
{
if (args.Button == MouseButtons.Left)
DoMouseOperation(args);
else if (args.Button == MouseButtons.Right)
Tree.CurrentNode = args.Node;
}
_mouseDownFlag = false;
}
private void NavigateBackward(int n)
{
int row = Math.Max(Tree.CurrentNode.Row - n, 0);
while (Tree.RowMap[row].IsHidden) --row;
if (row != Tree.CurrentNode.Row && row > 0)
FocusRow(Tree.RowMap[row]);
}
private void NavigateForward(int n)
{
int row = Math.Min(Tree.CurrentNode.Row + n, Tree.RowCount - 1);
while (Tree.RowMap[row].IsHidden) ++row;
if (row != Tree.CurrentNode.Row && row < Tree.RowMap.Count)
FocusRow(Tree.RowMap[row]);
}
protected virtual void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args)
{
Tree.ClearSelection();
}
protected virtual void FocusRow(TreeNodeAdv node)
{
Tree.SuspendSelectionEvent = true;
try
{
Tree.ClearSelectionInternal();
Tree.CurrentNode = node;
Tree.SelectionStart = node;
node.IsSelected = true;
Tree.ScrollTo(node);
}
finally
{
Tree.SuspendSelectionEvent = false;
}
}
protected bool CanSelect(TreeNodeAdv node)
{
if (Tree.SelectionMode == TreeSelectionMode.MultiSameParent)
{
return (Tree.SelectionStart == null || node.Parent == Tree.SelectionStart.Parent);
}
else
return true;
}
protected virtual void DoMouseOperation(TreeNodeAdvMouseEventArgs args)
{
if (Tree.SelectedNodes.Count == 1 && args.Node != null && args.Node.IsSelected)
return;
Tree.SuspendSelectionEvent = true;
try
{
Tree.ClearSelectionInternal();
if (args.Node != null)
args.Node.IsSelected = true;
Tree.SelectionStart = args.Node;
}
finally
{
Tree.SuspendSelectionEvent = false;
}
}
}
}
| |
using EFCore.BulkExtensions.SqlAdapters;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Caching.Memory;
using Npgsql;
using NpgsqlTypes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using Xunit;
namespace EFCore.BulkExtensions.Tests
{
public class EFCoreBulkTest
{
protected int EntitiesNumber => 10000;
private static Func<TestContext, int> ItemsCountQuery = EF.CompileQuery<TestContext, int>(ctx => ctx.Items.Count());
private static Func<TestContext, Item> LastItemQuery = EF.CompileQuery<TestContext, Item>(ctx => ctx.Items.LastOrDefault());
private static Func<TestContext, IEnumerable<Item>> AllItemsQuery = EF.CompileQuery<TestContext, IEnumerable<Item>>(ctx => ctx.Items.AsNoTracking());
[Theory]
[InlineData(DbServer.PostgreSQL)]
public void InsertEnumStringValue(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Database.ExecuteSqlRaw($@"DELETE FROM ""{nameof(Wall)}""");
var newWall = new Wall()
{
Id = 1,
WallTypeValue = WallType.Brick
};
// INSERT
context.BulkInsert(new List<Wall>() { newWall });
var addedWall = context.Walls.AsNoTracking().First(x => x.Id == newWall.Id);
Assert.True(addedWall.WallTypeValue == newWall.WallTypeValue);
}
[Theory]
[InlineData(DbServer.PostgreSQL, true)]
public void InsertTestPostgreSql(DbServer dbServer, bool isBulk)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Database.ExecuteSqlRaw($@"DELETE FROM ""{nameof(Item)}""");
context.Database.ExecuteSqlRaw($@"ALTER SEQUENCE ""{nameof(Item)}_{nameof(Item.ItemId)}_seq"" RESTART WITH 1");
context.Database.ExecuteSqlRaw($@"DELETE FROM ""{nameof(Box)}""");
context.Database.ExecuteSqlRaw($@"ALTER SEQUENCE ""{nameof(Box)}_{nameof(Box.BoxId)}_seq"" RESTART WITH 1");
context.Database.ExecuteSqlRaw($@"DELETE FROM ""{nameof(UserRole)}""");
var currentTime = DateTime.UtcNow; // default DateTime type: "timestamp with time zone"; DateTime.Now goes with: "timestamp without time zone"
var entities = new List<Item>();
for (int i = 1; i <= 2; i++)
{
var entity = new Item
{
//ItemId = i,
Name = "Name " + i,
Description = "info " + i,
Quantity = i,
Price = 0.1m * i,
TimeUpdated = currentTime,
};
entities.Add(entity);
}
var entities2 = new List<Item>();
for (int i = 2; i <= 3; i++)
{
var entity = new Item
{
ItemId = i,
Name = "Name " + i,
Description = "UPDATE " + i,
Quantity = i,
Price = 0.1m * i,
TimeUpdated = currentTime,
};
entities2.Add(entity);
}
var entities3 = new List<Item>();
for (int i = 3; i <= 4; i++)
{
var entity = new Item
{
//ItemId = i,
Name = "Name " + i,
Description = "CHANGE " + i,
Quantity = i,
Price = 0.1m * i,
TimeUpdated = currentTime,
};
entities3.Add(entity);
}
var entities56 = new List<Item>();
for (int i = 5; i <= 6; i++)
{
var entity = new Item
{
//ItemId = i,
Name = "Name " + i,
Description = "CHANGE " + i,
Quantity = i,
Price = 0.1m * i,
TimeUpdated = currentTime,
};
entities56.Add(entity);
}
// INSERT
context.BulkInsert(entities);
Assert.Equal("info 1", context.Items.Where(a => a.Name == "Name 1").AsNoTracking().FirstOrDefault().Description);
Assert.Equal("info 2", context.Items.Where(a => a.Name == "Name 2").AsNoTracking().FirstOrDefault().Description);
// UPDATE
context.BulkInsertOrUpdate(entities2, new BulkConfig() { NotifyAfter = 1 }, (a) => WriteProgress(a));
Assert.Equal("UPDATE 2", context.Items.Where(a => a.Name == "Name 2").AsNoTracking().FirstOrDefault().Description);
Assert.Equal("UPDATE 3", context.Items.Where(a => a.Name == "Name 3").AsNoTracking().FirstOrDefault().Description);
var configUpdateBy = new BulkConfig { UpdateByProperties = new List<string> { nameof(Item.Name) } };
configUpdateBy.SetOutputIdentity = true;
context.BulkUpdate(entities3, configUpdateBy);
Assert.Equal(3, entities3[0].ItemId); // to test Output
Assert.Equal(4, entities3[1].ItemId);
Assert.Equal("CHANGE 3", context.Items.Where(a => a.Name == "Name 3").AsNoTracking().FirstOrDefault().Description);
Assert.Equal("CHANGE 4", context.Items.Where(a => a.Name == "Name 4").AsNoTracking().FirstOrDefault().Description);
// Test Multiple KEYS
var userRoles = new List<UserRole> { new UserRole { Description = "Info" } };
context.BulkInsertOrUpdate(userRoles);
// DELETE
context.BulkDelete(new List<Item>() { entities2[1] }, configUpdateBy);
// READ
var secondEntity = new List<Item>() { new Item { Name = entities[1].Name } };
context.BulkRead(secondEntity, configUpdateBy);
Assert.Equal(2, secondEntity.FirstOrDefault().ItemId);
Assert.Equal("UPDATE 2", secondEntity.FirstOrDefault().Description);
// SAVE CHANGES
context.AddRange(entities56);
context.BulkSaveChanges();
Assert.Equal(5, entities56[0].ItemId);
// BATCH
var query = context.Items.AsQueryable().Where(a => a.ItemId <= 1);
query.BatchUpdate(new Item { Description = "UPDATE N", Price = 1.5m }/*, updateColumns*/);
var queryJoin = context.ItemHistories.Where(p => p.Item.Description == "UPDATE 2");
queryJoin.BatchUpdate(new ItemHistory { Remark = "Rx", });
var query2 = context.Items.AsQueryable().Where(a => a.ItemId > 1 && a.ItemId < 3);
query.BatchDelete();
var descriptionsToDelete = new List<string> { "info" };
var query3 = context.Items.Where(a => descriptionsToDelete.Contains(a.Description));
query3.BatchDelete();
// for type 'jsonb'
JsonDocument jsonbDoc = JsonDocument.Parse(@"{ ""ModelEL"" : ""Square""}");
var box = new Box { DocumentContent = jsonbDoc, ElementContent = jsonbDoc.RootElement };
context.BulkInsert(new List<Box> { box });
JsonDocument jsonbDoc2 = JsonDocument.Parse(@"{ ""ModelEL"" : ""Circle""}");
var boxQuery = context.Boxes.AsQueryable().Where(a => a.BoxId <= 1);
boxQuery.BatchUpdate(new Box { DocumentContent = jsonbDoc2, ElementContent = jsonbDoc2.RootElement });
//var incrementStep = 100;
//var suffix = " Concatenated";
//query.BatchUpdate(a => new Item { Name = a.Name + suffix, Quantity = a.Quantity + incrementStep }); // example of BatchUpdate Increment/Decrement value in variable
}
[Theory]
[InlineData(DbServer.SQLServer, true)]
[InlineData(DbServer.SQLite, true)]
//[InlineData(DbServer.SqlServer, false)] // for speed comparison with Regular EF CUD operations
public void OperationsTest(DbServer dbServer, bool isBulk)
{
ContextUtil.DbServer = dbServer;
//DeletePreviousDatabase();
new EFCoreBatchTest().RunDeleteAll(dbServer);
RunInsert(isBulk);
RunInsertOrUpdate(isBulk, dbServer);
RunUpdate(isBulk, dbServer);
RunRead(isBulk);
if (dbServer == DbServer.SQLServer)
{
RunInsertOrUpdateOrDelete(isBulk); // Not supported for Sqlite (has only UPSERT), instead use BulkRead, then split list into sublists and call separately Bulk methods for Insert, Update, Delete.
}
RunDelete(isBulk, dbServer);
//CheckQueryCache();
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
public void SideEffectsTest(DbServer dbServer)
{
BulkOperationShouldNotCloseOpenConnection(dbServer, context => context.BulkInsert(new[] { new Item() }));
BulkOperationShouldNotCloseOpenConnection(dbServer, context => context.BulkUpdate(new[] { new Item() }));
}
private static void BulkOperationShouldNotCloseOpenConnection(DbServer dbServer, Action<TestContext> bulkOperation)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
var sqlHelper = context.GetService<ISqlGenerationHelper>();
context.Database.OpenConnection();
try
{
// we use a temp table to verify whether the connection has been closed (and re-opened) inside BulkUpdate(Async)
var columnName = sqlHelper.DelimitIdentifier("Id");
var tableName = sqlHelper.DelimitIdentifier("#MyTempTable");
var createTableSql = $" TABLE {tableName} ({columnName} INTEGER);";
createTableSql = dbServer switch
{
DbServer.SQLite => $"CREATE TEMPORARY {createTableSql}",
DbServer.SQLServer => $"CREATE {createTableSql}",
_ => throw new ArgumentException($"Unknown database type: '{dbServer}'.", nameof(dbServer)),
};
context.Database.ExecuteSqlRaw(createTableSql);
bulkOperation(context);
context.Database.ExecuteSqlRaw($"SELECT {columnName} FROM {tableName}");
}
catch (Exception ex)
{
// Table already exist
}
finally
{
context.Database.CloseConnection();
}
}
private void DeletePreviousDatabase()
{
using var context = new TestContext(ContextUtil.GetOptions());
context.Database.EnsureDeleted();
}
private void CheckQueryCache()
{
using var context = new TestContext(ContextUtil.GetOptions());
var compiledQueryCache = ((MemoryCache)context.GetService<IMemoryCache>());
Assert.Equal(0, compiledQueryCache.Count);
}
private void WriteProgress(decimal percentage)
{
Debug.WriteLine(percentage);
}
private void RunInsert(bool isBulk)
{
using var context = new TestContext(ContextUtil.GetOptions());
var entities = new List<Item>();
var subEntities = new List<ItemHistory>();
for (int i = 1, j = -(EntitiesNumber - 1); i < EntitiesNumber; i++, j++)
{
var entity = new Item
{
ItemId = 0, //isBulk ? j : 0, // no longer used since order(Identity temporary filled with negative values from -N to -1) is set automaticaly with default config PreserveInsertOrder=TRUE
Name = "name " + i,
Description = "info " + Guid.NewGuid().ToString().Substring(0, 3),
Quantity = i % 10,
Price = i / (i % 5 + 1),
TimeUpdated = DateTime.Now,
ItemHistories = new List<ItemHistory>()
};
var subEntity1 = new ItemHistory
{
ItemHistoryId = SeqGuid.Create(),
Remark = $"some more info {i}.1"
};
var subEntity2 = new ItemHistory
{
ItemHistoryId = SeqGuid.Create(),
Remark = $"some more info {i}.2"
};
entity.ItemHistories.Add(subEntity1);
entity.ItemHistories.Add(subEntity2);
entities.Add(entity);
}
if (isBulk)
{
if (ContextUtil.DbServer == DbServer.SQLServer)
{
using var transaction = context.Database.BeginTransaction();
var bulkConfig = new BulkConfig
{
//PreserveInsertOrder = true, // true is default
SetOutputIdentity = true,
BatchSize = 4000,
UseTempDB = true,
CalculateStats = true
};
context.BulkInsert(entities, bulkConfig, (a) => WriteProgress(a));
Assert.Equal(EntitiesNumber - 1, bulkConfig.StatsInfo.StatsNumberInserted);
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberUpdated);
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted);
foreach (var entity in entities)
{
foreach (var subEntity in entity.ItemHistories)
{
subEntity.ItemId = entity.ItemId; // setting FK to match its linked PK that was generated in DB
}
subEntities.AddRange(entity.ItemHistories);
}
context.BulkInsert(subEntities);
transaction.Commit();
}
else if (ContextUtil.DbServer == DbServer.SQLite)
{
using var transaction = context.Database.BeginTransaction();
var bulkConfig = new BulkConfig() { SetOutputIdentity = true };
context.BulkInsert(entities, bulkConfig);
foreach (var entity in entities)
{
foreach (var subEntity in entity.ItemHistories)
{
subEntity.ItemId = entity.ItemId; // setting FK to match its linked PK that was generated in DB
}
subEntities.AddRange(entity.ItemHistories);
}
bulkConfig.SetOutputIdentity = false;
context.BulkInsert(subEntities, bulkConfig);
transaction.Commit();
}
}
else
{
context.Items.AddRange(entities);
context.SaveChanges();
}
// TEST
int entitiesCount = ItemsCountQuery(context);
Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();
Assert.Equal(EntitiesNumber - 1, entitiesCount);
Assert.NotNull(lastEntity);
Assert.Equal("name " + (EntitiesNumber - 1), lastEntity.Name);
}
private void RunInsertOrUpdate(bool isBulk, DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
var entities = new List<Item>();
var dateTimeNow = DateTime.Now;
for (int i = 2; i <= EntitiesNumber; i += 2)
{
entities.Add(new Item
{
ItemId = isBulk ? i : 0,
Name = "name InsertOrUpdate " + i,
Description = "info",
Quantity = i + 100,
Price = i / (i % 5 + 1),
TimeUpdated = dateTimeNow
});
}
if (isBulk)
{
var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true };
context.BulkInsertOrUpdate(entities, bulkConfig, (a) => WriteProgress(a));
if (dbServer == DbServer.SQLServer)
{
Assert.Equal(1, bulkConfig.StatsInfo.StatsNumberInserted);
Assert.Equal(EntitiesNumber / 2 - 1, bulkConfig.StatsInfo.StatsNumberUpdated);
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted);
}
}
else
{
context.Items.Add(entities[entities.Count - 1]);
context.SaveChanges();
}
// TEST
int entitiesCount = context.Items.Count();
Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();
Assert.Equal(EntitiesNumber, entitiesCount);
Assert.NotNull(lastEntity);
Assert.Equal("name InsertOrUpdate " + EntitiesNumber, lastEntity.Name);
}
private void RunInsertOrUpdateOrDelete(bool isBulk)
{
using var context = new TestContext(ContextUtil.GetOptions());
var entities = new List<Item>();
var dateTimeNow = DateTime.Now;
for (int i = 2; i <= EntitiesNumber; i += 2)
{
entities.Add(new Item
{
ItemId = i,
Name = "name InsertOrUpdateOrDelete " + i,
Description = "info",
Quantity = i,
Price = i / (i % 5 + 1),
TimeUpdated = dateTimeNow
});
}
if (isBulk)
{
var bulkConfig = new BulkConfig() { SetOutputIdentity = true, CalculateStats = true };
context.BulkInsertOrUpdateOrDelete(entities, bulkConfig, (a) => WriteProgress(a));
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted);
Assert.Equal(EntitiesNumber / 2, bulkConfig.StatsInfo.StatsNumberUpdated);
Assert.Equal(EntitiesNumber / 2, bulkConfig.StatsInfo.StatsNumberDeleted);
}
else
{
var existingItems = context.Items;
var removedItems = existingItems.Where(x => !entities.Any(y => y.ItemId == x.ItemId));
context.Items.RemoveRange(removedItems);
context.Items.AddRange(entities);
context.SaveChanges();
}
// TEST
int entitiesCount = context.Items.Count();
Item firstEntity = context.Items.OrderBy(a => a.ItemId).FirstOrDefault();
Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();
Assert.Equal(EntitiesNumber / 2, entitiesCount);
Assert.NotNull(firstEntity);
Assert.Equal("name InsertOrUpdateOrDelete 2", firstEntity.Name);
Assert.NotNull(lastEntity);
Assert.Equal("name InsertOrUpdateOrDelete " + EntitiesNumber, lastEntity.Name);
}
private void RunUpdate(bool isBulk, DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
int counter = 1;
var entities = context.Items.AsNoTracking().ToList();
foreach (var entity in entities)
{
entity.Description = "Desc Update " + counter++;
entity.Quantity += 1000; // will not be changed since Quantity property is not in config PropertiesToInclude
}
if (isBulk)
{
var bulkConfig = new BulkConfig
{
PropertiesToInclude = new List<string> { nameof(Item.Description) },
UpdateByProperties = dbServer == DbServer.SQLServer ? new List<string> { nameof(Item.Name) } : null,
CalculateStats = true
};
context.BulkUpdate(entities, bulkConfig);
if (dbServer == DbServer.SQLServer)
{
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted);
Assert.Equal(EntitiesNumber, bulkConfig.StatsInfo.StatsNumberUpdated);
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberDeleted);
}
}
else
{
context.Items.UpdateRange(entities);
context.SaveChanges();
}
// TEST
int entitiesCount = context.Items.Count();
Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();
Assert.Equal(EntitiesNumber, entitiesCount);
Assert.NotNull(lastEntity);
Assert.Equal("name InsertOrUpdate " + EntitiesNumber, lastEntity.Name);
}
private void RunRead(bool isBulk)
{
using var context = new TestContext(ContextUtil.GetOptions());
var entities = new List<Item>();
for (int i = 1; i < EntitiesNumber; i++)
{
var entity = new Item
{
Name = "name " + i,
};
entities.Add(entity);
}
context.BulkRead(
entities,
new BulkConfig
{
UpdateByProperties = new List<string> { nameof(Item.Name) }
}
);
Assert.Equal(1, entities[0].ItemId);
Assert.Equal(0, entities[1].ItemId);
Assert.Equal(3, entities[2].ItemId);
Assert.Equal(0, entities[3].ItemId);
}
private void RunDelete(bool isBulk, DbServer dbServer)
{
using var context = new TestContext(ContextUtil.GetOptions());
var entities = AllItemsQuery(context).ToList();
// ItemHistories will also be deleted because of Relationship - ItemId (Delete Rule: Cascade)
if (isBulk)
{
var bulkConfig = new BulkConfig() { CalculateStats = true };
context.BulkDelete(entities, bulkConfig);
if (dbServer == DbServer.SQLServer)
{
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberInserted);
Assert.Equal(0, bulkConfig.StatsInfo.StatsNumberUpdated);
Assert.Equal(entities.Count, bulkConfig.StatsInfo.StatsNumberDeleted);
}
}
else
{
context.Items.RemoveRange(entities);
context.SaveChanges();
}
// TEST
int entitiesCount = context.Items.Count();
Item lastEntity = context.Items.OrderByDescending(a => a.ItemId).FirstOrDefault();
Assert.Equal(0, entitiesCount);
Assert.Null(lastEntity);
// RESET AutoIncrement
string deleteTableSql = dbServer switch
{
DbServer.SQLServer => $"DBCC CHECKIDENT('[dbo].[{nameof(Item)}]', RESEED, 0);",
DbServer.SQLite => $"DELETE FROM sqlite_sequence WHERE name = '{nameof(Item)}';",
_ => throw new ArgumentException($"Unknown database type: '{dbServer}'.", nameof(dbServer)),
};
context.Database.ExecuteSqlRaw(deleteTableSql);
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, PublishedRepositoryEvents = true, WithApplication = true)]
public class MemberTypeServiceTests : UmbracoIntegrationTest
{
private IMemberService MemberService => GetRequiredService<IMemberService>();
private IMemberTypeService MemberTypeService => GetRequiredService<IMemberTypeService>();
[Test]
public void Member_Cannot_Edit_Property()
{
IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
MemberTypeService.Save(memberType);
// re-get
memberType = MemberTypeService.Get(memberType.Id);
foreach (IPropertyType p in memberType.PropertyTypes)
{
Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias));
}
}
[Test]
public void Member_Can_Edit_Property()
{
IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
MemberTypeService.Save(memberType);
string prop = memberType.PropertyTypes.First().Alias;
memberType.SetMemberCanEditProperty(prop, true);
MemberTypeService.Save(memberType);
// re-get
memberType = MemberTypeService.Get(memberType.Id);
foreach (IPropertyType p in memberType.PropertyTypes.Where(x => x.Alias != prop))
{
Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias));
}
Assert.IsTrue(memberType.MemberCanEditProperty(prop));
}
[Test]
public void Member_Cannot_View_Property()
{
IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
MemberTypeService.Save(memberType);
// re-get
memberType = MemberTypeService.Get(memberType.Id);
foreach (IPropertyType p in memberType.PropertyTypes)
{
Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias));
}
}
[Test]
public void Member_Can_View_Property()
{
IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
MemberTypeService.Save(memberType);
string prop = memberType.PropertyTypes.First().Alias;
memberType.SetMemberCanViewProperty(prop, true);
MemberTypeService.Save(memberType);
// re-get
memberType = MemberTypeService.Get(memberType.Id);
foreach (IPropertyType p in memberType.PropertyTypes.Where(x => x.Alias != prop))
{
Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias));
}
Assert.IsTrue(memberType.MemberCanViewProperty(prop));
}
[Test]
public void Deleting_PropertyType_Removes_The_Property_From_Member()
{
IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
MemberTypeService.Save(memberType);
IMember member = MemberBuilder.CreateSimpleMember(memberType, "test", "[email protected]", "pass", "test");
MemberService.Save(member);
int initProps = member.Properties.Count;
// remove a property (NOT ONE OF THE DEFAULTS)
Dictionary<string, PropertyType> standardProps = ConventionsHelper.GetStandardPropertyTypeStubs(ShortStringHelper);
memberType.RemovePropertyType(memberType.PropertyTypes.First(x => standardProps.ContainsKey(x.Alias) == false).Alias);
MemberTypeService.Save(memberType);
// re-load it from the db
member = MemberService.GetById(member.Id);
Assert.AreEqual(initProps - 1, member.Properties.Count);
}
[Test]
public void Cannot_Save_MemberType_With_Empty_Name()
{
// Arrange
IMemberType memberType = MemberTypeBuilder.CreateSimpleMemberType("memberTypeAlias", string.Empty);
// Act & Assert
Assert.Throws<ArgumentException>(() => MemberTypeService.Save(memberType));
}
[Test]
public void Empty_Description_Is_Always_Null_After_Saving_Member_Type()
{
IMemberTypeService service = MemberTypeService;
MemberType memberType = MemberTypeBuilder.CreateSimpleMemberType();
memberType.Description = null;
service.Save(memberType);
MemberType memberType2 = MemberTypeBuilder.CreateSimpleMemberType("memberType2", "Member Type 2");
memberType2.Description = string.Empty;
service.Save(memberType2);
Assert.IsNull(memberType.Description);
Assert.IsNull(memberType2.Description);
}
// [Test]
// public void Can_Save_MemberType_Structure_And_Create_A_Member_Based_On_It()
// {
// // Arrange
// var cs = MemberService;
// var cts = MemberTypeService;
// var dtdYesNo = DataTypeService.GetDataTypeDefinitionById(-49);
// var ctBase = new MemberType(-1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" };
// ctBase.AddPropertyType(new PropertyType(dtdYesNo)
// {
// Name = "Hide From Navigation",
// Alias = Constants.Conventions.Content.NaviHide
// }
// /*,"Navigation"*/);
// cts.Save(ctBase);
// var ctHomePage = new MemberType(ctBase)
// {
// Name = "Home Page",
// Alias = "HomePage",
// Icon = "settingDomain.gif",
// Thumbnail = "folder.png",
// AllowedAsRoot = true
// };
// ctHomePage.AddPropertyType(new PropertyType(dtdYesNo) { Name = "Some property", Alias = "someProperty" }
// /*,"Navigation"*/);
// cts.Save(ctHomePage);
// // Act
// var homeDoc = cs.CreateMember("Test", "[email protected]", "test", "HomePage");
// // Assert
// Assert.That(ctBase.HasIdentity, Is.True);
// Assert.That(ctHomePage.HasIdentity, Is.True);
// Assert.That(homeDoc.HasIdentity, Is.True);
// Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id));
// }
// [Test]
// public void Can_Create_And_Save_MemberType_Composition()
// {
// /*
// * Global
// * - Components
// * - Category
// */
// var service = ContentTypeService;
// var global = MemberTypeBuilder.CreateSimpleContentType("global", "Global");
// service.Save(global);
// var components = MemberTypeBuilder.CreateSimpleContentType("components", "Components", global);
// service.Save(components);
// var component = MemberTypeBuilder.CreateSimpleContentType("component", "Component", components);
// service.Save(component);
// var category = MemberTypeBuilder.CreateSimpleContentType("category", "Category", global);
// service.Save(category);
// var success = category.AddContentType(component);
// Assert.That(success, Is.False);
// }
// [Test]
// public void Can_Remove_ContentType_Composition_From_ContentType()
// {
// //Test for U4-2234
// var cts = ContentTypeService;
// //Arrange
// var component = CreateComponent();
// cts.Save(component);
// var banner = CreateBannerComponent(component);
// cts.Save(banner);
// var site = CreateSite();
// cts.Save(site);
// var homepage = CreateHomepage(site);
// cts.Save(homepage);
// //Add banner to homepage
// var added = homepage.AddContentType(banner);
// cts.Save(homepage);
// //Assert composition
// var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias);
// var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName"));
// Assert.That(added, Is.True);
// Assert.That(bannerExists, Is.True);
// Assert.That(bannerPropertyExists, Is.True);
// Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6));
// //Remove banner from homepage
// var removed = homepage.RemoveContentType(banner.Alias);
// cts.Save(homepage);
// //Assert composition
// var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias);
// var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName"));
// Assert.That(removed, Is.True);
// Assert.That(bannerStillExists, Is.False);
// Assert.That(bannerPropertyStillExists, Is.False);
// Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4));
// }
// [Test]
// public void Can_Copy_ContentType_By_Performing_Clone()
// {
// // Arrange
// var service = ContentTypeService;
// var metaContentType = MemberTypeBuilder.CreateMetaContentType();
// service.Save(metaContentType);
// var simpleContentType = MemberTypeBuilder.CreateSimpleContentType("category", "Category", metaContentType);
// service.Save(simpleContentType);
// var categoryId = simpleContentType.Id;
// // Act
// var sut = simpleContentType.Clone("newcategory");
// service.Save(sut);
// // Assert
// Assert.That(sut.HasIdentity, Is.True);
// var contentType = service.GetContentType(sut.Id);
// var category = service.GetContentType(categoryId);
// Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True);
// Assert.AreEqual(contentType.ParentId, category.ParentId);
// Assert.AreEqual(contentType.Level, category.Level);
// Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count());
// Assert.AreNotEqual(contentType.Id, category.Id);
// Assert.AreNotEqual(contentType.Key, category.Key);
// Assert.AreNotEqual(contentType.Path, category.Path);
// Assert.AreNotEqual(contentType.SortOrder, category.SortOrder);
// Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id);
// Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id);
// }
// private ContentType CreateComponent()
// {
// var component = new ContentType(-1)
// {
// Alias = "component",
// Name = "Component",
// Description = "ContentType used for Component grouping",
// Icon = ".sprTreeDoc3",
// Thumbnail = "doc.png",
// SortOrder = 1,
// CreatorId = 0,
// Trashed = false
// };
// var contentCollection = new PropertyTypeCollection();
// contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 });
// component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 });
// return component;
// }
// private ContentType CreateBannerComponent(ContentType parent)
// {
// var banner = new ContentType(parent)
// {
// Alias = "banner",
// Name = "Banner Component",
// Description = "ContentType used for Banner Component",
// Icon = ".sprTreeDoc3",
// Thumbnail = "doc.png",
// SortOrder = 1,
// CreatorId = 0,
// Trashed = false
// };
// var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext)
// {
// Alias = "bannerName",
// Name = "Banner Name",
// Description = "",
// HelpText = "",
// Mandatory = false,
// SortOrder = 2,
// DataTypeDefinitionId = -88
// };
// banner.AddPropertyType(propertyType, "Component");
// return banner;
// }
// private ContentType CreateSite()
// {
// var site = new ContentType(-1)
// {
// Alias = "site",
// Name = "Site",
// Description = "ContentType used for Site inheritence",
// Icon = ".sprTreeDoc3",
// Thumbnail = "doc.png",
// SortOrder = 2,
// CreatorId = 0,
// Trashed = false
// };
// var contentCollection = new PropertyTypeCollection();
// contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 });
// site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 });
// return site;
// }
// private ContentType CreateHomepage(ContentType parent)
// {
// var contentType = new ContentType(parent)
// {
// Alias = "homepage",
// Name = "Homepage",
// Description = "ContentType used for the Homepage",
// Icon = ".sprTreeDoc3",
// Thumbnail = "doc.png",
// SortOrder = 1,
// CreatorId = 0,
// Trashed = false
// };
// var contentCollection = new PropertyTypeCollection();
// contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 });
// contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 });
// contentCollection.Add(new PropertyType(new Guid(), DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 });
// contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 });
// return contentType;
// }
// private IEnumerable<IContentType> CreateContentTypeHierarchy()
// {
// //create the master type
// var masterContentType = MemberTypeBuilder.CreateSimpleContentType("masterContentType", "MasterContentType");
// masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE");
// ContentTypeService.Save(masterContentType);
// //add the one we just created
// var list = new List<IContentType> { masterContentType };
// for (var i = 0; i < 10; i++)
// {
// var contentType = MemberTypeBuilder.CreateSimpleContentType("childType" + i, "ChildType" + i,
// //make the last entry in the list, this one's parent
// list.Last());
// list.Add(contentType);
// }
// return list;
// }
}
}
| |
// 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 testcase attempts to checks GetDirectories/GetFiles with the following ReparsePoint implementations
- Mount Volumes
**/
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using Xunit;
public class Directory_ReparsePoints_MountVolume
{
private delegate void ExceptionCode();
private static bool s_pass = true;
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // testing mounting volumes and reparse points
public static void runTest()
{
try
{
Stopwatch watch;
const String MountPrefixName = "LaksMount";
String mountedDirName;
String dirNameWithoutRoot;
String dirNameReferedFromMountedDrive;
String dirName;
String[] expectedFiles;
String[] files;
String[] expectedDirs;
String[] dirs;
List<String> list;
watch = new Stopwatch();
watch.Start();
try
{
//Scenario 1: Vanilla - Different drive is mounted on the current drive
Console.WriteLine("Scenario 1 - Vanilla: Different drive is mounted on the current drive: {0}", watch.Elapsed);
string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent();
if (FileSystemDebugInfo.IsCurrentDriveNTFS() && otherDriveInMachine != null)
{
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName));
try
{
Console.WriteLine("Creating directory " + mountedDirName);
Directory.CreateDirectory(mountedDirName);
MountHelper.Mount(otherDriveInMachine.Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(otherDriveInMachine, ManageFileSystem.DirPrefixName);
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
//Files
expectedFiles = fileManager.GetAllFiles();
list = new List<String>();
//We will only test the filenames since they are unique
foreach (String file in expectedFiles)
list.Add(Path.GetFileName(file));
files = Directory.GetFiles(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(files.Length == list.Count, "Err_3947g! wrong count");
for (int i = 0; i < expectedFiles.Length; i++)
{
if (Eval(list.Contains(Path.GetFileName(files[i])), "Err_582bmw! No file found: {0}", files[i]))
list.Remove(Path.GetFileName(files[i]));
}
if (!Eval(list.Count == 0, "Err_891vut! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
//Directories
expectedDirs = fileManager.GetAllDirectories();
list = new List<String>();
foreach (String dir in expectedDirs)
list.Add(dir.Substring(dirName.Length));
dirs = Directory.GetDirectories(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(dirs.Length == list.Count, "Err_813weq! wrong count");
for (int i = 0; i < dirs.Length; i++)
{
string exDir = dirs[i].Substring(dirNameReferedFromMountedDrive.Length);
if (Eval(list.Contains(exDir), "Err_287kkm! No file found: {0}", exDir))
list.Remove(exDir);
}
if (!Eval(list.Count == 0, "Err_921mhs! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String value in list)
Console.WriteLine(value);
}
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
else
{
Console.WriteLine("Skipping since drive is not NTFS and there is no other drive on the machine");
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_768lme! Exception caught in scenario: {0}", ex);
}
//Scenario 2: Current drive is mounted on a different drive
Console.WriteLine(Environment.NewLine + "Scenario 2 - Current drive is mounted on a different drive: {0}", watch.Elapsed);
try
{
string otherDriveInMachine = IOServices.GetNtfsDriveOtherThanCurrent();
if (otherDriveInMachine != null)
{
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(otherDriveInMachine.Substring(0, 3), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
//Files
expectedFiles = fileManager.GetAllFiles();
list = new List<String>();
//We will only test the filenames since they are unique
foreach (String file in expectedFiles)
list.Add(Path.GetFileName(file));
files = Directory.GetFiles(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(files.Length == list.Count, "Err_689myg! wrong count");
for (int i = 0; i < expectedFiles.Length; i++)
{
if (Eval(list.Contains(Path.GetFileName(files[i])), "Err_894vhm! No file found: {0}", files[i]))
list.Remove(Path.GetFileName(files[i]));
}
if (!Eval(list.Count == 0, "Err_952qkj! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
//Directories
expectedDirs = fileManager.GetAllDirectories();
list = new List<String>();
foreach (String dir in expectedDirs)
list.Add(dir.Substring(dirName.Length));
dirs = Directory.GetDirectories(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(dirs.Length == list.Count, "Err_154vrz! wrong count");
for (int i = 0; i < dirs.Length; i++)
{
string exDir = dirs[i].Substring(dirNameReferedFromMountedDrive.Length);
if (Eval(list.Contains(exDir), "Err_301sao! No file found: {0}", exDir))
list.Remove(exDir);
}
if (!Eval(list.Count == 0, "Err_630gjj! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String value in list)
Console.WriteLine(value);
}
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
else
{
Console.WriteLine("Skipping since drive is not NTFS and there is no other drive on the machine");
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_231vwf! Exception caught in scenario: {0}", ex);
}
//scenario 3.1: Current drive is mounted on current drive
Console.WriteLine(Environment.NewLine + "Scenario 3.1 - Current drive is mounted on current drive: {0}", watch.Elapsed);
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Path.DirectorySeparatorChar.ToString(), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
//Files
expectedFiles = fileManager.GetAllFiles();
list = new List<String>();
//We will only test the filenames since they are unique
foreach (String file in expectedFiles)
list.Add(Path.GetFileName(file));
files = Directory.GetFiles(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(files.Length == list.Count, "Err_213fuo! wrong count");
for (int i = 0; i < expectedFiles.Length; i++)
{
if (Eval(list.Contains(Path.GetFileName(files[i])), "Err_499oxz! No file found: {0}", files[i]))
list.Remove(Path.GetFileName(files[i]));
}
if (!Eval(list.Count == 0, "Err_301gtz! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
//Directories
expectedDirs = fileManager.GetAllDirectories();
list = new List<String>();
foreach (String dir in expectedDirs)
list.Add(dir.Substring(dirName.Length));
dirs = Directory.GetDirectories(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(dirs.Length == list.Count, "Err_771dxv! wrong count");
for (int i = 0; i < dirs.Length; i++)
{
string exDir = dirs[i].Substring(dirNameReferedFromMountedDrive.Length);
if (Eval(list.Contains(exDir), "Err_315jey! No file found: {0}", exDir))
list.Remove(exDir);
}
if (!Eval(list.Count == 0, "Err_424opm! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String value in list)
Console.WriteLine(value);
}
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
else
{
Console.WriteLine("Drive is not NTFS. Skipping scenario");
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_493ojg! Exception caught in scenario: {0}", ex);
}
//scenario 3.2: Current drive is mounted on current directory
Console.WriteLine(Environment.NewLine + "Scenario 3.2 - Current drive is mounted on current directory: {0}", watch.Elapsed);
try
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
{
mountedDirName = Path.GetFullPath(ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), MountPrefixName));
try
{
Directory.CreateDirectory(mountedDirName);
MountHelper.Mount(Directory.GetCurrentDirectory().Substring(0, 2), mountedDirName);
dirName = ManageFileSystem.GetNonExistingDir(Directory.GetCurrentDirectory(), ManageFileSystem.DirPrefixName);
using (ManageFileSystem fileManager = new ManageFileSystem(dirName, 3, 100))
{
dirNameWithoutRoot = dirName.Substring(3);
dirNameReferedFromMountedDrive = Path.Combine(mountedDirName, dirNameWithoutRoot);
//Files
expectedFiles = fileManager.GetAllFiles();
list = new List<String>();
//We will only test the filenames since they are unique
foreach (String file in expectedFiles)
list.Add(Path.GetFileName(file));
files = Directory.GetFiles(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(files.Length == list.Count, "Err_253yit! wrong count");
for (int i = 0; i < expectedFiles.Length; i++)
{
if (Eval(list.Contains(Path.GetFileName(files[i])), "Err_798mjs! No file found: {0}", files[i]))
list.Remove(Path.GetFileName(files[i]));
}
if (!Eval(list.Count == 0, "Err_141lgl! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String fileName in list)
Console.WriteLine(fileName);
}
//Directories
expectedDirs = fileManager.GetAllDirectories();
list = new List<String>();
foreach (String dir in expectedDirs)
list.Add(dir.Substring(dirName.Length));
dirs = Directory.GetDirectories(dirNameReferedFromMountedDrive, "*.*", SearchOption.AllDirectories);
Eval(dirs.Length == list.Count, "Err_512oxq! wrong count");
for (int i = 0; i < dirs.Length; i++)
{
string exDir = dirs[i].Substring(dirNameReferedFromMountedDrive.Length);
if (Eval(list.Contains(exDir), "Err_907zbr! No file found: {0}", exDir))
list.Remove(exDir);
}
if (!Eval(list.Count == 0, "Err_574raf! wrong count: {0}", list.Count))
{
Console.WriteLine();
foreach (String value in list)
Console.WriteLine(value);
}
}
}
finally
{
MountHelper.Unmount(mountedDirName);
DeleteDir(mountedDirName, true);
}
}
else
{
Console.WriteLine("Drive is not NTFS. Skipping scenario");
}
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_432qcp! Exception caught in scenario: {0}", ex);
}
Console.WriteLine("Completed {0}", watch.Elapsed);
}
catch (Exception ex)
{
s_pass = false;
Console.WriteLine("Err_234rsgf! Uncaught exception in RunTest: {0}", ex);
}
Assert.True(s_pass);
}
private static void DeleteFile(String fileName)
{
if (File.Exists(fileName))
File.Delete(fileName);
}
private static void DeleteDir(String fileName, bool sub)
{
if (Directory.Exists(fileName))
Directory.Delete(fileName, sub);
}
//Checks for error
private static bool Eval(bool expression, String msg, params Object[] values)
{
return Eval(expression, String.Format(msg, values));
}
private static bool Eval<T>(T actual, T expected, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return retValue;
}
private static bool Eval(bool expression, String msg)
{
if (!expression)
{
s_pass = false;
Console.WriteLine(msg);
}
return expression;
}
//Checks for a particular type of exception
private static void CheckException<E>(ExceptionCode test, string error)
{
CheckException<E>(test, error, null);
}
//Checks for a particular type of exception and an Exception msg in the English locale
private static void CheckException<E>(ExceptionCode test, string error, String msgExpected)
{
bool exception = false;
try
{
test();
error = String.Format("{0} Exception NOT thrown ", error);
}
catch (Exception e)
{
if (e.GetType() == typeof(E))
{
exception = true;
if (System.Globalization.CultureInfo.CurrentUICulture.Name == "en-US" && msgExpected != null && e.Message != msgExpected)
{
exception = false;
error = String.Format("{0} Message Different: <{1}>", error, e.Message);
}
}
else
error = String.Format("{0} Exception type: {1}", error, e.GetType().Name);
}
Eval(exception, error);
}
}
| |
// 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 MultiplyLowUInt16()
{
var test = new SimpleBinaryOpTest__MultiplyLowUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MultiplyLowUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyLowUInt16 testClass)
{
var result = Avx2.MultiplyLow(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyLowUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.MultiplyLow(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MultiplyLowUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__MultiplyLowUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.MultiplyLow(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.MultiplyLow(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.MultiplyLow(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyLow), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyLow), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyLow), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.MultiplyLow(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.MultiplyLow(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.MultiplyLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.MultiplyLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.MultiplyLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MultiplyLowUInt16();
var result = Avx2.MultiplyLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MultiplyLowUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.MultiplyLow(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.MultiplyLow(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.MultiplyLow(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.MultiplyLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.MultiplyLow(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != BitConverter.ToUInt16(BitConverter.GetBytes(((uint)(left[0])) * right[0]), 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != BitConverter.ToUInt16(BitConverter.GetBytes(((uint)(left[i])) * right[i]), 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MultiplyLow)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/* ====================================================================
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 is1 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 TestCases.HSSF.Record
{
using System;
using NPOI.HSSF.Record;
using NUnit.Framework;
using NPOI.HSSF.Record.Cont;
using System.Text;
using System.IO;
using NPOI.Util;
/**
* Tests that records size calculates correctly.
*
* @author Jason Height (jheight at apache.org)
*/
[TestFixture]
public class TestUnicodeString
{
private static int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE;
/** a 4 character string requiring 16 bit encoding */
private static String STR_16_BIT = "A\u591A\u8A00\u8A9E";
public TestUnicodeString()
{
}
[Test]
public void TestSmallStringSize()
{
//Test a basic string
UnicodeString s = MakeUnicodeString("Test");
ConfirmSize(7, s);
//Test a small string that is uncompressed
s = MakeUnicodeString(STR_16_BIT);
s.OptionFlags = ((byte)0x01);
ConfirmSize(11, s);
//Test a compressed small string that has rich text formatting
s.String = "Test";
s.OptionFlags = ((byte)0x8);
UnicodeString.FormatRun r = new UnicodeString.FormatRun((short)0, (short)1);
s.AddFormatRun(r);
UnicodeString.FormatRun r2 = new UnicodeString.FormatRun((short)2, (short)2);
s.AddFormatRun(r2);
ConfirmSize(17, s);
//Test a uncompressed small string that has rich text formatting
s.String = STR_16_BIT;
s.OptionFlags = ((byte)0x9);
ConfirmSize(21, s);
//Test a compressed small string that has rich text and extended text
s.String = "Test";
s.OptionFlags = ((byte)0xC);
ConfirmSize(17, s);
// Extended phonetics data
// Minimum size is 14
// Also adds 4 bytes to hold the length
s.ExtendedRst=(
new UnicodeString.ExtRst()
);
ConfirmSize(35, s);
//Test a uncompressed small string that has rich text and extended text
s.String = STR_16_BIT;
s.OptionFlags = ((byte)0xD);
ConfirmSize(39, s);
s.ExtendedRst = (null);
ConfirmSize(21, s);
}
[Test]
public void TestPerfectStringSize()
{
//Test a basic string
UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1);
ConfirmSize(MAX_DATA_SIZE, s);
//Test an uncompressed string
//Note that we can only ever Get to a maximim size of 8227 since an uncompressed
//string is1 writing double bytes.
s = MakeUnicodeString((MAX_DATA_SIZE - 2 - 1) / 2,true);
s.OptionFlags = (byte)0x1;
ConfirmSize(MAX_DATA_SIZE - 1, s);
}
[Test]
public void TestPerfectRichStringSize()
{
//Test a rich text string
UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1 - 8 - 2);
s.AddFormatRun(new UnicodeString.FormatRun((short)1, (short)0));
s.AddFormatRun(new UnicodeString.FormatRun((short)2, (short)1));
s.OptionFlags=((byte)0x8);
ConfirmSize(MAX_DATA_SIZE, s);
//Test an uncompressed rich text string
//Note that we can only ever Get to a maximim size of 8227 since an uncompressed
//string is1 writing double bytes.
s = MakeUnicodeString((MAX_DATA_SIZE - 2 - 1 - 8 - 2) / 2,true);
s.AddFormatRun(new UnicodeString.FormatRun((short)1, (short)0));
s.AddFormatRun(new UnicodeString.FormatRun((short)2, (short)1));
s.OptionFlags = ((byte)0x9);
ConfirmSize(MAX_DATA_SIZE - 1, s);
}
[Test]
public void TestContinuedStringSize()
{
UnicodeString s = MakeUnicodeString(MAX_DATA_SIZE - 2 - 1 + 20);
ConfirmSize(MAX_DATA_SIZE + 4 + 1 + 20, s);
}
/** Tests that a string size calculation that fits neatly in two records, the second being a continue*/
[Test]
public void TestPerfectContinuedStringSize()
{
//Test a basic string
int strSize = RecordInputStream.MAX_RECORD_DATA_SIZE * 2;
//String overhead
strSize -= 3;
//Continue Record overhead
strSize -= 4;
//Continue Record additional byte overhead
strSize -= 1;
UnicodeString s = MakeUnicodeString(strSize);
ConfirmSize(MAX_DATA_SIZE * 2, s);
}
[Test]
public void TestFormatRun()
{
UnicodeString.FormatRun fr = new UnicodeString.FormatRun((short)4, (short)0x15c);
Assert.AreEqual(4, fr.CharacterPos);
Assert.AreEqual(0x15c, fr.FontIndex);
MemoryStream baos = new MemoryStream();
LittleEndianOutputStream out1 = new LittleEndianOutputStream(baos);
fr.Serialize(out1);
byte[] b = baos.ToArray();
Assert.AreEqual(4, b.Length);
Assert.AreEqual(4, b[0]);
Assert.AreEqual(0, b[1]);
Assert.AreEqual(0x5c, b[2]);
Assert.AreEqual(0x01, b[3]);
LittleEndianInputStream inp = new LittleEndianInputStream(
new MemoryStream(b)
);
fr = new UnicodeString.FormatRun(inp);
Assert.AreEqual(4, fr.CharacterPos);
Assert.AreEqual(0x15c, fr.FontIndex);
}
[Test]
public void TestExtRstFromEmpty()
{
UnicodeString.ExtRst ext = new UnicodeString.ExtRst();
Assert.AreEqual(0, ext.NumberOfRuns);
Assert.AreEqual(0, ext.FormattingFontIndex);
Assert.AreEqual(0, ext.FormattingOptions);
Assert.AreEqual("", ext.PhoneticText);
Assert.AreEqual(0, ext.PhRuns.Length);
Assert.AreEqual(10, ext.DataSize); // Excludes 4 byte header
MemoryStream baos = new MemoryStream();
LittleEndianOutputStream out1 = new LittleEndianOutputStream(baos);
ContinuableRecordOutput cout = new ContinuableRecordOutput(out1, 0xffff);
ext.Serialize(cout);
cout.WriteContinue();
byte[] b = baos.ToArray();
Assert.AreEqual(20, b.Length);
// First 4 bytes from the outputstream
Assert.AreEqual((sbyte)-1, (sbyte)b[0]);
Assert.AreEqual((sbyte)-1, (sbyte)b[1]);
Assert.AreEqual(14, b[2]);
Assert.AreEqual(00, b[3]);
// Reserved
Assert.AreEqual(1, b[4]);
Assert.AreEqual(0, b[5]);
// Data size
Assert.AreEqual(10, b[6]);
Assert.AreEqual(00, b[7]);
// Font*2
Assert.AreEqual(0, b[8]);
Assert.AreEqual(0, b[9]);
Assert.AreEqual(0, b[10]);
Assert.AreEqual(0, b[11]);
// 0 Runs
Assert.AreEqual(0, b[12]);
Assert.AreEqual(0, b[13]);
// Size=0, *2
Assert.AreEqual(0, b[14]);
Assert.AreEqual(0, b[15]);
Assert.AreEqual(0, b[16]);
Assert.AreEqual(0, b[17]);
// Last 2 bytes from the outputstream
Assert.AreEqual(ContinueRecord.sid, b[18]);
Assert.AreEqual(0, b[19]);
// Load in again and re-test
byte[] data = new byte[14];
Array.Copy(b, 4, data, 0, data.Length);
LittleEndianInputStream inp = new LittleEndianInputStream(
new MemoryStream(data)
);
ext = new UnicodeString.ExtRst(inp, data.Length);
Assert.AreEqual(0, ext.NumberOfRuns);
Assert.AreEqual(0, ext.FormattingFontIndex);
Assert.AreEqual(0, ext.FormattingOptions);
Assert.AreEqual("", ext.PhoneticText);
Assert.AreEqual(0, ext.PhRuns.Length);
}
[Test]
public void TestExtRstFromData()
{
byte[] data = new byte[] {
01, 00, 0x0C, 00,
00, 00, 0x37, 00,
00, 00,
00, 00, 00, 00,
00, 00 // Cruft at the end, as found from real files
};
Assert.AreEqual(16, data.Length);
LittleEndianInputStream inp = new LittleEndianInputStream(
new MemoryStream(data)
);
UnicodeString.ExtRst ext = new UnicodeString.ExtRst(inp, data.Length);
Assert.AreEqual(0x0c, ext.DataSize); // Excludes 4 byte header
Assert.AreEqual(0, ext.NumberOfRuns);
Assert.AreEqual(0x37, ext.FormattingOptions);
Assert.AreEqual(0, ext.FormattingFontIndex);
Assert.AreEqual("", ext.PhoneticText);
Assert.AreEqual(0, ext.PhRuns.Length);
}
[Test]
public void TestCorruptExtRstDetection()
{
byte[] data = new byte[] {
0x79, 0x79, 0x11, 0x11,
0x22, 0x22, 0x33, 0x33,
};
Assert.AreEqual(8, data.Length);
LittleEndianInputStream inp = new LittleEndianInputStream(
new MemoryStream(data)
);
UnicodeString.ExtRst ext = new UnicodeString.ExtRst(inp, data.Length);
// Will be empty
Assert.AreEqual(ext, new UnicodeString.ExtRst());
// If written, will be the usual size
Assert.AreEqual(10, ext.DataSize); // Excludes 4 byte header
// Is empty
Assert.AreEqual(0, ext.NumberOfRuns);
Assert.AreEqual(0, ext.FormattingOptions);
Assert.AreEqual(0, ext.FormattingFontIndex);
Assert.AreEqual("", ext.PhoneticText);
Assert.AreEqual(0, ext.PhRuns.Length);
}
[Test]
public void TestExtRstEqualsAndHashCode()
{
byte[] buf = new byte[200];
LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0);
String str = "\u1d02\u1d12\u1d22";
bos.WriteShort(1);
bos.WriteShort(5 * LittleEndianConsts.SHORT_SIZE + str.Length * 2 + 3 * LittleEndianConsts.SHORT_SIZE + 2); // data size
bos.WriteShort(0x4711);
bos.WriteShort(0x0815);
bos.WriteShort(1);
bos.WriteShort(str.Length);
bos.WriteShort(str.Length);
StringUtil.PutUnicodeLE(str, bos);
bos.WriteShort(1);
bos.WriteShort(1);
bos.WriteShort(3);
bos.WriteShort(42);
LittleEndianByteArrayInputStream in1 = new LittleEndianByteArrayInputStream(buf, 0, bos.WriteIndex);
UnicodeString.ExtRst extRst1 = new UnicodeString.ExtRst(in1, bos.WriteIndex);
in1 = new LittleEndianByteArrayInputStream(buf, 0, bos.WriteIndex);
UnicodeString.ExtRst extRst2 = new UnicodeString.ExtRst(in1, bos.WriteIndex);
Assert.AreEqual(extRst1, extRst2);
Assert.AreEqual(extRst1.GetHashCode(), extRst2.GetHashCode());
}
private static void ConfirmSize(int expectedSize, UnicodeString s)
{
ConfirmSize(expectedSize, s, 0);
}
/**
* Note - a value of zero for <c>amountUsedInCurrentRecord</c> would only ever occur just
* after a {@link ContinueRecord} had been started. In the initial {@link SSTRecord} this
* value starts at 8 (for the first {@link UnicodeString} written). In general, it can be
* any value between 0 and {@link #MAX_DATA_SIZE}
*/
private static void ConfirmSize(int expectedSize, UnicodeString s, int amountUsedInCurrentRecord)
{
ContinuableRecordOutput out1 = ContinuableRecordOutput.CreateForCountingOnly();
out1.WriteContinue();
for (int i = amountUsedInCurrentRecord; i > 0; i--)
{
out1.WriteByte(0);
}
int size0 = out1.TotalSize;
s.Serialize(out1);
int size1 = out1.TotalSize;
int actualSize = size1 - size0;
Assert.AreEqual(expectedSize, actualSize);
}
private static UnicodeString MakeUnicodeString(String s)
{
UnicodeString st = new UnicodeString(s);
st.OptionFlags = ((byte)0);
return st;
}
private static UnicodeString MakeUnicodeString(int numChars)
{
StringBuilder b = new StringBuilder(numChars);
for (int i = 0; i < numChars; i++)
{
b.Append(i % 10);
}
return MakeUnicodeString(b.ToString());
}
/**
* @param is16Bit if <c>true</c> the created string will have characters > 0x00FF
* @return a string of the specified number of characters
*/
private static UnicodeString MakeUnicodeString(int numChars, bool is16Bit)
{
StringBuilder b = new StringBuilder(numChars);
int charBase = is16Bit ? 0x8A00 : 'A';
for (int i = 0; i < numChars; i++)
{
char ch = (char)((i % 16) + charBase);
b.Append(ch);
}
return MakeUnicodeString(b.ToString());
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.2.6.3. Start or resume an exercise. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(ClockTime))]
public partial class StartResumePdu : SimulationManagementFamilyPdu, IEquatable<StartResumePdu>
{
/// <summary>
/// UTC time at which the simulation shall start or resume
/// </summary>
private ClockTime _realWorldTime = new ClockTime();
/// <summary>
/// Simulation clock time at which the simulation shall start or resume
/// </summary>
private ClockTime _simulationTime = new ClockTime();
/// <summary>
/// Identifier for the request
/// </summary>
private uint _requestID;
/// <summary>
/// Initializes a new instance of the <see cref="StartResumePdu"/> class.
/// </summary>
public StartResumePdu()
{
PduType = (byte)13;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(StartResumePdu left, StartResumePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(StartResumePdu left, StartResumePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._realWorldTime.GetMarshalledSize(); // this._realWorldTime
marshalSize += this._simulationTime.GetMarshalledSize(); // this._simulationTime
marshalSize += 4; // this._requestID
return marshalSize;
}
/// <summary>
/// Gets or sets the UTC time at which the simulation shall start or resume
/// </summary>
[XmlElement(Type = typeof(ClockTime), ElementName = "realWorldTime")]
public ClockTime RealWorldTime
{
get
{
return this._realWorldTime;
}
set
{
this._realWorldTime = value;
}
}
/// <summary>
/// Gets or sets the Simulation clock time at which the simulation shall start or resume
/// </summary>
[XmlElement(Type = typeof(ClockTime), ElementName = "simulationTime")]
public ClockTime SimulationTime
{
get
{
return this._simulationTime;
}
set
{
this._simulationTime = value;
}
}
/// <summary>
/// Gets or sets the Identifier for the request
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._realWorldTime.Marshal(dos);
this._simulationTime.Marshal(dos);
dos.WriteUnsignedInt((uint)this._requestID);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._realWorldTime.Unmarshal(dis);
this._simulationTime.Unmarshal(dis);
this._requestID = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<StartResumePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<realWorldTime>");
this._realWorldTime.Reflection(sb);
sb.AppendLine("</realWorldTime>");
sb.AppendLine("<simulationTime>");
this._simulationTime.Reflection(sb);
sb.AppendLine("</simulationTime>");
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("</StartResumePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as StartResumePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(StartResumePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._realWorldTime.Equals(obj._realWorldTime))
{
ivarsEqual = false;
}
if (!this._simulationTime.Equals(obj._simulationTime))
{
ivarsEqual = false;
}
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._realWorldTime.GetHashCode();
result = GenerateHash(result) ^ this._simulationTime.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
return result;
}
}
}
| |
/*
* 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 swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleWorkflow.Model
{
/// <summary>
/// Provides details of the <code>StartChildWorkflowExecution</code> decision.
///
///
/// <para>
/// <b>Access Control</b>
/// </para>
///
/// <para>
/// You can use IAM policies to control this decision's access to Amazon SWF resources
/// as follows:
/// </para>
/// <ul> <li>Use a <code>Resource</code> element with the domain name to limit the action
/// to only specified domains.</li> <li>Use an <code>Action</code> element to allow or
/// deny permission to call this action.</li> <li>Constrain the following parameters by
/// using a <code>Condition</code> element with the appropriate keys. <ul> <li> <code>tagList.member.N</code>:
/// The key is "swf:tagList.N" where N is the tag number from 0 to 4, inclusive.</li>
/// <li><code>taskList</code>: String constraint. The key is <code>swf:taskList.name</code>.</li>
/// <li><code>workflowType.name</code>: String constraint. The key is <code>swf:workflowType.name</code>.</li>
/// <li><code>workflowType.version</code>: String constraint. The key is <code>swf:workflowType.version</code>.</li>
/// </ul> </li> </ul>
/// <para>
/// If the caller does not have sufficient permissions to invoke the action, or the parameter
/// values fall outside the specified constraints, the action fails. The associated event
/// attribute's <b>cause</b> parameter will be set to OPERATION_NOT_PERMITTED. For details
/// and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using
/// IAM to Manage Access to Amazon SWF Workflows</a>.
/// </para>
/// </summary>
public partial class StartChildWorkflowExecutionDecisionAttributes
{
private ChildPolicy _childPolicy;
private string _control;
private string _executionStartToCloseTimeout;
private string _input;
private string _lambdaRole;
private List<string> _tagList = new List<string>();
private TaskList _taskList;
private string _taskPriority;
private string _taskStartToCloseTimeout;
private string _workflowId;
private WorkflowType _workflowType;
/// <summary>
/// Gets and sets the property ChildPolicy.
/// <para>
/// <i>Optional.</i> If set, specifies the policy to use for the child workflow executions
/// if the workflow execution being started is terminated by calling the <a>TerminateWorkflowExecution</a>
/// action explicitly or due to an expired timeout. This policy overrides the default
/// child policy specified when registering the workflow type using <a>RegisterWorkflowType</a>.
/// </para>
///
/// <para>
/// The supported child policies are:
/// </para>
/// <ul> <li><b>TERMINATE:</b> the child executions will be terminated.</li> <li><b>REQUEST_CANCEL:</b>
/// a request to cancel will be attempted for each child execution by recording a <code>WorkflowExecutionCancelRequested</code>
/// event in its history. It is up to the decider to take appropriate actions when it
/// receives an execution history with this event.</li> <li><b>ABANDON:</b> no action
/// will be taken. The child executions will continue to run.</li> </ul> <note>A child
/// policy for this workflow execution must be specified either as a default for the workflow
/// type or through this parameter. If neither this parameter is set nor a default child
/// policy was specified at registration time then a fault will be returned.</note>
/// </summary>
public ChildPolicy ChildPolicy
{
get { return this._childPolicy; }
set { this._childPolicy = value; }
}
// Check to see if ChildPolicy property is set
internal bool IsSetChildPolicy()
{
return this._childPolicy != null;
}
/// <summary>
/// Gets and sets the property Control.
/// <para>
/// <i>Optional.</i> Data attached to the event that can be used by the decider in subsequent
/// workflow tasks. This data is not sent to the child workflow execution.
/// </para>
/// </summary>
public string Control
{
get { return this._control; }
set { this._control = value; }
}
// Check to see if Control property is set
internal bool IsSetControl()
{
return this._control != null;
}
/// <summary>
/// Gets and sets the property ExecutionStartToCloseTimeout.
/// <para>
/// The total duration for this workflow execution. This overrides the defaultExecutionStartToCloseTimeout
/// specified when registering the workflow type.
/// </para>
///
/// <para>
/// The duration is specified in seconds; an integer greater than or equal to 0. The value
/// "NONE" can be used to specify unlimited duration.
/// </para>
/// <note>An execution start-to-close timeout for this workflow execution must be specified
/// either as a default for the workflow type or through this parameter. If neither this
/// parameter is set nor a default execution start-to-close timeout was specified at registration
/// time then a fault will be returned.</note>
/// </summary>
public string ExecutionStartToCloseTimeout
{
get { return this._executionStartToCloseTimeout; }
set { this._executionStartToCloseTimeout = value; }
}
// Check to see if ExecutionStartToCloseTimeout property is set
internal bool IsSetExecutionStartToCloseTimeout()
{
return this._executionStartToCloseTimeout != null;
}
/// <summary>
/// Gets and sets the property Input.
/// <para>
/// The input to be provided to the workflow execution.
/// </para>
/// </summary>
public string Input
{
get { return this._input; }
set { this._input = value; }
}
// Check to see if Input property is set
internal bool IsSetInput()
{
return this._input != null;
}
/// <summary>
/// Gets and sets the property LambdaRole.
/// <para>
/// The ARN of an IAM role that authorizes Amazon SWF to invoke AWS Lambda functions.
/// </para>
/// <note>In order for this workflow execution to invoke AWS Lambda functions, an appropriate
/// IAM role must be specified either as a default for the workflow type or through this
/// field.</note>
/// </summary>
public string LambdaRole
{
get { return this._lambdaRole; }
set { this._lambdaRole = value; }
}
// Check to see if LambdaRole property is set
internal bool IsSetLambdaRole()
{
return this._lambdaRole != null;
}
/// <summary>
/// Gets and sets the property TagList.
/// <para>
/// The list of tags to associate with the child workflow execution. A maximum of 5 tags
/// can be specified. You can list workflow executions with a specific tag by calling
/// <a>ListOpenWorkflowExecutions</a> or <a>ListClosedWorkflowExecutions</a> and specifying
/// a <a>TagFilter</a>.
/// </para>
/// </summary>
public List<string> TagList
{
get { return this._tagList; }
set { this._tagList = value; }
}
// Check to see if TagList property is set
internal bool IsSetTagList()
{
return this._tagList != null && this._tagList.Count > 0;
}
/// <summary>
/// Gets and sets the property TaskList.
/// <para>
/// The name of the task list to be used for decision tasks of the child workflow execution.
/// </para>
/// <note>A task list for this workflow execution must be specified either as a default
/// for the workflow type or through this parameter. If neither this parameter is set
/// nor a default task list was specified at registration time then a fault will be returned.</note>
///
/// <para>
/// The specified string must not start or end with whitespace. It must not contain a
/// <code>:</code> (colon), <code>/</code> (slash), <code>|</code> (vertical bar), or
/// any control characters (\u0000-\u001f | \u007f - \u009f). Also, it must not contain
/// the literal string quotarnquot.
/// </para>
/// </summary>
public TaskList TaskList
{
get { return this._taskList; }
set { this._taskList = value; }
}
// Check to see if TaskList property is set
internal bool IsSetTaskList()
{
return this._taskList != null;
}
/// <summary>
/// Gets and sets the property TaskPriority.
/// <para>
/// <i>Optional.</i> A task priority that, if set, specifies the priority for a decision
/// task of this workflow execution. This overrides the defaultTaskPriority specified
/// when registering the workflow type. Valid values are integers that range from Java's
/// <code>Integer.MIN_VALUE</code> (-2147483648) to <code>Integer.MAX_VALUE</code> (2147483647).
/// Higher numbers indicate higher priority.
/// </para>
///
/// <para>
/// For more information about setting task priority, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html">Setting
/// Task Priority</a> in the <i>Amazon Simple Workflow Developer Guide</i>.
/// </para>
/// </summary>
public string TaskPriority
{
get { return this._taskPriority; }
set { this._taskPriority = value; }
}
// Check to see if TaskPriority property is set
internal bool IsSetTaskPriority()
{
return this._taskPriority != null;
}
/// <summary>
/// Gets and sets the property TaskStartToCloseTimeout.
/// <para>
/// Specifies the maximum duration of decision tasks for this workflow execution. This
/// parameter overrides the <code>defaultTaskStartToCloseTimout</code> specified when
/// registering the workflow type using <a>RegisterWorkflowType</a>.
/// </para>
///
/// <para>
/// The duration is specified in seconds; an integer greater than or equal to 0. The value
/// "NONE" can be used to specify unlimited duration.
/// </para>
/// <note>A task start-to-close timeout for this workflow execution must be specified
/// either as a default for the workflow type or through this parameter. If neither this
/// parameter is set nor a default task start-to-close timeout was specified at registration
/// time then a fault will be returned.</note>
/// </summary>
public string TaskStartToCloseTimeout
{
get { return this._taskStartToCloseTimeout; }
set { this._taskStartToCloseTimeout = value; }
}
// Check to see if TaskStartToCloseTimeout property is set
internal bool IsSetTaskStartToCloseTimeout()
{
return this._taskStartToCloseTimeout != null;
}
/// <summary>
/// Gets and sets the property WorkflowId.
/// <para>
/// <b>Required.</b> The <code>workflowId</code> of the workflow execution.
/// </para>
///
/// <para>
/// The specified string must not start or end with whitespace. It must not contain a
/// <code>:</code> (colon), <code>/</code> (slash), <code>|</code> (vertical bar), or
/// any control characters (\u0000-\u001f | \u007f - \u009f). Also, it must not contain
/// the literal string quotarnquot.
/// </para>
/// </summary>
public string WorkflowId
{
get { return this._workflowId; }
set { this._workflowId = value; }
}
// Check to see if WorkflowId property is set
internal bool IsSetWorkflowId()
{
return this._workflowId != null;
}
/// <summary>
/// Gets and sets the property WorkflowType.
/// <para>
/// <b>Required.</b> The type of the workflow execution to be started.
/// </para>
/// </summary>
public WorkflowType WorkflowType
{
get { return this._workflowType; }
set { this._workflowType = value; }
}
// Check to see if WorkflowType property is set
internal bool IsSetWorkflowType()
{
return this._workflowType != null;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OhlcvItemGenerator.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Creates realistic OHLCV items.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ExampleLibrary
{
using System;
using System.Collections.Generic;
using OxyPlot.Axes;
using OxyPlot.Series;
/// <summary>
/// Creates realistic OHLCV items.
/// </summary>
public static class OhlcvItemGenerator
{
/// <summary>
/// The random number generator.
/// </summary>
private static readonly Random Rand = new Random();
/// <summary>
/// Creates bars governed by a MR process.
/// </summary>
/// <param name="n">N.</param>
/// <param name="x0">X0.</param>
/// <param name="v0">V0.</param>
/// <param name="csigma">Csigma.</param>
/// <param name="esigma">Esigma.</param>
/// <param name="kappa">Kappa.</param>
/// <returns>
/// The process.
/// </returns>
public static IEnumerable<OhlcvItem> MRProcess(
int n,
double x0 = 100.0,
double v0 = 500,
double csigma = 0.50,
double esigma = 0.75,
double kappa = 0.01)
{
double x = x0;
var baseT = DateTime.UtcNow;
for (int ti = 0; ti < n; ti++)
{
var dx_c = -kappa * (x - x0) + RandomNormal(0, csigma);
var dx_1 = -kappa * (x - x0) + RandomNormal(0, esigma);
var dx_2 = -kappa * (x - x0) + RandomNormal(0, esigma);
var open = x;
var close = x = x + dx_c;
var low = Min(open, close, open + dx_1, open + dx_2);
var high = Max(open, close, open + dx_1, open + dx_2);
var dp = close - open;
var v = v0 * Math.Exp(Math.Abs(dp) / csigma);
var dir = (dp < 0) ?
-Math.Min(-dp / esigma, 1.0) :
Math.Min(dp / esigma, 1.0);
var skew = (dir + 1) / 2.0;
var buyvol = skew * v;
var sellvol = (1 - skew) * v;
var nowT = baseT.AddSeconds(ti);
var t = DateTimeAxis.ToDouble(nowT);
yield return new OhlcvItem(t, open, high, low, close, buyvol, sellvol);
}
}
/// <summary>
/// Finds the minimum of the specified a, b, c and d.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">B.</param>
/// <param name="c">C.</param>
/// <param name="d">D.</param>
/// <returns>The minimum.</returns>
private static double Min(double a, double b, double c, double d)
{
return Math.Min(a, Math.Min(b, Math.Min(c, d)));
}
/// <summary>
/// Finds the maximum of the specified a, b, c and d.
/// </summary>
/// <param name="a">A.</param>
/// <param name="b">B.</param>
/// <param name="c">C.</param>
/// <param name="d">D.</param>
/// <returns>The maximum.</returns>
private static double Max(double a, double b, double c, double d)
{
return Math.Max(a, Math.Max(b, Math.Max(c, d)));
}
/// <summary>
/// Gets random normal
/// </summary>
/// <param name="mu">Mu.</param>
/// <param name="sigma">Sigma.</param>
/// <returns></returns>
private static double RandomNormal(double mu, double sigma)
{
return InverseCumNormal(Rand.NextDouble(), mu, sigma);
}
/// <summary>
/// Fast approximation for inverse cum normal
/// </summary>
/// <param name="p">probability</param>
/// <param name="mu">Mean</param>
/// <param name="sigma">std dev</param>
private static double InverseCumNormal(double p, double mu, double sigma)
{
const double A1 = -3.969683028665376e+01;
const double A2 = 2.209460984245205e+02;
const double A3 = -2.759285104469687e+02;
const double A4 = 1.383577518672690e+02;
const double A5 = -3.066479806614716e+01;
const double A6 = 2.506628277459239e+00;
const double B1 = -5.447609879822406e+01;
const double B2 = 1.615858368580409e+02;
const double B3 = -1.556989798598866e+02;
const double B4 = 6.680131188771972e+01;
const double B5 = -1.328068155288572e+01;
const double C1 = -7.784894002430293e-03;
const double C2 = -3.223964580411365e-01;
const double C3 = -2.400758277161838e+00;
const double C4 = -2.549732539343734e+00;
const double C5 = 4.374664141464968e+00;
const double C6 = 2.938163982698783e+00;
const double D1 = 7.784695709041462e-03;
const double D2 = 3.224671290700398e-01;
const double D3 = 2.445134137142996e+00;
const double D4 = 3.754408661907416e+00;
const double Xlow = 0.02425;
const double Xhigh = 1.0 - Xlow;
double z, r;
if (p < Xlow)
{
// Rational approximation for the lower region 0<x<u_low
z = Math.Sqrt(-2.0 * Math.Log(p));
z = (((((C1 * z + C2) * z + C3) * z + C4) * z + C5) * z + C6) /
((((D1 * z + D2) * z + D3) * z + D4) * z + 1.0);
}
else if (p <= Xhigh)
{
// Rational approximation for the central region u_low<=x<=u_high
z = p - 0.5;
r = z * z;
z = (((((A1 * r + A2) * r + A3) * r + A4) * r + A5) * r + A6) * z /
(((((B1 * r + B2) * r + B3) * r + B4) * r + B5) * r + 1.0);
}
else
{
// Rational approximation for the upper region u_high<x<1
z = Math.Sqrt(-2.0 * Math.Log(1.0 - p));
z = -(((((C1 * z + C2) * z + C3) * z + C4) * z + C5) * z + C6) /
((((D1 * z + D2) * z + D3) * z + D4) * z + 1.0);
}
// error (f_(z) - x) divided by the cumulative's derivative
r = (CumN0(z) - p) * Math.Sqrt(2.0) * Math.Sqrt(Math.PI) * Math.Exp(0.5 * z * z);
// Halley's method
z -= r / (1 + (0.5 * z * r));
return mu + (z * sigma);
}
/// <summary>
/// Cumulative for a N(0,1) distribution
/// </summary>
/// <returns>The n0.</returns>
/// <param name="x">The x coordinate.</param>
private static double CumN0(double x)
{
const double B1 = 0.319381530;
const double B2 = -0.356563782;
const double B3 = 1.781477937;
const double B4 = -1.821255978;
const double B5 = 1.330274429;
const double P = 0.2316419;
const double C = 0.39894228;
if (x >= 0.0)
{
double t = 1.0 / (1.0 + (P * x));
return (1.0 - C * Math.Exp(-x * x / 2.0) * t * (t * (t * (t * (t * B5 + B4) + B3) + B2) + B1));
}
else
{
double t = 1.0 / (1.0 - P * x);
return (C * Math.Exp(-x * x / 2.0) * t * (t * (t * (t * (t * B5 + B4) + B3) + B2) + B1));
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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 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.IO;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using WebsitePanel.Providers;
using OS = WebsitePanel.Providers.OS;
using WebsitePanel.EnterpriseServer;
namespace WebsitePanel.EnterpriseServer
{
public class BackupController
{
public const string BACKUP_CATALOG_FILE_NAME = "BackupCatalog.xml";
private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB
private const string RSA_SETTINGS_KEY = "RSA_KEY";
public static int Backup(bool async, string taskId, int userId, int packageId, int serviceId, int serverId,
string backupFileName, int storePackageId, string storePackageFolder, string storeServerFolder,
bool deleteTempBackup)
{
// check demo account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// check admin account
accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin);
if ((serviceId > 0 || serverId > 0) && accountCheck < 0) return accountCheck;
if (accountCheck < 0)
deleteTempBackup = true;
// check if backup temp folder is available
string tempFolder = GetTempBackupFolder();
if (!FolderWriteAccessible(tempFolder))
return BusinessErrorCodes.ERROR_BACKUP_TEMP_FOLDER_UNAVAILABLE;
// check destination folder if required
if (!String.IsNullOrEmpty(storePackageFolder) &&
!RemoteServerFolderWriteAccessible(storePackageId, storePackageFolder))
return BusinessErrorCodes.ERROR_BACKUP_DEST_FOLDER_UNAVAILABLE;
// check server folder if required
if (!String.IsNullOrEmpty(storeServerFolder) &&
!FolderWriteAccessible(storeServerFolder))
return BusinessErrorCodes.ERROR_BACKUP_SERVER_FOLDER_UNAVAILABLE;
// check/reset delete flag
accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin);
if (accountCheck < 0 && !deleteTempBackup)
deleteTempBackup = true;
if (async)
{
BackupAsyncWorker worker = new BackupAsyncWorker();
worker.threadUserId = SecurityContext.User.UserId;
worker.taskId = taskId;
worker.userId = userId;
worker.packageId = packageId;
worker.serviceId = serviceId;
worker.serverId = serverId;
worker.backupFileName = backupFileName;
worker.storePackageId = storePackageId;
worker.storePackageFolder = storePackageFolder;
worker.storeServerFolder = storeServerFolder;
worker.deleteTempBackup = deleteTempBackup;
// run
worker.BackupAsync();
return 0;
}
else
{
return BackupInternal(taskId, userId, packageId, serviceId, serverId,
backupFileName, storePackageId, storePackageFolder, storeServerFolder,
deleteTempBackup);
}
}
public static int BackupInternal(string taskId, int userId, int packageId, int serviceId, int serverId,
string backupFileName, int storePackageId, string storePackageFolder, string storeServerFolder,
bool deleteTempBackup)
{
try
{
TaskManager.StartTask(taskId, "BACKUP", "BACKUP", backupFileName, SecurityContext.User.UserId);
// get the list of items to backup
TaskManager.Write("Calculate items to backup");
List<ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId);
if (items.Count == 0)
return 0;
// group items by item types
Dictionary<int, List<ServiceProviderItem>> groupedItems = new Dictionary<int, List<ServiceProviderItem>>();
// sort by groups
foreach (ServiceProviderItem item in items)
{
// add to group
if (!groupedItems.ContainsKey(item.TypeId))
groupedItems[item.TypeId] = new List<ServiceProviderItem>();
groupedItems[item.TypeId].Add(item);
}
// temp backup folder
string tempFolder = GetTempBackupFolder();
// create backup catalog file
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
// write backup file header
writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
writer.WriteStartElement("Backup");
writer.WriteStartElement("Info");
writer.WriteElementString("Name", backupFileName);
writer.WriteElementString("Created", DateTime.Now.ToString("r"));
writer.WriteElementString("User", GetLoggedUsername());
writer.WriteEndElement(); // Info
// determine the number of items to backup
int totalItems = 0;
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
if (!itemType.Backupable)
continue;
totalItems += groupedItems[itemTypeId].Count;
}
TaskManager.IndicatorMaximum = totalItems + 2;
TaskManager.IndicatorCurrent = 0;
// backup grouped items
writer.WriteStartElement("Items");
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId);
if (!itemType.Backupable)
continue;
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
// instantiate controller
IBackupController controller = null;
try
{
if (group.GroupController != null)
controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
if (controller != null)
{
// backup items
foreach (ServiceProviderItem item in groupedItems[itemTypeId])
{
TaskManager.Write(String.Format("Backup {0} of {1} - {2} '{3}'",
TaskManager.IndicatorCurrent + 1,
totalItems,
itemType.DisplayName,
item.Name));
try
{
int backupResult = BackupItem(tempFolder, writer, item, group, controller);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't backup item");
}
// increment progress
TaskManager.IndicatorCurrent += 1;
}
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
writer.WriteEndElement(); // Items
// close catalog writer
writer.WriteEndElement(); // Backup
writer.Close();
// convert to Xml document
XmlDocument doc = new XmlDocument();
doc.LoadXml(sw.ToString());
// sign XML document
//SignXmlDocument(doc);
// save signed doc to file
try
{
doc.Save(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't save backup catalog file: "
+ Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
return 0;
}
TaskManager.Write("Packaging backup...");
// compress backup files
string[] zipFiles = Directory.GetFiles(tempFolder);
string[] zipFileNames = new string[zipFiles.Length];
for (int i = 0; i < zipFiles.Length; i++)
zipFileNames[i] = Path.GetFileName(zipFiles[i]);
string backupFileNamePath = Path.Combine(tempFolder, backupFileName);
try
{
FileUtils.ZipFiles(backupFileNamePath, tempFolder, zipFileNames);
// delete packed files
foreach (string zipFile in zipFiles)
File.Delete(zipFile);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't zip backed up files");
return 0;
}
TaskManager.IndicatorCurrent += 1;
TaskManager.Write("Copying backup...");
// move/copy backup file
if (!String.IsNullOrEmpty(storeServerFolder))
{
// copy to local folder or UNC
try
{
string destFile = Path.Combine(storeServerFolder, backupFileName);
File.Copy(backupFileNamePath, destFile, true);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't copy backup to destination location");
return 0;
}
}
else if (storePackageId > 0)
{
try
{
// copy to space folder
int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os);
if (osServiceId > 0)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osServiceId);
string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId,
Path.Combine(storePackageFolder, backupFileName));
FileStream stream = new FileStream(backupFileNamePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[FILE_BUFFER_LENGTH];
int readBytes = 0;
do
{
// read package file
readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH);
if (readBytes < FILE_BUFFER_LENGTH)
// resize buffer
Array.Resize<byte>(ref buffer, readBytes);
// write remote backup file
os.AppendFileBinaryContent(remoteBackupPath, buffer);
}
while (readBytes == FILE_BUFFER_LENGTH);
stream.Close();
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't copy backup to destination hosting space");
return 0;
}
}
TaskManager.IndicatorCurrent += 1;
// delete backup file if required
if (deleteTempBackup)
{
try
{
// delete backup folder and all its contents
Directory.Delete(tempFolder, true);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't delete temporary backup folder");
return 0;
}
}
BackgroundTask topTask = TaskManager.TopTask;
topTask.IndicatorCurrent = topTask.IndicatorMaximum;
TaskController.UpdateTask(topTask);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return 0;
}
public static List<ServiceProviderItem> GetBackupItems(int userId,
int packageId, int serviceId, int serverId)
{
List<ServiceProviderItem> items = new List<ServiceProviderItem>();
if (packageId > 0)
{
items.AddRange(PackageController.GetPackageItems(packageId));
}
else if (serviceId > 0)
{
items.AddRange(PackageController.GetServiceItems(serviceId));
}
else if (serverId > 0)
{
// get server services
List<ServiceInfo> services = ServerController.GetServicesByServerId(serverId);
foreach (ServiceInfo service in services)
items.AddRange(PackageController.GetServiceItems(service.ServiceId));
}
else if (userId > 0)
{
List<PackageInfo> packages = new List<PackageInfo>();
// get own spaces
packages.AddRange(PackageController.GetMyPackages(userId));
// get user spaces
packages.AddRange(PackageController.GetPackages(userId));
// build collection
foreach (PackageInfo package in packages)
items.AddRange(PackageController.GetPackageItems(package.PackageId));
}
return items;
}
public static KeyValueBunch GetBackupContentSummary(int userId, int packageId,
int serviceId, int serverId)
{
Dictionary<string, List<string>> summary = new Dictionary<string, List<string>>();
// Get backup items
List<ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId);
// Prepare filter for in-loop sort
ServiceProviderItemType[] itemTypes = PackageController.GetServiceItemTypes().ToArray();
// Group service items by type id
foreach (ServiceProviderItem si in items)
{
ServiceProviderItemType itemType = Array.Find<ServiceProviderItemType>(itemTypes,
x => x.ItemTypeId == si.TypeId && x.Backupable);
// Sort out item types without backup capabilities
if (itemType != null)
{
// Mimic a grouping sort
if (!summary.ContainsKey(itemType.DisplayName))
summary.Add(itemType.DisplayName, new List<string>());
//
summary[itemType.DisplayName].Add(si.Name);
}
}
//
KeyValueBunch result = new KeyValueBunch();
// Convert grouped data into serializable format
foreach (string groupName in summary.Keys)
result[groupName] = String.Join(",", summary[groupName].ToArray());
//
return result;
}
public static int Restore(bool async, string taskId, int userId, int packageId, int serviceId, int serverId,
int storePackageId, string storePackageBackupPath, string storeServerBackupPath)
{
// check demo account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
if (accountCheck < 0) return accountCheck;
// check admin account
accountCheck = SecurityContext.CheckAccount(DemandAccount.IsAdmin);
if ((serviceId > 0 || serverId > 0) && accountCheck < 0) return accountCheck;
// check if backup temp folder is available
string tempFolder = GetTempBackupFolder();
if (!FolderWriteAccessible(tempFolder))
return BusinessErrorCodes.ERROR_BACKUP_TEMP_FOLDER_UNAVAILABLE;
// check server source path if required
if (!String.IsNullOrEmpty(storeServerBackupPath))
{
try
{
if (!File.Exists(storeServerBackupPath))
return BusinessErrorCodes.ERROR_RESTORE_BACKUP_SOURCE_NOT_FOUND;
}
catch
{
return BusinessErrorCodes.ERROR_RESTORE_BACKUP_SOURCE_UNAVAILABLE;
}
}
if (async)
{
BackupAsyncWorker worker = new BackupAsyncWorker();
worker.threadUserId = SecurityContext.User.UserId;
worker.taskId = taskId;
worker.userId = userId;
worker.packageId = packageId;
worker.serviceId = serviceId;
worker.serverId = serverId;
worker.storePackageId = storePackageId;
worker.storePackageBackupPath = storePackageBackupPath;
worker.storeServerBackupPath = storeServerBackupPath;
// run
worker.RestoreAsync();
return 0;
}
else
{
return RestoreInternal(taskId, userId, packageId, serviceId, serverId,
storePackageId, storePackageBackupPath, storeServerBackupPath);
}
}
public static int RestoreInternal(string taskId, int userId, int packageId, int serviceId, int serverId,
int storePackageId, string storePackageBackupPath, string storeServerBackupPath)
{
try
{
// copy backup from remote or local server
string backupFileName = (storePackageId > 0)
? Path.GetFileName(storePackageBackupPath) : Path.GetFileName(storeServerBackupPath);
TaskManager.StartTask(taskId, "BACKUP", "RESTORE", backupFileName, SecurityContext.User.UserId);
// create temp folder
string tempFolder = GetTempBackupFolder();
string backupFileNamePath = Path.Combine(tempFolder, backupFileName);
if (storePackageId > 0)
{
try
{
int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os);
if (osServiceId > 0)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osServiceId);
string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId,
storePackageBackupPath);
FileStream stream = new FileStream(backupFileNamePath, FileMode.Create, FileAccess.Write);
byte[] buffer = new byte[FILE_BUFFER_LENGTH];
int offset = 0;
do
{
// read remote content
buffer = os.GetFileBinaryChunk(remoteBackupPath, offset, FILE_BUFFER_LENGTH);
// write remote content
stream.Write(buffer, 0, buffer.Length);
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
stream.Close();
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't copy source backup set");
return 0;
}
}
else
{
backupFileNamePath = storeServerBackupPath;
}
try
{
// unpack archive
FileUtils.UnzipFiles(backupFileNamePath, tempFolder);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't unzip backup set");
return 0;
}
// load backup catalog
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME));
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't find/open backup catalog file");
return 0;
}
// validate XML document
//if (!ValidateXmlDocument(doc))
//{
// TaskManager.WriteError("Corrupted or altered backup catalog file has been read");
// return 0;
//}
// get the list of items to restore
string condition = "";
if (userId > 0)
{
// get user spaces
List<PackageInfo> packages = new List<PackageInfo>();
packages.AddRange(PackageController.GetMyPackages(userId));
packages.AddRange(PackageController.GetPackages(userId));
List<string> parts = new List<string>();
foreach (PackageInfo package in packages)
parts.Add("@packageId = " + package.PackageId.ToString());
condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
}
else if (packageId > 0)
{
condition = "[@packageId = " + packageId + "]";
}
else if (serviceId > 0)
{
condition = "[@serviceId = " + serviceId + "]";
}
else if (serverId > 0)
{
// get server services
List<ServiceInfo> services = ServerController.GetServicesByServerId(serverId);
List<string> parts = new List<string>();
foreach (ServiceInfo service in services)
parts.Add("@serviceId = " + service.ServiceId.ToString());
condition = "[" + String.Join(" or ", parts.ToArray()) + "]";
}
XmlNodeList itemNodes = doc.SelectNodes("Backup/Items/Item" + condition);
TaskManager.IndicatorMaximum = itemNodes.Count;
TaskManager.IndicatorCurrent = 0;
// group items by item types
Dictionary<int, List<XmlNode>> groupedItems = new Dictionary<int, List<XmlNode>>();
// sort by groups
foreach (XmlNode itemNode in itemNodes)
{
int itemTypeId = Utils.ParseInt(itemNode.Attributes["itemTypeId"].Value, 0);
// add to group
if (!groupedItems.ContainsKey(itemTypeId))
groupedItems[itemTypeId] = new List<XmlNode>();
groupedItems[itemTypeId].Add(itemNode);
}
// restore grouped items
foreach (int itemTypeId in groupedItems.Keys)
{
// load item type
ServiceProviderItemType itemTypeInfo = PackageController.GetServiceItemType(itemTypeId);
if (!itemTypeInfo.Backupable)
continue;
Type itemType = Type.GetType(itemTypeInfo.TypeName);
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemTypeInfo.GroupId);
// instantiate controller
IBackupController controller = null;
try
{
controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
if (controller != null)
{
// backup items
foreach (XmlNode itemNode in groupedItems[itemTypeId])
{
int itemId = Utils.ParseInt(itemNode.Attributes["itemId"].Value, 0);
string itemName = itemNode.Attributes["itemName"].Value;
int itemPackageId = Utils.ParseInt(itemNode.Attributes["packageId"].Value, 0);
int itemServiceId = Utils.ParseInt(itemNode.Attributes["serviceId"].Value, 0);
TaskManager.Write(String.Format("Restore {0} '{1}'",
itemTypeInfo.DisplayName, itemName));
try
{
int restoreResult = controller.RestoreItem(tempFolder, itemNode,
itemId, itemType, itemName, itemPackageId, itemServiceId, group);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't restore item");
}
TaskManager.IndicatorCurrent++;
}
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
// delete backup folder and all its contents
try
{
Directory.Delete(tempFolder, true);
}
catch (Exception ex)
{
TaskManager.WriteError(ex, "Can't delete temporary backup folder");
return 0;
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return 0;
}
public static int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item)
{
// load item type
ServiceProviderItemType itemType = PackageController.GetServiceItemType(item.TypeId);
if (!itemType.Backupable)
return -1;
// load group
ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId);
// create controller
IBackupController controller = null;
try
{
controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController;
if (controller != null)
{
return BackupItem(tempFolder, writer, item, group, controller);
}
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
return -2;
}
private static int BackupItem(string tempFolder, XmlWriter writer,
ServiceProviderItem item, ResourceGroupInfo group, IBackupController controller)
{
writer.WriteStartElement("Item");
writer.WriteAttributeString("itemId", item.Id.ToString());
writer.WriteAttributeString("itemTypeId", item.TypeId.ToString());
writer.WriteAttributeString("itemName", item.Name);
writer.WriteAttributeString("packageId", item.PackageId.ToString());
writer.WriteAttributeString("serviceId", item.ServiceId.ToString());
try
{
return controller.BackupItem(tempFolder, writer, item, group);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
finally
{
writer.WriteEndElement(); // Item
}
return 0;
}
public static int RestoreItem()
{
return 0;
}
public static void WriteFileElement(XmlWriter writer, string fileName, string filePath, long size)
{
writer.WriteStartElement("File");
writer.WriteAttributeString("name", fileName);
writer.WriteAttributeString("path", filePath);
writer.WriteAttributeString("size", size.ToString());
writer.WriteEndElement();
}
#region Utility Methods
public static bool FolderWriteAccessible(string path)
{
try
{
string tempFile = Path.Combine(path, "check");
StreamWriter writer = File.CreateText(tempFile);
writer.Close();
File.Delete(tempFile);
return true;
}
catch
{
return false;
}
}
public static bool RemoteServerFolderWriteAccessible(int packageId, string path)
{
try
{
// copy to space folder
int osServiceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os);
if (osServiceId > 0)
{
OS.OperatingSystem os = new OS.OperatingSystem();
ServiceProviderProxy.Init(os, osServiceId);
string remoteServerPathCheck = FilesController.GetFullPackagePath(packageId,
Path.Combine(path, "check.txt"));
//
os.CreateFile(remoteServerPathCheck);
os.AppendFileBinaryContent(remoteServerPathCheck, Encoding.UTF8.GetBytes(remoteServerPathCheck));
os.DeleteFile(remoteServerPathCheck);
}
//
return true;
}
catch
{ //
return false;
}
}
public static void SignXmlDocument(XmlDocument doc)
{
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = GetUserRSAKey();
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
}
public static bool ValidateXmlDocument(XmlDocument doc)
{
// Create a new SignedXml object and pass it
// the XML document class.
SignedXml signedXml = new SignedXml(doc);
// Find the "Signature" node and create a new
// XmlNodeList object.
XmlNodeList nodeList = doc.GetElementsByTagName("Signature");
// Throw an exception if no signature was found.
if (nodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// This example only supports one signature for
// the entire XML document. Throw an exception
// if more than one signature was found.
if (nodeList.Count >= 2)
{
throw new CryptographicException("Verification failed: More that one signature was found for the document.");
}
// Load the first <signature> node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(GetUserRSAKey());
}
public static RSA GetUserRSAKey()
{
int userId = SecurityContext.User.UserId;
if(SecurityContext.User.IsPeer)
userId = SecurityContext.User.OwnerId;
UserSettings settings = UserController.GetUserSettings(userId, RSA_SETTINGS_KEY);
string keyXml = settings[RSA_SETTINGS_KEY];
RSA rsa = RSA.Create();
if (String.IsNullOrEmpty(keyXml) || settings.UserId != userId)
{
// generate new key
keyXml = rsa.ToXmlString(true);
// store to settings
settings[RSA_SETTINGS_KEY] = keyXml;
settings.UserId = userId;
UserController.UpdateUserSettings(settings);
}
else
{
rsa.FromXmlString(keyXml);
}
return rsa;
}
private static string GetLoggedUsername()
{
string username = SecurityContext.User.Identity.Name;
UserInfo user = UserController.GetUser(SecurityContext.User.UserId);
if (user != null)
username = user.Username;
return username;
}
public static string GetTempBackupFolder()
{
string timeStamp = DateTime.Now.Ticks.ToString();
string tempFolder = Path.Combine(ConfigSettings.BackupsPath, GetLoggedUsername() + "_" + timeStamp);
// create folder
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);
return tempFolder;
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.Scene
{
public unsafe class AnimationComponent : BaseComponent
{
public AnimationComponent()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.AnimationComponentCreateInstance());
}
public AnimationComponent(uint pId) : base(pId)
{
}
public AnimationComponent(string pName) : base(pName)
{
}
public AnimationComponent(IntPtr pObjPtr) : base(pObjPtr)
{
}
public AnimationComponent(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public AnimationComponent(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate float _AnimationComponentGetSpeed(IntPtr animationComponent);
private static _AnimationComponentGetSpeed _AnimationComponentGetSpeedFunc;
internal static float AnimationComponentGetSpeed(IntPtr animationComponent)
{
if (_AnimationComponentGetSpeedFunc == null)
{
_AnimationComponentGetSpeedFunc =
(_AnimationComponentGetSpeed)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentGetSpeed"), typeof(_AnimationComponentGetSpeed));
}
return _AnimationComponentGetSpeedFunc(animationComponent);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AnimationComponentSetSpeed(IntPtr animationComponent, float val);
private static _AnimationComponentSetSpeed _AnimationComponentSetSpeedFunc;
internal static void AnimationComponentSetSpeed(IntPtr animationComponent, float val)
{
if (_AnimationComponentSetSpeedFunc == null)
{
_AnimationComponentSetSpeedFunc =
(_AnimationComponentSetSpeed)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentSetSpeed"), typeof(_AnimationComponentSetSpeed));
}
_AnimationComponentSetSpeedFunc(animationComponent, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AnimationComponentGetTarget(IntPtr animationComponent);
private static _AnimationComponentGetTarget _AnimationComponentGetTargetFunc;
internal static IntPtr AnimationComponentGetTarget(IntPtr animationComponent)
{
if (_AnimationComponentGetTargetFunc == null)
{
_AnimationComponentGetTargetFunc =
(_AnimationComponentGetTarget)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentGetTarget"), typeof(_AnimationComponentGetTarget));
}
return _AnimationComponentGetTargetFunc(animationComponent);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AnimationComponentSetTarget(IntPtr animationComponent, IntPtr val);
private static _AnimationComponentSetTarget _AnimationComponentSetTargetFunc;
internal static void AnimationComponentSetTarget(IntPtr animationComponent, IntPtr val)
{
if (_AnimationComponentSetTargetFunc == null)
{
_AnimationComponentSetTargetFunc =
(_AnimationComponentSetTarget)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentSetTarget"), typeof(_AnimationComponentSetTarget));
}
_AnimationComponentSetTargetFunc(animationComponent, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AnimationComponentGetMeshAsset(IntPtr animationComponent);
private static _AnimationComponentGetMeshAsset _AnimationComponentGetMeshAssetFunc;
internal static IntPtr AnimationComponentGetMeshAsset(IntPtr animationComponent)
{
if (_AnimationComponentGetMeshAssetFunc == null)
{
_AnimationComponentGetMeshAssetFunc =
(_AnimationComponentGetMeshAsset)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentGetMeshAsset"), typeof(_AnimationComponentGetMeshAsset));
}
return _AnimationComponentGetMeshAssetFunc(animationComponent);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AnimationComponentSetMeshAsset(IntPtr animationComponent, string meshAssetId);
private static _AnimationComponentSetMeshAsset _AnimationComponentSetMeshAssetFunc;
internal static void AnimationComponentSetMeshAsset(IntPtr animationComponent, string meshAssetId)
{
if (_AnimationComponentSetMeshAssetFunc == null)
{
_AnimationComponentSetMeshAssetFunc =
(_AnimationComponentSetMeshAsset)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentSetMeshAsset"), typeof(_AnimationComponentSetMeshAsset));
}
_AnimationComponentSetMeshAssetFunc(animationComponent, meshAssetId);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AnimationComponentCreateInstance();
private static _AnimationComponentCreateInstance _AnimationComponentCreateInstanceFunc;
internal static IntPtr AnimationComponentCreateInstance()
{
if (_AnimationComponentCreateInstanceFunc == null)
{
_AnimationComponentCreateInstanceFunc =
(_AnimationComponentCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AnimationComponentCreateInstance"), typeof(_AnimationComponentCreateInstance));
}
return _AnimationComponentCreateInstanceFunc();
}
}
#endregion
#region Properties
public float Speed
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.AnimationComponentGetSpeed(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AnimationComponentSetSpeed(ObjectPtr->ObjPtr, value);
}
}
public MeshComponent Target
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return new MeshComponent(InternalUnsafeMethods.AnimationComponentGetTarget(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AnimationComponentSetTarget(ObjectPtr->ObjPtr, value.ObjectPtr->ObjPtr);
}
}
public string MeshAsset
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AnimationComponentGetMeshAsset(ObjectPtr->ObjPtr));
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AnimationComponentSetMeshAsset(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using SQLite;
using System.Reflection;
using System.Collections;
using System.Threading.Tasks;
//using Java.Lang;
using System.Threading;
using System.Diagnostics;
using System.Linq.Expressions;
namespace SimpleDatabase
{
public class SimpleDatabaseConnection
{
Dictionary<Tuple<Type, string>, Dictionary<int, Dictionary<int, Object>>> MemoryStore = new Dictionary<Tuple<Type, string>, Dictionary<int, Dictionary<int, object>>>();
Dictionary<Type, Dictionary<object, object>> ObjectsDict = new Dictionary<Type, Dictionary<object, object>>();
//Dictionary<Type,List<object>> Objects = new Dictionary<Type, List<object>> ();
Dictionary<Tuple<Type, string>, List<SimpleDatabaseGroup>> Groups = new Dictionary<Tuple<Type, string>, List<SimpleDatabaseGroup>>();
Dictionary<Type, GroupInfo> GroupInfoDict = new Dictionary<Type, GroupInfo>();
object groupLocker = new object();
object memStoreLocker = new object();
object writeLocker = new object();
SQLiteConnection connection;
public SimpleDatabaseConnection(SQLiteConnection sqliteConnection)
{
connection = sqliteConnection;
init();
}
public SimpleDatabaseConnection(string databasePath)
{
connection = new SQLiteConnection(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.Create, true);
connection.ExecuteScalar<string>("PRAGMA journal_mode=WAL");
init();
}
void init()
{
#if iOS
Foundation.NSNotificationCenter.DefaultCenter.AddObserver((Foundation.NSString)"UIApplicationDidReceiveMemoryWarningNotification",delegate{
ClearMemory();
});
#endif
}
public void MakeClassInstant<T>(GroupInfo info)
{
MakeClassInstant(typeof(T), info);
}
public void MakeClassInstant<T>()
{
var t = typeof(T);
MakeClassInstant(t);
}
public void MakeClassInstant(Type type)
{
MakeClassInstant(type, null);
}
public void MakeClassInstant(Type type, GroupInfo info)
{
if (info == null)
info = GetGroupInfo(type);
SetGroups(type, info);
FillGroups(type, info);
if (Groups[new Tuple<Type, string>(type, info.ToString())].Count() == 0)
SetGroups(type, info);
}
public GroupInfo GetGroupInfo<T>()
{
return GetGroupInfo(typeof(T));
}
public GroupInfo GetGroupInfo(Type type)
{
if (GroupInfoDict.ContainsKey(type))
return GroupInfoDict[type];
bool groupDesc = false;
var groupBy = GetGroupByProperty(type, out groupDesc);
bool desc = false;
var orderBy = GetOrderByProperty(type, out desc);
var groupInfo = new GroupInfo();
if (groupBy != null)
{
groupInfo.GroupBy = groupBy.Name;
groupInfo.GroupOrderByDesc = groupDesc;
}
if (orderBy != null)
{
groupInfo.OrderBy = orderBy.Name;
groupInfo.OrderByDesc = desc;
}
GroupInfoDict.Add(type, groupInfo);
return groupInfo;
}
private void SetGroups(Type type, GroupInfo groupInfo)
{
List<SimpleDatabaseGroup> groups = CreateGroupInfo(type, groupInfo);
var tuple = new Tuple<Type, string>(type, groupInfo.ToString());
lock (groupLocker)
{
if (Groups.ContainsKey(tuple))
Groups[tuple] = groups;
else
Groups.Add(tuple, groups);
}
}
private List<SimpleDatabaseGroup> CreateGroupInfo(Type type, GroupInfo groupInfo)
{
List<SimpleDatabaseGroup> groups;
if (string.IsNullOrEmpty(groupInfo.GroupBy))
groups = new List<SimpleDatabaseGroup>() { new SimpleDatabaseGroup { GroupString = "" } };
else
{
var query = $"select distinct {groupInfo.GroupBy} as GroupString from {groupInfo.FromString(GetTableName(type))} {groupInfo.FilterString(true)} {groupInfo.OrderByString(true)} {groupInfo.LimitString()}";
var queryInfo = groupInfo.ConvertSqlFromNamed(query);
groups = connection.Query<SimpleDatabaseGroup>(queryInfo.Item1, queryInfo.Item2.ToArray()).ToList();
}
for (int i = 0; i < groups.Count(); i++)
{
var group = groups[i];
group.ClassName = type.Name;
group.Filter = groupInfo.Filter ?? "";
group.GroupBy = groupInfo.GroupBy ?? "";
group.OrderBy = groupInfo.OrderBy ?? "";
group.Order = i;
string rowQuery;
if (string.IsNullOrEmpty(groupInfo.GroupBy))
rowQuery = $"select count(*) from {groupInfo.FromString(GetTableName(type))} {groupInfo.FilterString(true)}";
else
rowQuery = $"select count(*) from {groupInfo.FromString(GetTableName(type))} where {groupInfo.GroupBy} = @GroupByParam {groupInfo.FilterString(false)}";
var queryInfo = groupInfo.ConvertSqlFromNamed(rowQuery, new Dictionary<string, object> { { "@GroupByParam", group.GroupString } });
group.RowCount = connection.ExecuteScalar<int>(queryInfo.Item1, queryInfo.Item2);
//}
if (groupInfo.Limit > 0)
group.RowCount = Math.Min(group.RowCount, groupInfo.Limit);
}
return groups;
}
string GetTableName(Type type)
{
var tableInfo = GetTableMapping(connection, type);
return tableInfo.TableName;
}
public void UpdateInstant<T>(GroupInfo info)
{
UpdateInstant(typeof(T), info);
}
public void UpdateInstant<T>()
{
UpdateInstant(typeof(T));
}
public void UpdateInstant(Type type)
{
UpdateInstant(type, null);
}
public void UpdateInstant(Type type, GroupInfo info)
{
if (info == null)
info = GetGroupInfo(type);
var tuple = new Tuple<Type, string>(type, info.ToString());
lock (memStoreLocker)
{
if (MemoryStore.ContainsKey(tuple))
{
MemoryStore[tuple] = new Dictionary<int, Dictionary<int, object>>();
}
}
FillGroups(type, info);
}
public void ClearMemory()
{
lock (memStoreLocker)
{
ObjectsDict.Clear();
ClearMemoryStore();
cacheQueue.Clear();
}
}
public void ClearMemoryStore()
{
lock (memStoreLocker)
{
MemoryStore.Clear();
lock (groupLocker)
{
Groups.Clear();
GroupInfoDict.Clear();
}
}
}
public void ClearMemory<T>()
{
var t = typeof(T);
ClearMemory(t);
}
public void ClearMemory(params Type[] types)
{
lock (memStoreLocker)
{
var toRemove = MemoryStore.Where(x => types.Contains(x.Key.Item1)).ToArray();
foreach (var item in toRemove)
{
MemoryStore.Remove(item.Key);
}
}
lock (groupLocker)
{
Groups.Clear();
}
}
public void ClearMemory<T>(GroupInfo groupInfo)
{
var t = typeof(T);
ClearMemory(t, groupInfo);
}
public void ClearMemory(Type type, GroupInfo groupInfo)
{
var tuple = new Tuple<Type, string>(type, groupInfo.ToString());
lock (memStoreLocker)
{
MemoryStore.Remove(tuple);
}
lock (groupLocker)
{
Groups.Clear();
}
}
public string SectionHeader<T>(int section)
{
return SectionHeader<T>(GetGroupInfo(typeof(T)), section);
}
public string SectionHeader<T>(GroupInfo info, int section)
{
if (info == null)
info = GetGroupInfo<T>();
lock (groupLocker)
{
var t = typeof(T);
var tuple = new Tuple<Type, string>(t, info.ToString());
if (!Groups.ContainsKey(tuple) || Groups[tuple].Count <= section)
FillGroups(t, info);
try
{
return Groups[tuple][section].GroupString;
}
catch (Exception ex)
{
return "";
}
}
}
public string[] QuickJump<T>()
{
return QuickJump<T>(GetGroupInfo<T>());
}
public string[] QuickJump<T>(GroupInfo info)
{
if (info == null)
info = GetGroupInfo<T>();
lock (groupLocker)
{
var t = typeof(T);
var tuple = new Tuple<Type, string>(t, info.ToString());
if (!Groups.ContainsKey(tuple))
FillGroups(t, info);
var groups = Groups[tuple];
var strings = groups.Select(x => string.IsNullOrEmpty(x.GroupString) ? "" : x.GroupString[0].ToString()).ToArray();
return strings;
}
}
public int NumberOfSections<T>()
{
return NumberOfSections<T>(GetGroupInfo<T>());
}
public int NumberOfSections<T>(GroupInfo info)
{
if (info == null)
info = GetGroupInfo<T>();
lock (groupLocker)
{
var t = typeof(T);
var tuple = new Tuple<Type, string>(t, info.ToString());
if (!Groups.ContainsKey(tuple))
FillGroups(t, info);
return Groups[tuple].Count;
}
}
public int RowsInSection<T>(int section)
{
return RowsInSection<T>(GetGroupInfo<T>(), section);
}
public int RowsInSection<T>(GroupInfo info, int section)
{
if (info == null)
info = GetGroupInfo<T>();
lock (groupLocker)
{
var group = GetGroup<T>(info, section);
return group.RowCount;
}
}
private SimpleDatabaseGroup GetGroup<T>(int section)
{
return GetGroup<T>(GetGroupInfo<T>(), section);
}
private SimpleDatabaseGroup GetGroup<T>(GroupInfo info, int section)
{
return GetGroup(typeof(T), info, section);
}
private SimpleDatabaseGroup GetGroup(Type t, GroupInfo info, int section)
{
var tuple = new Tuple<Type, string>(t, info.ToString());
List<SimpleDatabaseGroup> group = null;
int count = 0;
while ((group == null || group.Count <= section) && count < 5)
{
if (count > 0)
Debug.WriteLine("Trying to fill groups: {0}", count);
lock (groupLocker)
{
Groups.TryGetValue(tuple, out group);
}
if (group == null)
{
FillGroups(t, info);
}
count++;
}
if (group == null || section >= group.Count)
return new SimpleDatabaseGroup();
return group[section];
}
private void FillGroups(Type t, GroupInfo info)
{
List<SimpleDatabaseGroup> groups;
groups = CreateGroupInfo(t, info);
lock (groupLocker)
{
var tuple = new Tuple<Type, string>(t, info.ToString());
Groups[tuple] = groups;
}
}
public T ObjectForRow<T>(int section, int row) where T : new()
{
return ObjectForRow<T>(GetGroupInfo(typeof(T)), section, row);
}
public T ObjectForRow<T>(GroupInfo info, int section, int row) where T : new()
{
if (info == null)
info = GetGroupInfo<T>();
lock (memStoreLocker)
{
var type = typeof(T);
var tuple = new Tuple<Type, string>(type, info.ToString());
if (MemoryStore.ContainsKey(tuple))
{
var groups = MemoryStore[tuple];
if (groups.ContainsKey(section))
{
var g = groups[section];
if (g.ContainsKey(row))
return (T)groups[section][row];
}
}
Precache<T>(info, section);
return getObject<T>(info, section, row);
}
}
public T GetObject<T>(object primaryKey) where T : new()
{
try
{
var type = typeof(T);
if (!ObjectsDict.ContainsKey(type))
ObjectsDict[type] = new Dictionary<object, object>();
if (ObjectsDict[type].ContainsKey(primaryKey))
return (T)ObjectsDict[type][primaryKey];
//Debug.WriteLine("object not in objectsdict");
var pk = GetTableMapping(connection, type);
var query = $"select * from {pk.TableName} where {pk.PK.Name} = ? ";
T item = connection.Query<T>(query, primaryKey).FirstOrDefault();
return item != null ? GetIfCached(item) : item;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return default(T);
}
}
private T getObject<T>(GroupInfo info, int section, int row) where T : new()
{
try
{
T item;
var t = typeof(T);
var group = GetGroup<T>(info, section);
string query;
if (string.IsNullOrEmpty(info.GroupBy))
query = $"select * from {info.FromString(GetTableName(t))} {info.FilterString(true)} {info.OrderByString(true)} LIMIT {row}, 1";
else
query = $"select * from {info.FromString(GetTableName(t))} where {info.GroupBy} = @GroupByParam {info.FilterString(false)} {info.OrderByString(true)} LIMIT @LimitParam , 1";
var queryInfo = info.ConvertSqlFromNamed(query, new Dictionary<string, object> {
{"@GroupByParam",group.GroupString},
{"@LimitParam", row }
});
item = connection.Query<T>(queryInfo.Item1, queryInfo.Item2).FirstOrDefault();
if (item == null)
return new T();
var tuple = new Tuple<Type, string>(t, info.ToString());
lock (memStoreLocker)
{
if (!MemoryStore.ContainsKey(tuple))
MemoryStore.Add(tuple, new Dictionary<int, Dictionary<int, object>>());
var groups = MemoryStore[tuple];
if (!groups.ContainsKey(section))
groups.Add(section, new Dictionary<int, object>());
if (!groups[section].ContainsKey(row))
groups[section].Add(row, item);
else
groups[section][row] = item;
return GetIfCached(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return default(T);
}
}
public void AddObjectToDict(object item, Type t)
{
lock (groupLocker)
{
var primaryKey = GetTableMapping(connection, t);
if (primaryKey == null)
return;
object pk = primaryKey.PK.GetValue(item);
if (!ObjectsDict.ContainsKey(t))
ObjectsDict.Add(t, new Dictionary<object, object>());
ObjectsDict[t][pk] = item;
// if (!Objects.ContainsKey (t))
// Objects.Add (t, new List<object> ());
// if (!Objects [t].Contains (item))
// Objects [t].Add (item);
}
}
public void AddObjectToDict(object item)
{
AddObjectToDict(item, item.GetType());
}
public void RemoveObjectFromDict(object item)
{
RemoveObjectFromDict(item, item.GetType());
}
public void RemoveObjectFromDict(object item, Type t)
{
lock (groupLocker)
{
var primaryKey = GetTableMapping(connection, t);
if (primaryKey == null)
return;
object pk = primaryKey.PK.GetValue(item);
if (ObjectsDict.ContainsKey(t))
ObjectsDict[t].Remove(pk);
}
}
T GetIfCached<T>(T item)
{
lock (groupLocker)
{
var t = typeof(T);
var primaryKey = GetTableMapping(connection, t);
if (primaryKey == null)
return item;
var pk = primaryKey.PK.GetValue(item);
if (!ObjectsDict.ContainsKey(t))
ObjectsDict.Add(t, new Dictionary<object, object>());
object oldItem;
if (ObjectsDict[t].TryGetValue(pk, out oldItem))
{
return (T)oldItem;
}
ObjectsDict[t][pk] = item;
return item;
}
}
public int GetObjectCount<T>()
{
return GetObjectCount<T>(null);
}
public int GetObjectCount<T>(GroupInfo info)
{
if (info == null)
info = GetGroupInfo<T>();
var filterString = info.FilterString(true);
var t = typeof(T);
string query = $"Select count(*) from {info.FromString(GetTableName(t))} {filterString}";
var queryInfo = info.ConvertSqlFromNamed(query);
int count = connection.ExecuteScalar<int>(queryInfo.Item1, queryInfo.Item2);
if (info.Limit > 0)
return Math.Min(info.Limit, count);
return count;
}
public int GetDistinctObjectCount<T>(string column)
{
return GetDistinctObjectCount<T>(null, column);
}
public int GetDistinctObjectCount<T>(GroupInfo info, string column)
{
if (info == null)
info = GetGroupInfo<T>();
var filterString = info.FilterString(true);
var t = typeof(T);
string query = $"Select distinct count({column}) from {info.FromString(GetTableName(t))} {filterString} {info.LimitString()}";
var queryInfo = info.ConvertSqlFromNamed(query);
int count = connection.ExecuteScalar<int>(queryInfo.Item1, queryInfo.Item2);
if (info.Limit > 0)
return Math.Min(info.Limit, count);
return count;
}
public T GetObjectByIndex<T>(int index, GroupInfo info = null) where T : new()
{
T item;
var t = typeof(T);
if (info == null)
info = GetGroupInfo<T>();
var filterString = info.FilterString(true);
var query = $"select * from {info.FromString(GetTableName(t))} {filterString} {info.OrderByString(true)} LIMIT {index}, 1";
var queryInfo = info.ConvertSqlFromNamed(query);
item = connection.Query<T>(queryInfo.Item1, queryInfo.Item2).FirstOrDefault();
if (item == null)
return default(T);
return GetIfCached(item);
}
public List<T> GetObjects<T>(GroupInfo info) where T : new()
{
if (info == null)
info = GetGroupInfo<T>();
var filterString = info.FilterString(true);
var t = typeof(T);
string query = $"Select * from {info.FromString(GetTableName(t))} {filterString} {info.LimitString()}";
var queryInfo = info.ConvertSqlFromNamed(query);
return connection.Query<T>(queryInfo.Item1, queryInfo.Item2).ToList();
}
public void Precache<T>() where T : new()
{
Precache<T>(GetGroupInfo(typeof(T)));
}
public void Precache<T>(GroupInfo info) where T : new()
{
return;
if (info == null)
info = GetGroupInfo<T>();
var type = typeof(T);
var tuple = new Tuple<Type, string>(type, info.ToString());
FillGroups(type, info);
lock (groupLocker)
{
if (Groups[tuple].Count() == 0)
SetGroups(type, info);
foreach (var group in Groups[tuple])
{
if (group.Loaded)
continue;
cacheQueue.AddLast(delegate
{
LoadItemsForGroup<T>(group);
});
}
}
StartQueue();
}
public void Precache<T>(int section) where T : new()
{
Precache<T>(GetGroupInfo(typeof(T)), section);
}
public void Precache<T>(GroupInfo info, int section) where T : new()
{
try
{
if (info == null)
info = GetGroupInfo<T>();
var type = typeof(T);
var group = GetGroup(type, info, section);
cacheQueue.AddFirst(delegate
{
LoadItemsForGroup<T>(group);
});
StartQueue();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private void LoadItemsForGroup<T>(SimpleDatabaseGroup group) where T : new()
{
try
{
if (group.Loaded)
return;
Debug.WriteLine("Loading items for group");
var type = typeof(T);
string query = $"select * from {group.FromString(type.Name)} where {group.GroupBy} = @GroupByParam {group.FilterString(false)} {group.OrderByString(true)} LIMIT @LimitParam , 50";
List<T> items;
int current = 0;
bool hasMore = true;
while (hasMore)
{
if (string.IsNullOrEmpty(group.GroupBy))
query = $"select * from {group.FromString(type.Name)} {group.FilterString(true)} {group.OrderByString(true)} LIMIT {current}, 50";
var queryInfo = group.ConvertSqlFromNamed(query, new Dictionary<string, object> {
{"@GroupByParam",group.GroupString},
{"@LimitParam", current }
});
items = connection.Query<T>(queryInfo.Item1, queryInfo.Item2).ToList();
{
Dictionary<int, object> memoryGroup;
lock (memStoreLocker)
{
var tuple = new Tuple<Type, string>(type, group.ToString());
if (!MemoryStore.ContainsKey(tuple))
{
MemoryStore.Add(tuple, new Dictionary<int, Dictionary<int, object>>());
}
if (!MemoryStore[tuple].ContainsKey(group.Order))
try
{
MemoryStore[tuple].Add(group.Order, new Dictionary<int, object>());
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
memoryGroup = MemoryStore[tuple][group.Order];
}
for (int i = 0; i < items.Count; i++)
{
lock (groupLocker)
{
if (memoryGroup.ContainsKey(i + current))
memoryGroup[i + current] = items[i];
else
memoryGroup.Add(i + current, items[i]);
}
GetIfCached(items[i]);
}
}
current += items.Count;
if (current == group.RowCount)
hasMore = false;
}
Debug.WriteLine("group loaded");
group.Loaded = true;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
LinkedList<Action> cacheQueue = new LinkedList<Action>();
object locker = new object();
bool queueIsRunning = false;
private void StartQueue()
{
return;
lock (locker)
{
if (queueIsRunning)
return;
if (cacheQueue.Count == 0)
return;
queueIsRunning = true;
}
Task.Run(() => runQueue());
}
void runQueue()
{
Action action;
lock (locker)
{
if (cacheQueue.Count == 0)
{
queueIsRunning = false;
return;
}
try
{
//Task.Factory.StartNew (delegate {
action = cacheQueue.First();
cacheQueue.Remove(action);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
runQueue();
return;
}
}
if (action != null)
action();
//}).ContinueWith (delegate {
runQueue();
}
static Dictionary<Type, Tuple<PropertyInfo, bool>> groupByProperties = new Dictionary<Type, Tuple<PropertyInfo, bool>>();
static internal PropertyInfo GetGroupByProperty(Type type, out bool desc)
{
Tuple<PropertyInfo, bool> property;
if (groupByProperties.TryGetValue(type, out property))
{
desc = property.Item2;
return property.Item1;
}
foreach (var prop in type.GetProperties())
{
var attribtues = prop.GetCustomAttributes(false);
var visibleAtt = attribtues.Where(x => x is GroupByAttribute).FirstOrDefault() as GroupByAttribute;
if (visibleAtt != null)
{
desc = visibleAtt.Descending;
groupByProperties[type] = new Tuple<PropertyInfo, bool>(prop, desc);
return prop;
}
}
desc = false;
return null;
}
static Dictionary<Type, Tuple<PropertyInfo, bool>> orderByProperties = new Dictionary<Type, Tuple<PropertyInfo, bool>>();
internal static PropertyInfo GetOrderByProperty(Type type, out bool desc)
{
Tuple<PropertyInfo, bool> property;
if (orderByProperties.TryGetValue(type, out property))
{
desc = property.Item2;
return property.Item1;
}
foreach (var prop in type.GetProperties())
{
var attribtues = prop.GetCustomAttributes(false);
var visibleAtt = attribtues.Where(x => x is OrderByAttribute).FirstOrDefault() as OrderByAttribute;
if (visibleAtt != null)
{
desc = visibleAtt.Descending;
orderByProperties[type] = new Tuple<PropertyInfo, bool>(prop, desc);
return prop;
}
}
desc = false;
return null;
}
static Dictionary<Type, TableMapping> cachedTableMappings = new Dictionary<Type, TableMapping>();
static TableMapping GetTableMapping(SQLiteConnection connection, Type type)
{
TableMapping property;
if (!cachedTableMappings.TryGetValue(type, out property))
cachedTableMappings[type] = property = connection.GetMapping(type);
return property;
}
#region sqlite
public int InsertAll(System.Collections.IEnumerable objects)
{
var c = 0;
var types = new HashSet<Type>();
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.Insert(item);
if (i > 0)
{
AddObjectToDict(item);
types.Add(item.GetType());
c += i;
}
}
});
}
if (c > 0)
ClearMemory(types.ToArray());
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll(System.Collections.IEnumerable objects, string extra)
{
var c = 0;
var types = new HashSet<Type>();
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.Insert(item, extra);
if (i > 0)
{
AddObjectToDict(item);
types.Add(item.GetType());
c += i;
}
}
});
}
if (c > 0)
ClearMemory(types.ToArray());
return c;
}
public Task<int> InsertAllAsync(System.Collections.IEnumerable objects)
{
return Task.Run(() => connection.InsertAll(objects));
}
public Task<int> InsertAllAsync(System.Collections.IEnumerable objects, string extra)
{
return Task.Run(() => connection.InsertAll(objects, extra));
}
public AsyncTableQuery<T> TablesAsync<T>()
where T : new()
{
return new AsyncTableQuery<T>(connection.Table<T>());
}
public Task<int> InsertAsync(object item)
{
return Task.Run(() => Insert(item));
}
public Task<int> InsertAsync(object item, string extra)
{
return Task.Run(() => Insert(item, extra));
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll(System.Collections.IEnumerable objects, Type objType)
{
var c = 0;
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.Insert(item, objType);
if (i > 0)
{
AddObjectToDict(item);
c += i;
}
}
});
}
if (c > 0)
ClearMemory(objType);
return c;
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert(object obj)
{
var c = connection.Insert(obj);
if (c > 0)
{
ClearMemory(obj.GetType());
AddObjectToDict(obj);
}
return c;
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace(object obj)
{
var c = connection.InsertOrReplace(obj);
if (c > 0)
{
ClearMemory(obj.GetType());
AddObjectToDict(obj);
}
return c;
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert(object obj, Type objType)
{
var c = connection.Insert(obj, objType);
if (c > 0)
{
ClearMemory(objType);
AddObjectToDict(obj);
}
return c;
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace(object obj, Type objType)
{
var c = connection.InsertOrReplace(obj, objType);
if (c > 0)
{
ClearMemory(objType);
AddObjectToDict(obj);
}
return c;
}
public int InsertOrReplaceAll(System.Collections.IEnumerable objects)
{
var c = 0;
var types = new HashSet<Type>();
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.InsertOrReplace(item);
if (i > 0)
{
AddObjectToDict(item);
types.Add(item.GetType());
c += i;
}
}
});
}
if (c > 0)
ClearMemory(types.ToArray());
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertOrReplaceAll(System.Collections.IEnumerable objects, Type objType)
{
var c = 0;
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.InsertOrReplace(item, objType);
if (i > 0)
{
AddObjectToDict(item);
c += i;
}
}
});
}
if (c > 0)
ClearMemory(objType);
return c;
}
public void RunInTransaction(Action<SQLiteConnection> action)
{
lock (writeLocker)
{
connection.RunInTransaction(() => action(connection));
}
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert(object obj, string extra)
{
var c = connection.Insert(obj, extra);
if (c > 0)
{
ClearMemory(obj.GetType());
AddObjectToDict(obj);
}
return c;
}
/// <summary>
/// Inserts the given object and retrieves its
/// auto incremented primary key if it has one.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
//public int Insert (object obj, string extra, Type objType)
//{
// return connection.Insert (obj,extra,objType);
//}
public int Execute(string query, params object[] args)
{
return connection.Execute(query, args);
}
public Task<int> ExecuteAsync(string query, params object[] args)
{
return Task.Run(() => connection.Execute(query, args));
}
public List<T> Query<T>(string query, params object[] args) where T : new()
{
return connection.Query<T>(query, args);
}
public Task<List<T>> QueryAsync<T>(string query, params object[] args) where T : new()
{
return Task.Run(() => connection.Query<T>(query, args));
}
public int Delete(object objectToDelete)
{
var c = connection.Delete(objectToDelete);
if (c > 0)
{
ClearMemory(objectToDelete.GetType());
RemoveObjectFromDict(objectToDelete);
}
return c;
}
public int DeleteAll(System.Collections.IEnumerable objects)
{
var c = 0;
var types = new HashSet<Type>();
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.Delete(item);
if (i > 0)
{
RemoveObjectFromDict(item);
types.Add(item.GetType());
c += i;
}
}
});
}
if (c > 0)
ClearMemory(types.ToArray());
return c;
}
public int DeleteAll(System.Collections.IEnumerable objects, Type type)
{
var c = 0;
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.Delete(item, type);
if (i > 0)
{
RemoveObjectFromDict(item);
c += i;
}
}
});
}
if (c > 0)
ClearMemory(type);
return c;
}
public int Update(object obj)
{
var c = connection.Update(obj);
if (c > 0)
{
ClearMemory(obj.GetType());
AddObjectToDict(obj);
}
return c;
}
public Task<int> UpdateAsync(object obj)
{
return Task.Run(() =>
{
AddObjectToDict(obj);
return connection.Update(obj);
});
}
public int UpdateAll(System.Collections.IEnumerable objects)
{
var c = 0;
var types = new HashSet<Type>();
lock (writeLocker)
{
connection.RunInTransaction(() =>
{
foreach (var item in objects)
{
var i = connection.Update(item);
if (i > 0)
{
AddObjectToDict(item);
types.Add(item.GetType());
c += i;
}
}
});
}
if (c > 0)
ClearMemory(types.ToArray());
return c;
}
public Dictionary<Type, CreateTableResult> CreateTables(params Type[] types)
{
return connection.CreateTables(types);
}
public CreateTableResult CreateTable<T>() where T : new()
{
return connection.CreateTable<T>();
}
public T ExecuteScalar<T>(string query, params object[] args) where T : new()
{
return connection.ExecuteScalar<T>(query, args);
}
#endregion
public class AsyncTableQuery<T>
where T : new()
{
TableQuery<T> _innerQuery;
public AsyncTableQuery(TableQuery<T> innerQuery)
{
_innerQuery = innerQuery;
}
public AsyncTableQuery<T> Where(Expression<Func<T, bool>> predExpr)
{
return new AsyncTableQuery<T>(_innerQuery.Where(predExpr));
}
public AsyncTableQuery<T> Skip(int n)
{
return new AsyncTableQuery<T>(_innerQuery.Skip(n));
}
public AsyncTableQuery<T> Take(int n)
{
return new AsyncTableQuery<T>(_innerQuery.Take(n));
}
public AsyncTableQuery<T> OrderBy<U>(Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T>(_innerQuery.OrderBy<U>(orderExpr));
}
public AsyncTableQuery<T> OrderByDescending<U>(Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T>(_innerQuery.OrderByDescending<U>(orderExpr));
}
public Task<List<T>> ToListAsync()
{
return Task.Factory.StartNew(() =>
{
return _innerQuery.ToList();
});
}
public Task<int> CountAsync()
{
return Task.Factory.StartNew(() =>
{
return _innerQuery.Count();
});
}
public Task<T> ElementAtAsync(int index)
{
return Task.Factory.StartNew(() =>
{
return _innerQuery.ElementAt(index);
});
}
public Task<T> FirstAsync()
{
return Task<T>.Factory.StartNew(() =>
{
return _innerQuery.First();
});
}
public Task<T> FirstOrDefaultAsync()
{
return Task<T>.Factory.StartNew(() =>
{
return _innerQuery.FirstOrDefault();
});
}
}
}
[AttributeUsage(AttributeTargets.Property)]
public class GroupByAttribute : IndexedAttribute
{
public bool Descending { get; set; }
public GroupByAttribute(bool descending = false)
{
Descending = descending;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class OrderByAttribute : IndexedAttribute
{
public bool Descending { get; set; }
public OrderByAttribute(bool descending = false)
{
Descending = descending;
}
}
}
| |
namespace CefSharp.WinForms.Example
{
partial class BrowserForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BrowserForm));
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newTabToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeTabToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printToPdfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showDevToolsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeDevToolsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.cutMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectAllMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.copySourceToClipBoardAsyncMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zoomLevelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zoomInToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zoomOutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.currentZoomLevelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.scriptToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.isTextInputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.doesElementWithIDExistToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.listenForButtonClickToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.goToDemoPageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.injectJavascriptCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.testToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openDataUrlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.httpbinorgToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.runFileDialogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadExtensionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.javascriptBindingStressTestToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.browserTabControl = new System.Windows.Forms.TabControl();
this.showDevToolsDockedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.zoomLevelToolStripMenuItem,
this.scriptToolStripMenuItem,
this.testToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(730, 24);
this.menuStrip1.TabIndex = 1;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newTabToolStripMenuItem,
this.closeTabToolStripMenuItem,
this.printToolStripMenuItem,
this.printToPdfToolStripMenuItem,
this.aboutToolStripMenuItem,
this.showDevToolsMenuItem,
this.showDevToolsDockedToolStripMenuItem,
this.closeDevToolsMenuItem,
this.toolStripMenuItem3,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// newTabToolStripMenuItem
//
this.newTabToolStripMenuItem.Name = "newTabToolStripMenuItem";
this.newTabToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.T)));
this.newTabToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.newTabToolStripMenuItem.Text = "&New Tab";
this.newTabToolStripMenuItem.Click += new System.EventHandler(this.NewTabToolStripMenuItemClick);
//
// closeTabToolStripMenuItem
//
this.closeTabToolStripMenuItem.Name = "closeTabToolStripMenuItem";
this.closeTabToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.W)));
this.closeTabToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.closeTabToolStripMenuItem.Text = "&Close Tab";
this.closeTabToolStripMenuItem.Click += new System.EventHandler(this.CloseTabToolStripMenuItemClick);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.printToolStripMenuItem.Text = "&Print";
this.printToolStripMenuItem.Click += new System.EventHandler(this.PrintToolStripMenuItemClick);
//
// printToPdfToolStripMenuItem
//
this.printToPdfToolStripMenuItem.Name = "printToPdfToolStripMenuItem";
this.printToPdfToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.printToPdfToolStripMenuItem.Text = "Print To Pdf";
this.printToPdfToolStripMenuItem.Click += new System.EventHandler(this.PrintToPdfToolStripMenuItemClick);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.aboutToolStripMenuItem.Text = "About";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.AboutToolStripMenuItemClick);
//
// showDevToolsMenuItem
//
this.showDevToolsMenuItem.Name = "showDevToolsMenuItem";
this.showDevToolsMenuItem.Size = new System.Drawing.Size(208, 22);
this.showDevToolsMenuItem.Text = "Show Dev Tools (Default)";
this.showDevToolsMenuItem.Click += new System.EventHandler(this.ShowDevToolsMenuItemClick);
//
// closeDevToolsMenuItem
//
this.closeDevToolsMenuItem.Name = "closeDevToolsMenuItem";
this.closeDevToolsMenuItem.Size = new System.Drawing.Size(208, 22);
this.closeDevToolsMenuItem.Text = "Close Dev Tools";
this.closeDevToolsMenuItem.Click += new System.EventHandler(this.CloseDevToolsMenuItemClick);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(205, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitMenuItemClick);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoMenuItem,
this.redoMenuItem,
this.findMenuItem,
this.toolStripMenuItem2,
this.cutMenuItem,
this.copyMenuItem,
this.pasteMenuItem,
this.deleteMenuItem,
this.selectAllMenuItem,
this.toolStripSeparator1,
this.copySourceToClipBoardAsyncMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "Edit";
//
// undoMenuItem
//
this.undoMenuItem.Name = "undoMenuItem";
this.undoMenuItem.Size = new System.Drawing.Size(251, 22);
this.undoMenuItem.Text = "Undo";
this.undoMenuItem.Click += new System.EventHandler(this.UndoMenuItemClick);
//
// redoMenuItem
//
this.redoMenuItem.Name = "redoMenuItem";
this.redoMenuItem.Size = new System.Drawing.Size(251, 22);
this.redoMenuItem.Text = "Redo";
this.redoMenuItem.Click += new System.EventHandler(this.RedoMenuItemClick);
//
// findMenuItem
//
this.findMenuItem.Name = "findMenuItem";
this.findMenuItem.Size = new System.Drawing.Size(251, 22);
this.findMenuItem.Text = "Find";
this.findMenuItem.Click += new System.EventHandler(this.FindMenuItemClick);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(248, 6);
//
// cutMenuItem
//
this.cutMenuItem.Name = "cutMenuItem";
this.cutMenuItem.Size = new System.Drawing.Size(251, 22);
this.cutMenuItem.Text = "Cut";
this.cutMenuItem.Click += new System.EventHandler(this.CutMenuItemClick);
//
// copyMenuItem
//
this.copyMenuItem.Name = "copyMenuItem";
this.copyMenuItem.Size = new System.Drawing.Size(251, 22);
this.copyMenuItem.Text = "Copy";
this.copyMenuItem.Click += new System.EventHandler(this.CopyMenuItemClick);
//
// pasteMenuItem
//
this.pasteMenuItem.Name = "pasteMenuItem";
this.pasteMenuItem.Size = new System.Drawing.Size(251, 22);
this.pasteMenuItem.Text = "Paste";
this.pasteMenuItem.Click += new System.EventHandler(this.PasteMenuItemClick);
//
// deleteMenuItem
//
this.deleteMenuItem.Name = "deleteMenuItem";
this.deleteMenuItem.Size = new System.Drawing.Size(251, 22);
this.deleteMenuItem.Text = "Delete";
this.deleteMenuItem.Click += new System.EventHandler(this.DeleteMenuItemClick);
//
// selectAllMenuItem
//
this.selectAllMenuItem.Name = "selectAllMenuItem";
this.selectAllMenuItem.Size = new System.Drawing.Size(251, 22);
this.selectAllMenuItem.Text = "Select All";
this.selectAllMenuItem.Click += new System.EventHandler(this.SelectAllMenuItemClick);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(248, 6);
//
// copySourceToClipBoardAsyncMenuItem
//
this.copySourceToClipBoardAsyncMenuItem.Name = "copySourceToClipBoardAsyncMenuItem";
this.copySourceToClipBoardAsyncMenuItem.Size = new System.Drawing.Size(251, 22);
this.copySourceToClipBoardAsyncMenuItem.Text = "Copy Source to Clipboard (async)";
this.copySourceToClipBoardAsyncMenuItem.Click += new System.EventHandler(this.CopySourceToClipBoardAsyncClick);
//
// zoomLevelToolStripMenuItem
//
this.zoomLevelToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.zoomInToolStripMenuItem,
this.zoomOutToolStripMenuItem,
this.currentZoomLevelToolStripMenuItem});
this.zoomLevelToolStripMenuItem.Name = "zoomLevelToolStripMenuItem";
this.zoomLevelToolStripMenuItem.Size = new System.Drawing.Size(81, 20);
this.zoomLevelToolStripMenuItem.Text = "Zoom Level";
//
// zoomInToolStripMenuItem
//
this.zoomInToolStripMenuItem.Name = "zoomInToolStripMenuItem";
this.zoomInToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.zoomInToolStripMenuItem.Text = "Zoom In";
this.zoomInToolStripMenuItem.Click += new System.EventHandler(this.ZoomInToolStripMenuItemClick);
//
// zoomOutToolStripMenuItem
//
this.zoomOutToolStripMenuItem.Name = "zoomOutToolStripMenuItem";
this.zoomOutToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.zoomOutToolStripMenuItem.Text = "Zoom Out";
this.zoomOutToolStripMenuItem.Click += new System.EventHandler(this.ZoomOutToolStripMenuItemClick);
//
// currentZoomLevelToolStripMenuItem
//
this.currentZoomLevelToolStripMenuItem.Name = "currentZoomLevelToolStripMenuItem";
this.currentZoomLevelToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.currentZoomLevelToolStripMenuItem.Text = "Current Zoom Level";
this.currentZoomLevelToolStripMenuItem.Click += new System.EventHandler(this.CurrentZoomLevelToolStripMenuItemClick);
//
// scriptToolStripMenuItem
//
this.scriptToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.isTextInputToolStripMenuItem,
this.doesElementWithIDExistToolStripMenuItem,
this.listenForButtonClickToolStripMenuItem});
this.scriptToolStripMenuItem.Name = "scriptToolStripMenuItem";
this.scriptToolStripMenuItem.Size = new System.Drawing.Size(49, 20);
this.scriptToolStripMenuItem.Text = "Script";
//
// isTextInputToolStripMenuItem
//
this.isTextInputToolStripMenuItem.Name = "isTextInputToolStripMenuItem";
this.isTextInputToolStripMenuItem.Size = new System.Drawing.Size(271, 22);
this.isTextInputToolStripMenuItem.Text = "Does active element accept text input";
this.isTextInputToolStripMenuItem.Click += new System.EventHandler(this.DoesActiveElementAcceptTextInputToolStripMenuItemClick);
//
// doesElementWithIDExistToolStripMenuItem
//
this.doesElementWithIDExistToolStripMenuItem.Name = "doesElementWithIDExistToolStripMenuItem";
this.doesElementWithIDExistToolStripMenuItem.Size = new System.Drawing.Size(271, 22);
this.doesElementWithIDExistToolStripMenuItem.Text = "Does element with ID exist";
this.doesElementWithIDExistToolStripMenuItem.Click += new System.EventHandler(this.DoesElementWithIdExistToolStripMenuItemClick);
//
// listenForButtonClickToolStripMenuItem
//
this.listenForButtonClickToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.goToDemoPageToolStripMenuItem,
this.injectJavascriptCodeToolStripMenuItem});
this.listenForButtonClickToolStripMenuItem.Name = "listenForButtonClickToolStripMenuItem";
this.listenForButtonClickToolStripMenuItem.Size = new System.Drawing.Size(271, 22);
this.listenForButtonClickToolStripMenuItem.Text = "Listen for button click";
//
// goToDemoPageToolStripMenuItem
//
this.goToDemoPageToolStripMenuItem.Name = "goToDemoPageToolStripMenuItem";
this.goToDemoPageToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.goToDemoPageToolStripMenuItem.Text = "Go to demo page";
this.goToDemoPageToolStripMenuItem.Click += new System.EventHandler(this.GoToDemoPageToolStripMenuItemClick);
//
// injectJavascriptCodeToolStripMenuItem
//
this.injectJavascriptCodeToolStripMenuItem.Name = "injectJavascriptCodeToolStripMenuItem";
this.injectJavascriptCodeToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.injectJavascriptCodeToolStripMenuItem.Text = "Inject Javascript code";
this.injectJavascriptCodeToolStripMenuItem.Click += new System.EventHandler(this.InjectJavascriptCodeToolStripMenuItemClick);
//
// testToolStripMenuItem
//
this.testToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openDataUrlToolStripMenuItem,
this.httpbinorgToolStripMenuItem,
this.runFileDialogToolStripMenuItem,
this.loadExtensionsToolStripMenuItem,
this.javascriptBindingStressTestToolStripMenuItem});
this.testToolStripMenuItem.Name = "testToolStripMenuItem";
this.testToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.testToolStripMenuItem.Text = "Test";
//
// openDataUrlToolStripMenuItem
//
this.openDataUrlToolStripMenuItem.Name = "openDataUrlToolStripMenuItem";
this.openDataUrlToolStripMenuItem.Size = new System.Drawing.Size(226, 22);
this.openDataUrlToolStripMenuItem.Text = "Open Data Url";
this.openDataUrlToolStripMenuItem.Click += new System.EventHandler(this.OpenDataUrlToolStripMenuItemClick);
//
// httpbinorgToolStripMenuItem
//
this.httpbinorgToolStripMenuItem.Name = "httpbinorgToolStripMenuItem";
this.httpbinorgToolStripMenuItem.Size = new System.Drawing.Size(226, 22);
this.httpbinorgToolStripMenuItem.Text = "httpbin.org";
this.httpbinorgToolStripMenuItem.Click += new System.EventHandler(this.OpenHttpBinOrgToolStripMenuItemClick);
//
// runFileDialogToolStripMenuItem
//
this.runFileDialogToolStripMenuItem.Name = "runFileDialogToolStripMenuItem";
this.runFileDialogToolStripMenuItem.Size = new System.Drawing.Size(226, 22);
this.runFileDialogToolStripMenuItem.Text = "Run File Dialog";
this.runFileDialogToolStripMenuItem.Click += new System.EventHandler(this.RunFileDialogToolStripMenuItemClick);
//
// loadExtensionsToolStripMenuItem
//
this.loadExtensionsToolStripMenuItem.Name = "loadExtensionsToolStripMenuItem";
this.loadExtensionsToolStripMenuItem.Size = new System.Drawing.Size(226, 22);
this.loadExtensionsToolStripMenuItem.Text = "Load Example Extension";
this.loadExtensionsToolStripMenuItem.Click += new System.EventHandler(this.LoadExtensionsToolStripMenuItemClick);
//
// javascriptBindingStressTestToolStripMenuItem
//
this.javascriptBindingStressTestToolStripMenuItem.Name = "javascriptBindingStressTestToolStripMenuItem";
this.javascriptBindingStressTestToolStripMenuItem.Size = new System.Drawing.Size(226, 22);
this.javascriptBindingStressTestToolStripMenuItem.Text = "Javascript Binding Stress Test";
this.javascriptBindingStressTestToolStripMenuItem.Click += new System.EventHandler(this.JavascriptBindingStressTestToolStripMenuItemClick);
//
// browserTabControl
//
this.browserTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.browserTabControl.Location = new System.Drawing.Point(0, 24);
this.browserTabControl.Name = "browserTabControl";
this.browserTabControl.SelectedIndex = 0;
this.browserTabControl.Size = new System.Drawing.Size(730, 466);
this.browserTabControl.TabIndex = 2;
//
// showDevToolsDockedToolStripMenuItem
//
this.showDevToolsDockedToolStripMenuItem.Name = "showDevToolsDockedToolStripMenuItem";
this.showDevToolsDockedToolStripMenuItem.Size = new System.Drawing.Size(208, 22);
this.showDevToolsDockedToolStripMenuItem.Text = "Show Dev Tools (Docked)";
this.showDevToolsDockedToolStripMenuItem.Click += new System.EventHandler(this.ShowDevToolsDockedMenuItemClick);
//
// BrowserForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(730, 490);
this.Controls.Add(this.browserTabControl);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Name = "BrowserForm";
this.Text = "BrowserForm";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoMenuItem;
private System.Windows.Forms.ToolStripMenuItem cutMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectAllMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem showDevToolsMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem findMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem copySourceToClipBoardAsyncMenuItem;
private System.Windows.Forms.TabControl browserTabControl;
private System.Windows.Forms.ToolStripMenuItem newTabToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeTabToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeDevToolsMenuItem;
private System.Windows.Forms.ToolStripMenuItem zoomLevelToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem zoomInToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem zoomOutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem currentZoomLevelToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem scriptToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem isTextInputToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem doesElementWithIDExistToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem listenForButtonClickToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem goToDemoPageToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem injectJavascriptCodeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printToPdfToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem testToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openDataUrlToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem httpbinorgToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem runFileDialogToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadExtensionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem javascriptBindingStressTestToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showDevToolsDockedToolStripMenuItem;
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource
{
public partial class MetadataAsSourceTests : AbstractMetadataAsSourceTests
{
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestClass()
{
var metadataSource = "public class C {}";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class [|C|]
{{
public C();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class [|C|]
Public Sub New()
End Class");
}
[WorkItem(546241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546241")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestInterface()
{
var metadataSource = "public interface I {}";
var symbolName = "I";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public interface [|I|]
{{
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Interface [|I|]
End Interface");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestConstructor()
{
var metadataSource = "public class C {}";
var symbolName = "C..ctor";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public [|C|]();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub [|New|]()
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestMethod()
{
var metadataSource = "public class C { public void Foo() {} }";
var symbolName = "C.Foo";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public void [|Foo|]();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Public Sub [|Foo|]()
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestField()
{
var metadataSource = "public class C { public string S; }";
var symbolName = "C.S";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public string [|S|];
public C();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public [|S|] As String
Public Sub New()
End Class");
}
[WorkItem(546240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546240")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestProperty()
{
var metadataSource = "public class C { public string S { get; protected set; } }";
var symbolName = "C.S";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public string [|S|] {{ get; protected set; }}
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Public Property [|S|] As String
End Class");
}
[WorkItem(546194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546194")]
[WorkItem(546291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546291")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEvent()
{
var metadataSource = "using System; public class C { public event Action E; }";
var symbolName = "C.E";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
public class C
{{
public C();
public event Action [|E|];
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Public Class C
Public Sub New()
Public Event [|E|] As Action
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNestedType()
{
var metadataSource = "public class C { protected class D { } }";
var symbolName = "C+D";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
protected class [|D|]
{{
public D();
}}
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Protected Class [|D|]
Public Sub New()
End Class
End Class");
}
[WorkItem(546195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem(546269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEnum()
{
var metadataSource = "public enum E { A, B, C }";
var symbolName = "E";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum [|E|]
{{
A = 0,
B = 1,
C = 2
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum [|E|]
A = 0
B = 1
C = 2
End Enum");
}
[WorkItem(546195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546195"), WorkItem(546269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546269")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEnumFromField()
{
var metadataSource = "public enum E { A, B, C }";
var symbolName = "E.C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E
{{
A = 0,
B = 1,
[|C|] = 2
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E
A = 0
B = 1
[|C|] = 2
End Enum");
}
[WorkItem(546273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546273")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEnumWithUnderlyingType()
{
var metadataSource = "public enum E : short { A = 0, B = 1, C = 2 }";
var symbolName = "E.C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E : short
{{
A = 0,
B = 1,
[|C|] = 2
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E As Short
A = 0
B = 1
[|C|] = 2
End Enum");
}
[WorkItem(650741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650741")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEnumWithOverflowingUnderlyingType()
{
var metadataSource = "public enum E : ulong { A = 9223372036854775808 }";
var symbolName = "E.A";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E : ulong
{{
[|A|] = 9223372036854775808
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E As ULong
[|A|] = 9223372036854775808UL
End Enum");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEnumWithDifferentValues()
{
var metadataSource = "public enum E : short { A = 1, B = 2, C = 3 }";
var symbolName = "E.C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public enum E : short
{{
A = 1,
B = 2,
[|C|] = 3
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Enum E As Short
A = 1
B = 2
[|C|] = 3
End Enum");
}
[WorkItem(546198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546198")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestTypeInNamespace()
{
var metadataSource = "namespace N { public class C {} }";
var symbolName = "N.C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
namespace N
{{
public class [|C|]
{{
public C();
}}
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Namespace N
Public Class [|C|]
Public Sub New()
End Class
End Namespace");
}
[WorkItem(546223, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546223")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestInlineConstant()
{
var metadataSource = @"public class C { public const string S = ""Hello mas""; }";
var symbolName = "C.S";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public const string [|S|] = ""Hello mas"";
public C();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Const [|S|] As String = ""Hello mas""
Public Sub New()
End Class");
}
[WorkItem(546221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546221")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestInlineTypeOf()
{
var metadataSource = @"
using System;
public class MyTypeAttribute : Attribute
{
public MyTypeAttribute(Type type) {}
}
[MyType(typeof(string))]
public class C {}";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
[MyType(typeof(string))]
public class [|C|]
{{
public C();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
<MyType(GetType(String))>
Public Class [|C|]
Public Sub New()
End Class");
}
[WorkItem(546231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546231")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNoDefaultConstructorInStructs()
{
var metadataSource = "public struct S {}";
var symbolName = "S";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public struct [|S|]
{{
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Structure [|S|]
End Structure");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestReferenceDefinedType()
{
var metadataSource = "public class C { public static C Create() { return new C(); } }";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class [|C|]
{{
public C();
public static C Create();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class [|C|]
Public Sub New()
Public Shared Function Create() As C
End Class");
}
[WorkItem(546227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestGenericType()
{
var metadataSource = "public class G<SomeType> { public SomeType S; }";
var symbolName = "G`1";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class [|G|]<SomeType>
{{
public SomeType S;
public G();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class [|G|](Of SomeType)
Public S As SomeType
Public Sub New()
End Class");
}
[WorkItem(546227, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546227")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestGenericDelegate()
{
var metadataSource = "public class C { public delegate void D<SomeType>(SomeType s); }";
var symbolName = "C+D`1";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public delegate void [|D|]<SomeType>(SomeType s);
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Public Class C
Public Sub New()
Public Delegate Sub [|D|](Of SomeType)(s As SomeType)
End Class");
}
[WorkItem(546200, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546200")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestAttribute()
{
var metadataSource = @"
using System;
namespace N
{
public class WorkingAttribute : Attribute
{
public WorkingAttribute(bool working) {}
}
}
[N.Working(true)]
public class C {}";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using N;
[Working(true)]
public class [|C|]
{{
public C();
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports N
<Working(True)>
Public Class [|C|]
Public Sub New()
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestSymbolIdMatchesMetadata()
{
await TestSymbolIdMatchesMetadataAsync(LanguageNames.CSharp);
await TestSymbolIdMatchesMetadataAsync(LanguageNames.VisualBasic);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNotReusedOnAssemblyDiffers()
{
await TestNotReusedOnAssemblyDiffersAsync(LanguageNames.CSharp);
await TestNotReusedOnAssemblyDiffersAsync(LanguageNames.VisualBasic);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestThrowsOnGenerateNamespace()
{
var namespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol("Outerspace");
using (var context = await TestContext.CreateAsync())
{
await Assert.ThrowsAsync<ArgumentException>(async () =>
{
await context.GenerateSourceAsync(namespaceSymbol);
});
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestReuseGenerateMemberOfGeneratedType()
{
var metadataSource = "public class C { public bool Is; }";
using (var context = await TestContext.CreateAsync(LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource)))
{
var a = await context.GenerateSourceAsync("C");
var b = await context.GenerateSourceAsync("C.Is");
context.VerifyDocumentReused(a, b);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestReuseRepeatGeneration()
{
using (var context = await TestContext.CreateAsync())
{
var a = await context.GenerateSourceAsync();
var b = await context.GenerateSourceAsync();
context.VerifyDocumentReused(a, b);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestWorkspaceContextHasReasonableProjectName()
{
using (var context = await TestContext.CreateAsync())
{
var compilation = await context.DefaultProject.GetCompilationAsync();
var result = await context.GenerateSourceAsync(compilation.ObjectType);
var openedDocument = context.GetDocument(result);
Assert.Equal(openedDocument.Project.AssemblyName, "mscorlib");
Assert.Equal(openedDocument.Project.Name, "mscorlib");
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestReuseGenerateFromDifferentProject()
{
using (var context = await TestContext.CreateAsync())
{
var projectId = ProjectId.CreateNewId();
var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.CSharp).GetProject(projectId)
.WithMetadataReferences(context.DefaultProject.MetadataReferences)
.WithCompilationOptions(new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var a = await context.GenerateSourceAsync(project: context.DefaultProject);
var b = await context.GenerateSourceAsync(project: project);
context.VerifyDocumentReused(a, b);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNotReusedGeneratingForDifferentLanguage()
{
using (var context = await TestContext.CreateAsync(LanguageNames.CSharp))
{
var projectId = ProjectId.CreateNewId();
var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.VisualBasic).GetProject(projectId)
.WithMetadataReferences(context.DefaultProject.MetadataReferences)
.WithCompilationOptions(new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
var a = await context.GenerateSourceAsync(project: context.DefaultProject);
var b = await context.GenerateSourceAsync(project: project);
context.VerifyDocumentNotReused(a, b);
}
}
[WorkItem(546311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546311")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task FormatMetadataAsSource()
{
using (var context = await TestContext.CreateAsync(LanguageNames.CSharp))
{
var file = await context.GenerateSourceAsync("System.Console", project: context.DefaultProject);
var document = context.GetDocument(file);
await Formatting.Formatter.FormatAsync(document);
}
}
[WorkItem(530829, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530829")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task IndexedProperty()
{
var metadataSource = @"
Public Class C
Public Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
var expected = $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public class C
{{
public C();
public string [|get_IndexProp|](int p1);
public void set_IndexProp(int p1, string value);
}}";
var symbolName = "C.get_IndexProp";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected);
}
[WorkItem(566688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566688")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task AttributeReferencingInternalNestedType()
{
var metadataSource = @"using System;
[My(typeof(D))]
public class C
{
public C() { }
internal class D { }
}
public class MyAttribute : Attribute
{
public MyAttribute(Type t) { }
}";
var expected = $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
[My(typeof(D))]
public class [|C|]
{{
public C();
}}";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected);
}
[WorkItem(530978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530978")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestAttributesOnMembers()
{
var metadataSource = @"using System;
[Obsolete]
public class C
{
[Obsolete]
[ThreadStatic]
public int field1;
[Obsolete]
public int prop1 { get; set; }
[Obsolete]
public int prop2 { get { return 10; } set {} }
[Obsolete]
public void method1() {}
[Obsolete]
public C() {}
[Obsolete]
~C() {}
[Obsolete]
public int this[int x] { get { return 10; } set {} }
[Obsolete]
public event Action event1;
[Obsolete]
public event Action event2 { add {} remove {}}
public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {}
[Obsolete]
public static C operator + (C c1, C c2) { return new C(); }
}
";
var expectedCS = $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[DefaultMember(""Item"")]
[Obsolete]
public class [|C|]
{{
[Obsolete]
[ThreadStatic]
public int field1;
[Obsolete]
public C();
[Obsolete]
~C();
[Obsolete]
public int this[int x] {{ get; set; }}
[Obsolete]
public int prop1 {{ get; set; }}
[Obsolete]
public int prop2 {{ get; set; }}
[Obsolete]
public event Action event1;
[Obsolete]
public event Action event2;
[Obsolete]
public void method1();
public void method2([CallerMemberName] string name = """");
[Obsolete]
public static C operator +(C c1, C c2);
}}
";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expectedCS);
var expectedVB = $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
<DefaultMember(""Item"")>
<Obsolete>
Public Class [|C|]
<Obsolete>
<ThreadStatic>
Public field1 As Integer
<Obsolete>
Public Sub New()
<Obsolete>
Default Public Property Item(x As Integer) As Integer
<Obsolete>
Public Property prop1 As Integer
<Obsolete>
Public Property prop2 As Integer
<Obsolete>
Public Event event1 As Action
<Obsolete>
Public Event event2 As Action
<Obsolete>
Public Sub method1()
Public Sub method2(<CallerMemberName> Optional name As String = """")
<Obsolete>
Protected Overrides Sub Finalize()
<Obsolete>
Public Shared Operator +(c1 As C, c2 As C) As C
End Class
";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB);
}
[WorkItem(530923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530923")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEmptyLineBetweenMembers()
{
var metadataSource = @"using System;
public class C
{
public int field1;
public int prop1 { get; set; }
public int field2;
public int prop2 { get { return 10; } set {} }
public void method1() {}
public C() {}
public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {}
~C() {}
public int this[int x] { get { return 10; } set {} }
public event Action event1;
public static C operator + (C c1, C c2) { return new C(); }
public event Action event2 { add {} remove {}}
public static C operator - (C c1, C c2) { return new C(); }
}
";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[DefaultMember(""Item"")]
public class [|C|]
{{
public int field1;
public int field2;
public C();
~C();
public int this[int x] {{ get; set; }}
public int prop1 {{ get; set; }}
public int prop2 {{ get; set; }}
public event Action event1;
public event Action event2;
public void method1();
public void method2([CallerMemberName] string name = """");
public static C operator +(C c1, C c2);
public static C operator -(C c1, C c2);
}}
";
var symbolName = "C";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expectedCS, compareTokens: false);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
<DefaultMember(""Item"")>
Public Class [|C|]
Public field1 As Integer
Public field2 As Integer
Public Sub New()
Default Public Property Item(x As Integer) As Integer
Public Property prop1 As Integer
Public Property prop2 As Integer
Public Event event1 As Action
Public Event event2 As Action
Public Sub method1()
Public Sub method2(<CallerMemberName> Optional name As String = """")
Protected Overrides Sub Finalize()
Public Shared Operator +(c1 As C, c2 As C) As C
Public Shared Operator -(c1 As C, c2 As C) As C
End Class";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB, compareTokens: false);
}
[WorkItem(728644, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728644")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestEmptyLineBetweenMembers2()
{
var source = @"
using System;
/// <summary>T:IFoo</summary>
public interface IFoo
{
/// <summary>P:IFoo.Prop1</summary>
Uri Prop1 { get; set; }
/// <summary>M:IFoo.Method1</summary>
Uri Method1();
}
";
var symbolName = "IFoo";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
//
// {FeaturesResources.Summary_colon}
// T:IFoo
public interface [|IFoo|]
{{
//
// {FeaturesResources.Summary_colon}
// P:IFoo.Prop1
Uri Prop1 {{ get; set; }}
//
// {FeaturesResources.Summary_colon}
// M:IFoo.Method1
Uri Method1();
}}
";
await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.CSharp, expectedCS, compareTokens: false, includeXmlDocComments: true);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
'
' {FeaturesResources.Summary_colon}
' T:IFoo
Public Interface [|IFoo|]
'
' {FeaturesResources.Summary_colon}
' P:IFoo.Prop1
Property Prop1 As Uri
'
' {FeaturesResources.Summary_colon}
' M:IFoo.Method1
Function Method1() As Uri
End Interface
";
await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.VisualBasic, expectedVB, compareTokens: false, includeXmlDocComments: true);
}
[WorkItem(679114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679114"), WorkItem(715013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715013")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestDefaultValueEnum()
{
var source = @"
using System.IO;
public class Test
{
public void foo(FileOptions options = 0) {}
}
";
var symbolName = "Test";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System.IO;
public class [|Test|]
{{
public Test();
public void foo(FileOptions options = FileOptions.None);
}}
";
await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.CSharp, expectedCS);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System.IO
Public Class [|Test|]
Public Sub New()
Public Sub foo(Optional options As FileOptions = FileOptions.None)
End Class";
await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.VisualBasic, expectedVB);
}
[WorkItem(651261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651261")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNullAttribute()
{
var source = @"
using System;
[Test(null)]
public class TestAttribute : Attribute
{
public TestAttribute(int[] i)
{
}
}";
var symbolName = "TestAttribute";
var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System;
[Test(null)]
public class [|TestAttribute|] : Attribute
{{
public TestAttribute(int[] i);
}}
";
await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.CSharp, expectedCS);
var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
<Test(Nothing)>
Public Class [|TestAttribute|]
Inherits Attribute
Public Sub New(i() As Integer)
End Class";
await GenerateAndVerifySourceAsync(source, symbolName, LanguageNames.VisualBasic, expectedVB);
}
[WorkItem(897006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNavigationViaReducedExtensionMethodCS()
{
var metadata = @"using System;
public static class ObjectExtensions
{
public static void M(this object o, int x) { }
}";
var sourceWithSymbolReference = @"
class C
{
void M()
{
new object().[|M|](5);
}
}";
var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
public static class ObjectExtensions
{{
public static void [|M|](this object o, int x);
}}
";
using (var context = await TestContext.CreateAsync(
LanguageNames.CSharp,
SpecializedCollections.SingletonEnumerable(metadata),
includeXmlDocComments: false,
sourceWithSymbolReference: sourceWithSymbolReference))
{
var navigationSymbol = await context.GetNavigationSymbolAsync();
var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol);
context.VerifyResult(metadataAsSourceFile, expected);
}
}
[WorkItem(897006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/897006")]
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestNavigationViaReducedExtensionMethodVB()
{
var metadata = @"Imports System.Runtime.CompilerServices
Namespace NS
Public Module StringExtensions
<Extension()>
Public Sub M(ByVal o As String, x As Integer)
End Sub
End Module
End Namespace";
var sourceWithSymbolReference = @"
Imports NS.StringExtensions
Public Module C
Sub M()
Dim s = ""Yay""
s.[|M|](1)
End Sub
End Module";
var expected = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System.Runtime.CompilerServices
Namespace NS
<Extension>
Public Module StringExtensions
<Extension> Public Sub [|M|](o As String, x As Integer)
End Module
End Namespace";
using (var context = await TestContext.CreateAsync(
LanguageNames.VisualBasic,
SpecializedCollections.SingletonEnumerable(metadata),
includeXmlDocComments: false,
sourceWithSymbolReference: sourceWithSymbolReference))
{
var navigationSymbol = await context.GetNavigationSymbolAsync();
var metadataAsSourceFile = await context.GenerateSourceAsync(navigationSymbol);
context.VerifyResult(metadataAsSourceFile, expected);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public async Task TestIndexersAndOperators()
{
var metadataSource = @"public class Program
{
public int this[int x]
{
get
{
return 0;
}
set
{
}
}
public static Program operator + (Program p1, Program p2)
{
return new Program();
}
}";
var symbolName = "Program";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, $@"
#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// {CodeAnalysisResources.InMemoryAssembly}
#endregion
using System.Reflection;
[DefaultMember(""Item"")]
public class [|Program|]
{{
public Program();
public int this[int x] {{ get; set; }}
public static Program operator +(Program p1, Program p2);
}}");
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, $@"
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System.Reflection
<DefaultMember(""Item"")>
Public Class [|Program|]
Public Sub New()
Default Public Property Item(x As Integer) As Integer
Public Shared Operator +(p1 As Program, p2 As Program) As Program
End Class");
}
}
}
| |
using System.Collections.Generic;
using Flame.Compiler;
using LLVMSharp;
using static LLVMSharp.LLVM;
namespace Flame.LLVM.Codegen
{
/// <summary>
/// A try-finally block implementation for the Itanium C++ ABI.
/// </summary>
public sealed class ItaniumCxxFinallyBlock : CodeBlock
{
/// <summary>
/// Creates a try-finally block.
/// </summary>
/// <param name="CodeGenerator">The code generator that creates this block.</param>
/// <param name="TryBody">The body of the try clause.</param>
/// <param name="FinallyBody">The body of the finally clause.</param>
public ItaniumCxxFinallyBlock(
ICodeGenerator CodeGenerator,
CodeBlock TryBody,
CodeBlock FinallyBody)
{
this.codeGenerator = CodeGenerator;
this.TryBody = TryBody;
this.FinallyBody = FinallyBody;
}
/// <summary>
/// Gets the body of the try clause in this block.
/// </summary>
/// <returns>The try clause's body.</returns>
public CodeBlock TryBody { get; private set; }
/// <summary>
/// Gets the body of the finally clause in this block.
/// </summary>
/// <returns>The finally clause's body.</returns>
public CodeBlock FinallyBody { get; private set; }
private ICodeGenerator codeGenerator;
/// <inheritdoc/>
public override ICodeGenerator CodeGenerator => codeGenerator;
/// <inheritdoc/>
public override IType Type => TryBody.Type;
/// <inheritdoc/>
public override BlockCodegen Emit(BasicBlockBuilder BasicBlock)
{
var exceptionDataType = StructType(new[] { PointerType(Int8Type(), 0), Int32Type() }, false);
var isPropagatingStorage = BasicBlock.FunctionBody.CreateEntryPointAlloca(
Int1Type(),
"exception_value_alloca");
var finallyBlock = BasicBlock.CreateChildBlock("finally");
var finallyLandingPadBlock = BasicBlock.CreateChildBlock("finally_landingpad");
var finallyExceptionBlock = BasicBlock.CreateChildBlock("finally_exception");
var leaveBlock = BasicBlock.CreateChildBlock("leave");
// The try block is a regular block that jumps to the finally block.
//
// try:
// store i1 false, i1* %is_propagating_exception_alloca
// <try body>
// br label %finally
BuildStore(
BasicBlock.Builder,
ConstInt(Int1Type(), 0, false),
isPropagatingStorage);
var tryCodegen = TryBody.Emit(BasicBlock.WithUnwindTarget(finallyLandingPadBlock, finallyExceptionBlock));
BuildBr(tryCodegen.BasicBlock.Builder, finallyBlock.Block);
PopulateFinallyBlock(finallyBlock, leaveBlock, isPropagatingStorage);
PopulateThunkLandingPadBlock(finallyLandingPadBlock, finallyExceptionBlock.Block, true);
// The 'finally_exception' block is entered if an exception is propagating from
// the 'try' block. It sets the 'is propagating' flag to 'true' and branches
// to the finally block.
//
// finally_exception:
// store i1 true, i1* %is_propagating_exception_alloca
// br label %finally
BuildStore(
finallyExceptionBlock.Builder,
ConstInt(Int1Type(), 1, false),
isPropagatingStorage);
BuildBr(finallyExceptionBlock.Builder, finallyBlock.Block);
return new BlockCodegen(leaveBlock, tryCodegen.Value);
}
/// <summary>
/// Populates a 'finally' block with instructions.
/// </summary>
/// <param name="FinallyBlock">The 'finally' block to populate.</param>
/// <param name="LeaveBlock">
/// The 'leave' block to which the 'finally' block jumps if no exception was thrown.
/// </param>
/// <param name="IsPropagatingStorage">
/// A pointer to a Boolean flag that tells if an exception is being propagated.
/// </param>
private void PopulateFinallyBlock(
BasicBlockBuilder FinallyBlock,
BasicBlockBuilder LeaveBlock,
LLVMValueRef IsPropagatingStorage)
{
// A finally block is just a normal block that does this:
//
// finally:
// <finally body>
// if (is_handling_exception)
// {
// unwind;
// }
// else
// {
// goto leave_try;
// }
var finallyTail = FinallyBody.Emit(FinallyBlock).BasicBlock;
var propagateExceptionBlock = GetManualUnwindTarget(finallyTail);
BuildCondBr(
finallyTail.Builder,
BuildLoad(
finallyTail.Builder,
IsPropagatingStorage,
"is_handling_exception"),
propagateExceptionBlock,
LeaveBlock.Block);
}
/// <summary>
/// Gets the manual unwind target for the given block, if any.
/// If there is no manual unwind target, then a block is created
/// that resumes the exception.
/// </summary>
/// <param name="BasicBlock">The basic block to unwind from.</param>
/// <returns>An unwind target block.</returns>
public static LLVMBasicBlockRef GetManualUnwindTarget(BasicBlockBuilder BasicBlock)
{
// The idea is to create a block that, if jumped to, does the following:
//
// static if (is_top_level_try)
// resume exception_data;
// else
// goto next_unwind_target;
if (BasicBlock.HasUnwindTarget)
{
return BasicBlock.ManualUnwindTarget;
}
else
{
var resumeBlock = BasicBlock.CreateChildBlock("resume");
var exceptionTuple = BuildLoad(
resumeBlock.Builder,
resumeBlock.FunctionBody.ExceptionDataStorage.Value,
"exception_tuple");
BuildResume(resumeBlock.Builder, exceptionTuple);
return resumeBlock.Block;
}
}
/// <summary>
/// Populates a thunk landing pad block: a basic block that starts with a
/// landing pad that catches any and all exceptions, stores the exception
/// data and then jumps unconditionally to the target block.
/// </summary>
/// <param name="ThunkLandingPad">The thunk landing pad block to set up.</param>
/// <param name="Target">The thunk landing pad block's target.</param>
/// <param name="IsCleanup">
/// Specifies if the thunk should use a 'cleanup' landing pad or a catch-all landing pad.
/// </param>
public static void PopulateThunkLandingPadBlock(
BasicBlockBuilder ThunkLandingPad,
LLVMBasicBlockRef Target,
bool IsCleanup)
{
// A thunk landing pad block is an unwind target that does little more than
// branch to its target.
//
// thunk:
// %exception_data = { i8*, i32 } landingpad (cleanup|catch i8* null)
// store { i8*, i32 } %exception_data, { i8*, i32 }* %exception_data_alloca
// br %target
var bytePtr = PointerType(Int8Type(), 0);
var exceptionDataType = StructType(new[] { bytePtr, Int32Type() }, false);
var personality = ThunkLandingPad.FunctionBody.Module.Declare(IntrinsicValue.GxxPersonalityV0);
var exceptionData = BuildLandingPad(
ThunkLandingPad.Builder,
exceptionDataType,
ConstBitCast(personality, bytePtr),
IsCleanup ? 0u : 1u,
"exception_data");
if (IsCleanup)
{
exceptionData.SetCleanup(true);
}
else
{
exceptionData.AddClause(ConstNull(bytePtr));
}
BuildStore(
ThunkLandingPad.Builder,
exceptionData,
ThunkLandingPad.FunctionBody.ExceptionDataStorage.Value);
BuildBr(ThunkLandingPad.Builder, Target);
}
}
}
| |
// <copyright file="Keys.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
namespace OpenQA.Selenium
{
/// <summary>
/// Representations of keys able to be pressed that are not text keys for sending to the browser.
/// </summary>
public static class Keys
{
/// <summary>
/// Represents the NUL keystroke.
/// </summary>
public static readonly string Null = Convert.ToString(Convert.ToChar(0xE000, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Cancel keystroke.
/// </summary>
public static readonly string Cancel = Convert.ToString(Convert.ToChar(0xE001, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Help keystroke.
/// </summary>
public static readonly string Help = Convert.ToString(Convert.ToChar(0xE002, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Backspace key.
/// </summary>
public static readonly string Backspace = Convert.ToString(Convert.ToChar(0xE003, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Tab key.
/// </summary>
public static readonly string Tab = Convert.ToString(Convert.ToChar(0xE004, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Clear keystroke.
/// </summary>
public static readonly string Clear = Convert.ToString(Convert.ToChar(0xE005, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Return key.
/// </summary>
public static readonly string Return = Convert.ToString(Convert.ToChar(0xE006, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Enter key.
/// </summary>
public static readonly string Enter = Convert.ToString(Convert.ToChar(0xE007, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string Shift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string LeftShift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string Control = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string LeftControl = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string Alt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string LeftAlt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Pause key.
/// </summary>
public static readonly string Pause = Convert.ToString(Convert.ToChar(0xE00B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Escape key.
/// </summary>
public static readonly string Escape = Convert.ToString(Convert.ToChar(0xE00C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Spacebar key.
/// </summary>
public static readonly string Space = Convert.ToString(Convert.ToChar(0xE00D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Up key.
/// </summary>
public static readonly string PageUp = Convert.ToString(Convert.ToChar(0xE00E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Down key.
/// </summary>
public static readonly string PageDown = Convert.ToString(Convert.ToChar(0xE00F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the End key.
/// </summary>
public static readonly string End = Convert.ToString(Convert.ToChar(0xE010, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Home key.
/// </summary>
public static readonly string Home = Convert.ToString(Convert.ToChar(0xE011, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string Left = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string ArrowLeft = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string Up = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string ArrowUp = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string Right = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string ArrowRight = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Left arrow key.
/// </summary>
public static readonly string Down = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Left arrow key.
/// </summary>
public static readonly string ArrowDown = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Insert key.
/// </summary>
public static readonly string Insert = Convert.ToString(Convert.ToChar(0xE016, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Delete key.
/// </summary>
public static readonly string Delete = Convert.ToString(Convert.ToChar(0xE017, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the semi-colon key.
/// </summary>
public static readonly string Semicolon = Convert.ToString(Convert.ToChar(0xE018, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the equal sign key.
/// </summary>
public static readonly string Equal = Convert.ToString(Convert.ToChar(0xE019, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Number pad keys
/// <summary>
/// Represents the number pad 0 key.
/// </summary>
public static readonly string NumberPad0 = Convert.ToString(Convert.ToChar(0xE01A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 1 key.
/// </summary>
public static readonly string NumberPad1 = Convert.ToString(Convert.ToChar(0xE01B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 2 key.
/// </summary>
public static readonly string NumberPad2 = Convert.ToString(Convert.ToChar(0xE01C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 3 key.
/// </summary>
public static readonly string NumberPad3 = Convert.ToString(Convert.ToChar(0xE01D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 4 key.
/// </summary>
public static readonly string NumberPad4 = Convert.ToString(Convert.ToChar(0xE01E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 5 key.
/// </summary>
public static readonly string NumberPad5 = Convert.ToString(Convert.ToChar(0xE01F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 6 key.
/// </summary>
public static readonly string NumberPad6 = Convert.ToString(Convert.ToChar(0xE020, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 7 key.
/// </summary>
public static readonly string NumberPad7 = Convert.ToString(Convert.ToChar(0xE021, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 8 key.
/// </summary>
public static readonly string NumberPad8 = Convert.ToString(Convert.ToChar(0xE022, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 9 key.
/// </summary>
public static readonly string NumberPad9 = Convert.ToString(Convert.ToChar(0xE023, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad multiplication key.
/// </summary>
public static readonly string Multiply = Convert.ToString(Convert.ToChar(0xE024, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad addition key.
/// </summary>
public static readonly string Add = Convert.ToString(Convert.ToChar(0xE025, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad thousands separator key.
/// </summary>
public static readonly string Separator = Convert.ToString(Convert.ToChar(0xE026, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad subtraction key.
/// </summary>
public static readonly string Subtract = Convert.ToString(Convert.ToChar(0xE027, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad decimal separator key.
/// </summary>
public static readonly string Decimal = Convert.ToString(Convert.ToChar(0xE028, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad division key.
/// </summary>
public static readonly string Divide = Convert.ToString(Convert.ToChar(0xE029, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Function keys
/// <summary>
/// Represents the function key F1.
/// </summary>
public static readonly string F1 = Convert.ToString(Convert.ToChar(0xE031, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F2.
/// </summary>
public static readonly string F2 = Convert.ToString(Convert.ToChar(0xE032, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F3.
/// </summary>
public static readonly string F3 = Convert.ToString(Convert.ToChar(0xE033, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F4.
/// </summary>
public static readonly string F4 = Convert.ToString(Convert.ToChar(0xE034, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F5.
/// </summary>
public static readonly string F5 = Convert.ToString(Convert.ToChar(0xE035, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F6.
/// </summary>
public static readonly string F6 = Convert.ToString(Convert.ToChar(0xE036, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F7.
/// </summary>
public static readonly string F7 = Convert.ToString(Convert.ToChar(0xE037, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F8.
/// </summary>
public static readonly string F8 = Convert.ToString(Convert.ToChar(0xE038, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F9.
/// </summary>
public static readonly string F9 = Convert.ToString(Convert.ToChar(0xE039, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F10.
/// </summary>
public static readonly string F10 = Convert.ToString(Convert.ToChar(0xE03A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F11.
/// </summary>
public static readonly string F11 = Convert.ToString(Convert.ToChar(0xE03B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F12.
/// </summary>
public static readonly string F12 = Convert.ToString(Convert.ToChar(0xE03C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key META.
/// </summary>
public static readonly string Meta = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key COMMAND.
/// </summary>
public static readonly string Command = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
private static Dictionary<string, string> descriptions;
/// <summary>
/// Gets the description of a specific key.
/// </summary>
/// <param name="value">The key value for which to get the description.</param>
/// <returns>The description of the key.</returns>
internal static object GetDescription(string value)
{
if (descriptions == null)
{
descriptions = new Dictionary<string, string>();
descriptions.Add(Null, "Null");
descriptions.Add(Cancel, "Cancel");
descriptions.Add(Help, "Help");
descriptions.Add(Backspace, "Backspace");
descriptions.Add(Tab, "Tab");
descriptions.Add(Clear, "Clear");
descriptions.Add(Return, "Return");
descriptions.Add(Enter, "Enter");
descriptions.Add(Shift, "Shift");
descriptions.Add(Control, "Control");
descriptions.Add(Alt, "Alt");
descriptions.Add(Pause, "Pause");
descriptions.Add(Escape, "Escape");
descriptions.Add(Space, "Space");
descriptions.Add(PageUp, "Page Up");
descriptions.Add(PageDown, "PageDown");
descriptions.Add(End, "End");
descriptions.Add(Home, "Home");
descriptions.Add(Left, "Left");
descriptions.Add(Up, "Up");
descriptions.Add(Right, "Right");
descriptions.Add(Down, "Down");
descriptions.Add(Insert, "Insert");
descriptions.Add(Delete, "Delete");
descriptions.Add(Semicolon, "Semicolon");
descriptions.Add(Equal, "Equal");
descriptions.Add(NumberPad0, "Number Pad 0");
descriptions.Add(NumberPad1, "Number Pad 1");
descriptions.Add(NumberPad2, "Number Pad 2");
descriptions.Add(NumberPad3, "Number Pad 3");
descriptions.Add(NumberPad4, "Number Pad 4");
descriptions.Add(NumberPad5, "Number Pad 5");
descriptions.Add(NumberPad6, "Number Pad 6");
descriptions.Add(NumberPad7, "Number Pad 7");
descriptions.Add(NumberPad8, "Number Pad 8");
descriptions.Add(NumberPad9, "Number Pad 9");
descriptions.Add(Multiply, "Multiply");
descriptions.Add(Add, "Add");
descriptions.Add(Separator, "Separator");
descriptions.Add(Subtract, "Subtract");
descriptions.Add(Decimal, "Decimal");
descriptions.Add(Divide, "Divide");
descriptions.Add(F1, "F1");
descriptions.Add(F2, "F2");
descriptions.Add(F3, "F3");
descriptions.Add(F4, "F4");
descriptions.Add(F5, "F5");
descriptions.Add(F6, "F6");
descriptions.Add(F7, "F7");
descriptions.Add(F8, "F8");
descriptions.Add(F9, "F9");
descriptions.Add(F10, "F10");
descriptions.Add(F11, "F11");
descriptions.Add(F12, "F12");
descriptions.Add(Meta, "Meta");
descriptions.Add(Command, "Command");
}
if (descriptions.ContainsKey(value))
{
return descriptions[value];
}
return value;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace MeshEngine {
public class Materials {
public class MaterialTriangles {
public List<int> triangles;
}
public Mesh mesh;
public bool materialsChanged;
private List<Material> materials;
private Dictionary<string, int> nameIndex;
private MaterialColorIndex colorIndex;
private List<int> triangleMaterials; // index points to triangle in TrianglesManager.triangles * 3, value is index in MaterialManager.materials. length = TrianglesManager.triangles.Count / 3.
public Materials(Mesh mesh) {
this.mesh = mesh;
materials = new List<Material>();
nameIndex = new Dictionary<string, int>();
colorIndex = new MaterialColorIndex();
triangleMaterials = new List<int>();
materialsChanged = false;
}
public void Clear() {
materials.Clear();
nameIndex.Clear();
colorIndex.Clear();
triangleMaterials.Clear();
}
public int TriangleMaterialsCount() {
return triangleMaterials.Count;
}
public void TruncateToCount(int count) {
for (int i = triangleMaterials.Count - 1; i >= count; i--) {
triangleMaterials.RemoveAt(i);
}
materialsChanged = true;
}
public int FindOrCreateMaterialIndexByFillColor() {
Color fillColor = Settings.fillColor;
int materialIndex = FindOrCreateMaterialIndexByColor(fillColor);
return materialIndex;
}
public void SetMaterials(List<Material> myMaterials) {
Clear();
materials = myMaterials;
BuildIndices();
}
public List<Material> GetMaterials() {
return materials;
}
public List<int> GetTriangleIndexMaterialIndex() {
return triangleMaterials;
}
public Material MaterialByIndex(int materialIndex) {
return materials[materialIndex];
}
private string ColorArrayString(Color[] colors) {
List<string> strings = new List<string>();
foreach (Color color in colors) {
strings.Add(ColorUtility.ToHtmlStringRGBA(color));
}
return string.Join(",", strings.ToArray());
}
public int FindOrCreateMaterialIndexByColor(Color color) {
int index = colorIndex.LastMaterialIndexByColor(color);
if (index != -1) return index;
return NewMaterialIndexFromColor(color);
}
private string FindNextName(string name) {
// FIXME: This is O(N) for the number of same names in the system.
int i = 2;
while (true) {
string nextName = name + '_' + i;
if (!nameIndex.ContainsKey(nextName)) return nextName;
i++;
}
}
public int NewMaterialIndexFromColor(Color color) {
Material material = NewMaterialFromColor(color);
if (nameIndex.ContainsKey(material.name)) material.name = FindNextName(material.name);
return AddMaterial(material);
}
public static Material NewMaterialFromColor(Color color) {
Material material = new Material();
material.color = color;
material.name = "Material_#" + ColorUtility.ToHtmlStringRGBA(color);
return material;
}
public int GetLastMaterialIndex() {
if (materials.Count > 0) return materials.Count - 1;
Material material = GetLastMaterial();
AddMaterial(material);
return materials.Count - 1;
}
public Material GetLastMaterial() {
if (materials.Count > 0) return materials.Last();
Color fillColor = Settings.fillColor;
return NewMaterialFromColor(fillColor);
}
public int MaterialIndexByTriangleIndex(int triangleIndex) {
int index = triangleIndex / 3;
return triangleMaterials[index];
}
public Material GetMaterialByTriangleIndex(int triangleIndex) {
int index = triangleIndex / 3;
return materials[triangleMaterials[index]];
}
public List<string> MaterialNames() {
List<string> materialNames = new List<string>();
for (int i = 0; i < triangleMaterials.Count; i++) {
materialNames.Add(materials[triangleMaterials[i]].name);
}
return materialNames;
}
public void SetTriangleIndexMaterialIndex(int triangleIndex, int materialIndex) {
int index = triangleIndex / 3;
triangleMaterials[index] = materialIndex;
materialsChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void AppendTriangleUsingFillColorMaterial() {
int fillColorMaterialIndex = FindOrCreateMaterialIndexByFillColor();
triangleMaterials.Add(fillColorMaterialIndex);
//Debug.Log("AppendTriangleUsingFillColorMaterial fillColor=" + ColorUtility.ToHtmlStringRGBA(meshController.settingsPanelController.GetComponent<SettingsController>().fillColor) + ",mmMaterial.color=" + ColorUtility.ToHtmlStringRGBA(materials[fillColorMaterialIndex].color) + ",triangleMaterials.Count="+ triangleMaterials.Count + ",fillColorMaterialIndex="+ fillColorMaterialIndex);
materialsChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void AppendTriangleUsingMaterialIndex(int materialIndex) {
triangleMaterials.Add(materialIndex);
materialsChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void AppendTriangleUsingLastMaterial() {
int lastMaterialIndex = GetLastMaterialIndex();
triangleMaterials.Add(lastMaterialIndex);
materialsChanged = true;
mesh.persistence.changedSinceLastSave = true;
}
public void RemoveTriangleByIndex(int triangleIndex) {
int index = triangleIndex / 3;
triangleMaterials.RemoveAt(index);
materialsChanged = true;
mesh.persistence.changedSinceLastSave = true;
// TODO: remove material if all references to it have been removed?
}
private string ColorToString(Color color) {
return "r=" + color.r.ToString() + ",g=" + color.g.ToString() + ",b=" + color.b.ToString() + ",a=" + color.a.ToString();
}
public int AddMaterial(Material material) {
materials.Add(material);
int index = materials.Count - 1;
nameIndex.Add(material.name, index);
colorIndex.AddIndexByColor(material.color, index);
return index;
}
public Material MaterialByTriangleIndex(int triangleIndex) {
int index = triangleIndex / 3;
//Debug.Log("MaterialByTriangleIndex index=" + index + ",triangleMaterials[index]="+ triangleMaterials[index]);
return materials[triangleMaterials[index]];
}
public void BuildIndices() {
BuildNameIndex();
BuildColorIndex();
}
public void BuildColorIndex() {
colorIndex.Clear();
for (int i = 0; i < materials.Count; i++) {
Material material = materials[i];
colorIndex.AddIndexByColor(material.color, i);
}
}
public void BuildNameIndex() {
nameIndex.Clear();
for (int i = 0; i < materials.Count; i++) {
Material material = materials[i];
nameIndex.Add(material.name, i);
}
}
public Material FillTriangle(Triangle triangle) {
Material triangleMaterial = mesh.materials.GetMaterialByTriangleIndex(triangle.index);
Color fillColor = Settings.fillColor;
if (triangleMaterial.color == fillColor) return triangleMaterial; // triangle is already the desired color - nothing to do.
int materialIndex = mesh.materials.FindOrCreateMaterialIndexByColor(fillColor);
mesh.materials.SetTriangleIndexMaterialIndex(triangle.index, materialIndex);
Material material = mesh.materials.MaterialByIndex(materialIndex);
materialsChanged = true;
mesh.persistence.changedSinceLastSave = true;
return material;
}
public void PopulateTriangleMaterialsByMaterialNames(List<string> materialNames) {
triangleMaterials.Clear();
foreach (string name in materialNames) {
if (name == null) {
int materialIndex = GetLastMaterialIndex();
triangleMaterials.Add(materialIndex);
} else {
triangleMaterials.Add(nameIndex[name]);
}
}
}
public List<MaterialTriangles> GetTriangles() {
List<MaterialTriangles> triangles = new List<MaterialTriangles>();
for (int i = 0; i < materials.Count; i++) {
MaterialTriangles materialTriangles = new MaterialTriangles();
materialTriangles.triangles = new List<int>();
triangles.Add(materialTriangles);
}
for (int i = 0; i < mesh.triangles.triangles.Count; i++) {
int materialIndex = triangleMaterials[i / 3];
triangles[materialIndex].triangles.Add(mesh.triangles.triangles[i]);
}
return triangles;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.SharePoint;
namespace GSoft.Dynamite.Binding
{
/// <summary>
/// An adapter class to convert a SPListItem to an IDictionary<string, object>.
/// </summary>
[CLSCompliant(false)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Adding Dictionnary would be harder to understand.")]
public class ListItemValuesAdapter : IDictionary<string, object>, ISharePointListItemValues
{
#region Fields
private readonly SPListItem _listItem;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ListItemValuesAdapter"/> class.
/// </summary>
/// <param name="listItem">The list item.</param>
public ListItemValuesAdapter(SPListItem listItem)
{
this._listItem = listItem;
}
#endregion
#region ISharePointListItemValues Members
/// <summary>
/// Returns the underlying SharePoint list item
/// </summary>
public SPListItem ListItem
{
get
{
return this._listItem;
}
}
#endregion
#region IDictionary<string,object> Members
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get
{
return this._listItem.Fields.Count;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<string> Keys
{
get
{
return this._listItem.Fields.Cast<SPField>().Select(x => x.InternalName).ToList();
}
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<object> Values
{
get
{
return this._listItem.Fields.Cast<SPField>().Select(x => this._listItem[x.InternalName]).ToList();
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>
/// The element with the specified key.
/// </returns>
/// <param name="key">The key to get or set.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception>
public object this[string key]
{
get
{
return this._listItem[key];
}
set
{
this._listItem[key] = value;
}
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.NotSupportedException">This method is not supported.</exception>
public void Add(string key, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <exception cref="T:System.NotSupportedException">This method is not supported.</exception>
public void Add(KeyValuePair<string, object> item)
{
this._listItem[item.Key] = item.Value;
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public void Clear()
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
object value;
return this.TryGetValue(item.Key, out value) && object.Equals(value, item.Value);
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool ContainsKey(string key)
{
return this._listItem.Fields.GetFieldByInternalName(key) != null;
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
var pos = arrayIndex;
foreach (var keyValue in this)
{
array[pos++] = keyValue;
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return this._listItem.Fields.Cast<SPField>().Select(x => new KeyValuePair<string, object>(x.InternalName, this._listItem[x.InternalName])).GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool Remove(string key)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public bool Remove(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Try get value replaces the exception with null.")]
public bool TryGetValue(string key, out object value)
{
try
{
value = this._listItem[key];
return true;
}
catch
{
value = null;
return false;
}
}
#endregion
}
}
| |
//
// Copyright 2012-2016, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
//--------------------------------------------------------------------
// Original defines
// usings are in WebAuthenticator.<Platform>.cs
//
//#if PLATFORM_IOS
//using AuthenticateUIType = MonoTouch.UIKit.UIViewController;
//#elif PLATFORM_ANDROID
//using AuthenticateUIType = Android.Content.Intent;
//using UIContext = Android.Content.Context;
//#elif PLATFORM_WINPHONE
//using Microsoft.Phone.Shell;
//using AuthenticateUIType = System.Uri;
//#else
//using AuthenticateUIType = System.Object;
//#endif
//--------------------------------------------------------------------
#if ! AZURE_MOBILE_SERVICES
namespace Xamarin.Auth
#else
namespace Xamarin.Auth._MobileServices
#endif
{
/// <summary>
/// An authenticator that displays a web page.
/// </summary>
#if XAMARIN_AUTH_INTERNAL
internal abstract partial class WebAuthenticator : Authenticator
#else
public abstract partial class WebAuthenticator : Authenticator
#endif
{
/// <summary>
/// Gets or sets whether to automatically clear cookies before logging in.
/// </summary>
/// <seealso cref="ClearCookies"/>
public bool ClearCookiesBeforeLogin
{
get { return this.clearCookies; }
set { this.clearCookies = value; }
}
/// <summary>
/// Method that returns the initial URL to be displayed in the web browser.
/// </summary>
/// <returns>
/// A task that will return the initial URL.
/// </returns>
/// <param name="custom_query_parameters">Custom Query parameters</param>
public abstract Task<Uri> GetInitialUrlAsync(Dictionary<string, string> custom_query_parameters = null);
/// <summary>
/// Event handler called when a new page is being loaded in the web browser.
///
/// Must be virtual because of OAuth1Authenticator
/// </summary>
/// <param name='url'>
/// The URL of the page.
/// </param>
public virtual void OnPageLoading(Uri url)
{
#if DEBUG
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("WebAuthenticator OnPageLoading Called");
sb.AppendLine(" AbsoluteUri = ").AppendLine(url.AbsoluteUri);
sb.AppendLine(" AbsolutePath = ").AppendLine(url.AbsolutePath);
System.Diagnostics.Debug.WriteLine(sb.ToString());
#endif
return;
}
/// <summary>
/// Event handler called when a new page has been loaded in the web browser.
/// Implementations should call <see cref="Authenticator.OnSucceeded(Xamarin.Auth.Account)"/> if this page
/// signifies a successful authentication.
/// </summary>
/// <param name='url'>
/// The URL of the page.
/// </param>
public abstract void OnPageLoaded(Uri url);
/// <summary>
/// Clears all cookies.
/// </summary>
/// <seealso cref="ClearCookiesBeforeLogin"/>
//public static void ClearCookies()
//{
//#if PLATFORM_IOS
//var store = MonoTouch.Foundation.NSHttpCookieStorage.SharedStorage;
//var cookies = store.Cookies;
//foreach (var c in cookies) {
// store.DeleteCookie (c);
//}
//#elif PLATFORM_ANDROID
//Android.Webkit.CookieSyncManager.CreateInstance (Android.App.Application.Context);
//Android.Webkit.CookieManager.Instance.RemoveAllCookie ();
//#endif
//}
/// <summary>
/// Occurs when the visual, user-interactive, browsing has completed but there
/// is more authentication work to do.
/// </summary>
public event EventHandler BrowsingCompleted;
private bool clearCookies = true;
/// <summary>
/// Raises the browsing completed event.
/// </summary>
protected virtual void OnBrowsingCompleted()
{
var ev = BrowsingCompleted;
if (ev != null)
{
ev(this, EventArgs.Empty);
}
}
public string Scheme
{
get;
set;
}
public string Host
{
get;
set;
}
protected Dictionary<string, string> request_parameters;
/// <summary>
/// Gets or sets the request parameters.
/// Request Parameters for OAuth and OpenId parameters
/// </summary>
/// <value>The request parameters.</value>
public Dictionary<string, string> RequestParameters
{
get
{
return this.request_parameters;
}
set
{
request_parameters = value;
return;
}
}
public bool IsUriEncodedDataString(string s)
{
if
(
s.Equals(Uri.EscapeDataString(s))
&&
Uri.IsWellFormedUriString(s, UriKind.RelativeOrAbsolute)
)
{
return true;
}
return false;
}
public override string ToString()
{
/*
string msg = string.Format
(
"[WebAuthenticator: ClearCookiesBeforeLogin={0}, Scheme={1}, Host={2}, "
+
"RequestParameters={3}, PlatformUIMethod={4}, IsUsingNativeUI={5}]",
ClearCookiesBeforeLogin,
Scheme,
Host,
RequestParameters,
PlatformUIMethod,
IsUsingNativeUI
);
*/
System.Text.StringBuilder sb = new System.Text.StringBuilder(base.ToString());
sb.AppendLine().AppendLine(this.GetType().ToString());
classlevel_depth++;
string prefix = new string('\t', classlevel_depth);
sb.Append(prefix).AppendLine($"IsUsingNativeUI = {IsUsingNativeUI}");
sb.Append(prefix).AppendLine($"Scheme = {Scheme}");
sb.Append(prefix).AppendLine($"Host = {Host}");
sb.Append(prefix).AppendLine($"RequestParameters = {RequestParameters}");
sb.Append(prefix).AppendLine($"ClearCookiesBeforeLogin = {ClearCookiesBeforeLogin}");
sb.Append(prefix).AppendLine($"PlatformUIMethod = {PlatformUIMethod}");
return sb.ToString();
}
}
}
| |
using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using FileHelpers;
using FileHelpers.Events;
using FileHelpersSamples.Properties;
namespace FileHelpersSamples
{
/// <summary>
/// This example show how progress bars work
/// </summary>
public class frmProgressSample : frmFather
{
private Button cmdRun;
private Framework.Controls.XpProgressBar prog1;
private Framework.Controls.XpProgressBar prog4;
private Framework.Controls.XpProgressBar prog3;
private Framework.Controls.XpProgressBar prog2;
private System.Windows.Forms.TextBox txtClass;
private System.Windows.Forms.Label label2;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public frmProgressSample()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <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.cmdRun = new System.Windows.Forms.Button();
this.prog1 = new Framework.Controls.XpProgressBar();
this.prog3 = new Framework.Controls.XpProgressBar();
this.prog2 = new Framework.Controls.XpProgressBar();
this.prog4 = new Framework.Controls.XpProgressBar();
this.txtClass = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// pictureBox3
//
this.pictureBox3.Location = new System.Drawing.Point(568, 8);
this.pictureBox3.Name = "pictureBox3";
//
// cmdRun
//
this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (110)));
this.cmdRun.Font = new System.Drawing.Font("Tahoma",
9.75F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.cmdRun.ForeColor = System.Drawing.Color.Gainsboro;
this.cmdRun.Location = new System.Drawing.Point(336, 8);
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(152, 32);
this.cmdRun.TabIndex = 0;
this.cmdRun.Text = "RUN >>";
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// prog1
//
this.prog1.Color1 = System.Drawing.Color.Blue;
this.prog1.Color2 = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (64)));
this.prog1.ColorText = System.Drawing.Color.WhiteSmoke;
this.prog1.ColorTextShadow = System.Drawing.Color.DimGray;
this.prog1.Font = new System.Drawing.Font("Tahoma",
14.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog1.GradientStyle = Framework.Controls.GradientMode.Horizontal;
this.prog1.Location = new System.Drawing.Point(8, 64);
this.prog1.Name = "prog1";
this.prog1.Position = 0;
this.prog1.PositionMax = 100;
this.prog1.PositionMin = 0;
this.prog1.Size = new System.Drawing.Size(654, 32);
this.prog1.StepDistance = ((System.Byte) (0));
this.prog1.StepWidth = ((System.Byte) (3));
this.prog1.Text = "CodeProject XpProgressBar";
this.prog1.TextShadowAlpha = ((System.Byte) (200));
this.prog1.WatermarkAlpha = 255;
this.prog1.WatermarkImage = null;
//
// prog3
//
this.prog3.Color1 = System.Drawing.Color.FromArgb(((System.Byte) (255)),
((System.Byte) (224)),
((System.Byte) (192)));
this.prog3.Color2 = System.Drawing.Color.FromArgb(((System.Byte) (192)),
((System.Byte) (64)),
((System.Byte) (0)));
this.prog3.ColorText = System.Drawing.Color.FromArgb(((System.Byte) (115)),
((System.Byte) (50)),
((System.Byte) (0)));
this.prog3.ColorTextShadow = System.Drawing.Color.DimGray;
this.prog3.Font = new System.Drawing.Font("Tahoma",
12F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog3.GradientStyle = Framework.Controls.GradientMode.Vertical;
this.prog3.Location = new System.Drawing.Point(8, 144);
this.prog3.Name = "prog3";
this.prog3.Position = 0;
this.prog3.PositionMax = 100;
this.prog3.PositionMin = 0;
this.prog3.Size = new System.Drawing.Size(654, 32);
this.prog3.StepDistance = ((System.Byte) (0));
this.prog3.StepWidth = ((System.Byte) (3));
this.prog3.WatermarkAlpha = 255;
this.prog3.WatermarkImage = null;
//
// prog2
//
this.prog2.Color1 = System.Drawing.Color.AliceBlue;
this.prog2.Color2 = System.Drawing.Color.SteelBlue;
this.prog2.ColorText = System.Drawing.Color.FromArgb(((System.Byte) (0)),
((System.Byte) (0)),
((System.Byte) (64)));
this.prog2.Font = new System.Drawing.Font("Tahoma",
12F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog2.GradientStyle = Framework.Controls.GradientMode.Diagonal;
this.prog2.Location = new System.Drawing.Point(8, 104);
this.prog2.Name = "prog2";
this.prog2.Position = 0;
this.prog2.PositionMax = 100;
this.prog2.PositionMin = 0;
this.prog2.Size = new System.Drawing.Size(654, 32);
this.prog2.Text = "Full Customizable";
this.prog2.TextShadow = false;
this.prog2.WatermarkAlpha = 255;
this.prog2.WatermarkImage = null;
//
// prog4
//
this.prog4.Color1 = System.Drawing.Color.RoyalBlue;
this.prog4.Color2 = System.Drawing.Color.AliceBlue;
this.prog4.ColorText = System.Drawing.Color.Navy;
this.prog4.ColorTextShadow = System.Drawing.Color.DimGray;
this.prog4.Font = new System.Drawing.Font("Tahoma",
11.25F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.prog4.GradientStyle = Framework.Controls.GradientMode.HorizontalCenter;
this.prog4.Location = new System.Drawing.Point(8, 184);
this.prog4.Name = "prog4";
this.prog4.Position = 0;
this.prog4.PositionMax = 100;
this.prog4.PositionMin = 0;
this.prog4.Size = new System.Drawing.Size(654, 32);
this.prog4.StepDistance = ((System.Byte) (0));
this.prog4.StepWidth = ((System.Byte) (3));
this.prog4.WatermarkAlpha = 255;
this.prog4.WatermarkImage = null;
//
// txtClass
//
this.txtClass.Font = new System.Drawing.Font("Courier New",
8.25F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.txtClass.Location = new System.Drawing.Point(8, 240);
this.txtClass.Multiline = true;
this.txtClass.Name = "txtClass";
this.txtClass.ReadOnly = true;
this.txtClass.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtClass.Size = new System.Drawing.Size(656, 224);
this.txtClass.TabIndex = 12;
this.txtClass.Text = @"private void Run()
{
FileHelperEngine engine = new FileHelperEngine(typeof (CustomersVerticalBar));
engine.SetProgressHandler(new ProgressChangeHandler(ProgressChange));
engine.WriteFile(""test.txt"", records);
}
private void ProgressChange(ProgressEventArgs e)
{
prog1.PositionMax = e.ProgressTotal;
prog1.Position = e.ProgressCurrent;
prog1.Text = ""Record "" + e.ProgressCurrent.ToString();
Application.DoEvents();
}";
this.txtClass.WordWrap = false;
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma",
9F,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,
((System.Byte) (0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(8, 224);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(272, 16);
this.label2.TabIndex = 13;
this.label2.Text = "Sample code of using the ProgressChange";
//
// frmProgressSample
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(674, 496);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtClass);
this.Controls.Add(this.prog4);
this.Controls.Add(this.prog2);
this.Controls.Add(this.prog3);
this.Controls.Add(this.prog1);
this.Controls.Add(this.cmdRun);
this.Name = "frmProgressSample";
this.Text = "FileHelpers - Progress Example";
this.Controls.SetChildIndex(this.pictureBox3, 0);
this.Controls.SetChildIndex(this.cmdRun, 0);
this.Controls.SetChildIndex(this.prog1, 0);
this.Controls.SetChildIndex(this.prog3, 0);
this.Controls.SetChildIndex(this.prog2, 0);
this.Controls.SetChildIndex(this.prog4, 0);
this.Controls.SetChildIndex(this.txtClass, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Run the engine with a progress bar
/// hooked into it to give the user a visual
/// cue on how things are progressing.
/// </summary>
private void cmdRun_Click(object sender, EventArgs e)
{
// Disable the button, don't want it clicked twice
cmdRun.Enabled = false;
FileHelperEngine engine = new FileHelperEngine(typeof (CustomersVerticalBar));
object[] records = engine.ReadString(Resources.Customers);
Application.DoEvents();
engine.Progress += ProgressChange;
engine.WriteString(records);
// enable the button again we have finished.
cmdRun.Enabled = true;
}
/// <summary>
/// Set the progress bars data, how it is used is
/// up to the progress bars themselves.
/// </summary>
private void ProgressChange(object sender, ProgressEventArgs e)
{
prog1.PositionMax = e.TotalRecords;
prog2.PositionMax = e.TotalRecords;
prog3.PositionMax = e.TotalRecords;
prog4.PositionMax = e.TotalRecords;
prog1.Position = e.CurrentRecord;
prog2.Position = e.CurrentRecord;
prog3.Position = e.CurrentRecord;
prog4.Position = e.CurrentRecord;
prog3.Text = "Record " + e.CurrentRecord.ToString();
prog4.Text = e.CurrentRecord.ToString() + " Of " + e.TotalRecords.ToString();
Application.DoEvents();
Thread.Sleep(10);
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/datetime.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Type {
/// <summary>Holder for reflection information generated from google/type/datetime.proto</summary>
public static partial class DatetimeReflection {
#region Descriptor
/// <summary>File descriptor for google/type/datetime.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DatetimeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chpnb29nbGUvdHlwZS9kYXRldGltZS5wcm90bxILZ29vZ2xlLnR5cGUaHmdv",
"b2dsZS9wcm90b2J1Zi9kdXJhdGlvbi5wcm90byLgAQoIRGF0ZVRpbWUSDAoE",
"eWVhchgBIAEoBRINCgVtb250aBgCIAEoBRILCgNkYXkYAyABKAUSDQoFaG91",
"cnMYBCABKAUSDwoHbWludXRlcxgFIAEoBRIPCgdzZWNvbmRzGAYgASgFEg0K",
"BW5hbm9zGAcgASgFEi8KCnV0Y19vZmZzZXQYCCABKAsyGS5nb29nbGUucHJv",
"dG9idWYuRHVyYXRpb25IABIqCgl0aW1lX3pvbmUYCSABKAsyFS5nb29nbGUu",
"dHlwZS5UaW1lWm9uZUgAQg0KC3RpbWVfb2Zmc2V0IicKCFRpbWVab25lEgoK",
"AmlkGAEgASgJEg8KB3ZlcnNpb24YAiABKAlCaQoPY29tLmdvb2dsZS50eXBl",
"Qg1EYXRlVGltZVByb3RvUAFaPGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3Rv",
"L2dvb2dsZWFwaXMvdHlwZS9kYXRldGltZTtkYXRldGltZfgBAaICA0dUUGIG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.DateTime), global::Google.Type.DateTime.Parser, new[]{ "Year", "Month", "Day", "Hours", "Minutes", "Seconds", "Nanos", "UtcOffset", "TimeZone" }, new[]{ "TimeOffset" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.TimeZone), global::Google.Type.TimeZone.Parser, new[]{ "Id", "Version" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Represents civil time (or occasionally physical time).
///
/// This type can represent a civil time in one of a few possible ways:
///
/// * When utc_offset is set and time_zone is unset: a civil time on a calendar
/// day with a particular offset from UTC.
/// * When time_zone is set and utc_offset is unset: a civil time on a calendar
/// day in a particular time zone.
/// * When neither time_zone nor utc_offset is set: a civil time on a calendar
/// day in local time.
///
/// The date is relative to the Proleptic Gregorian Calendar.
///
/// If year is 0, the DateTime is considered not to have a specific year. month
/// and day must have valid, non-zero values.
///
/// This type may also be used to represent a physical time if all the date and
/// time fields are set and either case of the `time_offset` oneof is set.
/// Consider using `Timestamp` message for physical time instead. If your use
/// case also would like to store the user's timezone, that can be done in
/// another field.
///
/// This type is more flexible than some applications may want. Make sure to
/// document and validate your application's limitations.
/// </summary>
public sealed partial class DateTime : pb::IMessage<DateTime>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<DateTime> _parser = new pb::MessageParser<DateTime>(() => new DateTime());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DateTime> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.DatetimeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DateTime() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DateTime(DateTime other) : this() {
year_ = other.year_;
month_ = other.month_;
day_ = other.day_;
hours_ = other.hours_;
minutes_ = other.minutes_;
seconds_ = other.seconds_;
nanos_ = other.nanos_;
switch (other.TimeOffsetCase) {
case TimeOffsetOneofCase.UtcOffset:
UtcOffset = other.UtcOffset.Clone();
break;
case TimeOffsetOneofCase.TimeZone:
TimeZone = other.TimeZone.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DateTime Clone() {
return new DateTime(this);
}
/// <summary>Field number for the "year" field.</summary>
public const int YearFieldNumber = 1;
private int year_;
/// <summary>
/// Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a
/// datetime without a year.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Year {
get { return year_; }
set {
year_ = value;
}
}
/// <summary>Field number for the "month" field.</summary>
public const int MonthFieldNumber = 2;
private int month_;
/// <summary>
/// Required. Month of year. Must be from 1 to 12.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Month {
get { return month_; }
set {
month_ = value;
}
}
/// <summary>Field number for the "day" field.</summary>
public const int DayFieldNumber = 3;
private int day_;
/// <summary>
/// Required. Day of month. Must be from 1 to 31 and valid for the year and
/// month.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Day {
get { return day_; }
set {
day_ = value;
}
}
/// <summary>Field number for the "hours" field.</summary>
public const int HoursFieldNumber = 4;
private int hours_;
/// <summary>
/// Required. Hours of day in 24 hour format. Should be from 0 to 23. An API
/// may choose to allow the value "24:00:00" for scenarios like business
/// closing time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Hours {
get { return hours_; }
set {
hours_ = value;
}
}
/// <summary>Field number for the "minutes" field.</summary>
public const int MinutesFieldNumber = 5;
private int minutes_;
/// <summary>
/// Required. Minutes of hour of day. Must be from 0 to 59.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Minutes {
get { return minutes_; }
set {
minutes_ = value;
}
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 6;
private int seconds_;
/// <summary>
/// Required. Seconds of minutes of the time. Must normally be from 0 to 59. An
/// API may allow the value 60 if it allows leap-seconds.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 7;
private int nanos_;
/// <summary>
/// Required. Fractions of seconds in nanoseconds. Must be from 0 to
/// 999,999,999.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
/// <summary>Field number for the "utc_offset" field.</summary>
public const int UtcOffsetFieldNumber = 8;
/// <summary>
/// UTC offset. Must be whole seconds, between -18 hours and +18 hours.
/// For example, a UTC offset of -4:00 would be represented as
/// { seconds: -14400 }.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Duration UtcOffset {
get { return timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset ? (global::Google.Protobuf.WellKnownTypes.Duration) timeOffset_ : null; }
set {
timeOffset_ = value;
timeOffsetCase_ = value == null ? TimeOffsetOneofCase.None : TimeOffsetOneofCase.UtcOffset;
}
}
/// <summary>Field number for the "time_zone" field.</summary>
public const int TimeZoneFieldNumber = 9;
/// <summary>
/// Time zone.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Type.TimeZone TimeZone {
get { return timeOffsetCase_ == TimeOffsetOneofCase.TimeZone ? (global::Google.Type.TimeZone) timeOffset_ : null; }
set {
timeOffset_ = value;
timeOffsetCase_ = value == null ? TimeOffsetOneofCase.None : TimeOffsetOneofCase.TimeZone;
}
}
private object timeOffset_;
/// <summary>Enum of possible cases for the "time_offset" oneof.</summary>
public enum TimeOffsetOneofCase {
None = 0,
UtcOffset = 8,
TimeZone = 9,
}
private TimeOffsetOneofCase timeOffsetCase_ = TimeOffsetOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeOffsetOneofCase TimeOffsetCase {
get { return timeOffsetCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearTimeOffset() {
timeOffsetCase_ = TimeOffsetOneofCase.None;
timeOffset_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DateTime);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DateTime other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Year != other.Year) return false;
if (Month != other.Month) return false;
if (Day != other.Day) return false;
if (Hours != other.Hours) return false;
if (Minutes != other.Minutes) return false;
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
if (!object.Equals(UtcOffset, other.UtcOffset)) return false;
if (!object.Equals(TimeZone, other.TimeZone)) return false;
if (TimeOffsetCase != other.TimeOffsetCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Year != 0) hash ^= Year.GetHashCode();
if (Month != 0) hash ^= Month.GetHashCode();
if (Day != 0) hash ^= Day.GetHashCode();
if (Hours != 0) hash ^= Hours.GetHashCode();
if (Minutes != 0) hash ^= Minutes.GetHashCode();
if (Seconds != 0) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) hash ^= UtcOffset.GetHashCode();
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) hash ^= TimeZone.GetHashCode();
hash ^= (int) timeOffsetCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Year != 0) {
output.WriteRawTag(8);
output.WriteInt32(Year);
}
if (Month != 0) {
output.WriteRawTag(16);
output.WriteInt32(Month);
}
if (Day != 0) {
output.WriteRawTag(24);
output.WriteInt32(Day);
}
if (Hours != 0) {
output.WriteRawTag(32);
output.WriteInt32(Hours);
}
if (Minutes != 0) {
output.WriteRawTag(40);
output.WriteInt32(Minutes);
}
if (Seconds != 0) {
output.WriteRawTag(48);
output.WriteInt32(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(56);
output.WriteInt32(Nanos);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
output.WriteRawTag(66);
output.WriteMessage(UtcOffset);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
output.WriteRawTag(74);
output.WriteMessage(TimeZone);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Year != 0) {
output.WriteRawTag(8);
output.WriteInt32(Year);
}
if (Month != 0) {
output.WriteRawTag(16);
output.WriteInt32(Month);
}
if (Day != 0) {
output.WriteRawTag(24);
output.WriteInt32(Day);
}
if (Hours != 0) {
output.WriteRawTag(32);
output.WriteInt32(Hours);
}
if (Minutes != 0) {
output.WriteRawTag(40);
output.WriteInt32(Minutes);
}
if (Seconds != 0) {
output.WriteRawTag(48);
output.WriteInt32(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(56);
output.WriteInt32(Nanos);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
output.WriteRawTag(66);
output.WriteMessage(UtcOffset);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
output.WriteRawTag(74);
output.WriteMessage(TimeZone);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Year != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Year);
}
if (Month != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Month);
}
if (Day != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Day);
}
if (Hours != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Hours);
}
if (Minutes != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Minutes);
}
if (Seconds != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UtcOffset);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TimeZone);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DateTime other) {
if (other == null) {
return;
}
if (other.Year != 0) {
Year = other.Year;
}
if (other.Month != 0) {
Month = other.Month;
}
if (other.Day != 0) {
Day = other.Day;
}
if (other.Hours != 0) {
Hours = other.Hours;
}
if (other.Minutes != 0) {
Minutes = other.Minutes;
}
if (other.Seconds != 0) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
switch (other.TimeOffsetCase) {
case TimeOffsetOneofCase.UtcOffset:
if (UtcOffset == null) {
UtcOffset = new global::Google.Protobuf.WellKnownTypes.Duration();
}
UtcOffset.MergeFrom(other.UtcOffset);
break;
case TimeOffsetOneofCase.TimeZone:
if (TimeZone == null) {
TimeZone = new global::Google.Type.TimeZone();
}
TimeZone.MergeFrom(other.TimeZone);
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Year = input.ReadInt32();
break;
}
case 16: {
Month = input.ReadInt32();
break;
}
case 24: {
Day = input.ReadInt32();
break;
}
case 32: {
Hours = input.ReadInt32();
break;
}
case 40: {
Minutes = input.ReadInt32();
break;
}
case 48: {
Seconds = input.ReadInt32();
break;
}
case 56: {
Nanos = input.ReadInt32();
break;
}
case 66: {
global::Google.Protobuf.WellKnownTypes.Duration subBuilder = new global::Google.Protobuf.WellKnownTypes.Duration();
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
subBuilder.MergeFrom(UtcOffset);
}
input.ReadMessage(subBuilder);
UtcOffset = subBuilder;
break;
}
case 74: {
global::Google.Type.TimeZone subBuilder = new global::Google.Type.TimeZone();
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
subBuilder.MergeFrom(TimeZone);
}
input.ReadMessage(subBuilder);
TimeZone = subBuilder;
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Year = input.ReadInt32();
break;
}
case 16: {
Month = input.ReadInt32();
break;
}
case 24: {
Day = input.ReadInt32();
break;
}
case 32: {
Hours = input.ReadInt32();
break;
}
case 40: {
Minutes = input.ReadInt32();
break;
}
case 48: {
Seconds = input.ReadInt32();
break;
}
case 56: {
Nanos = input.ReadInt32();
break;
}
case 66: {
global::Google.Protobuf.WellKnownTypes.Duration subBuilder = new global::Google.Protobuf.WellKnownTypes.Duration();
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
subBuilder.MergeFrom(UtcOffset);
}
input.ReadMessage(subBuilder);
UtcOffset = subBuilder;
break;
}
case 74: {
global::Google.Type.TimeZone subBuilder = new global::Google.Type.TimeZone();
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
subBuilder.MergeFrom(TimeZone);
}
input.ReadMessage(subBuilder);
TimeZone = subBuilder;
break;
}
}
}
}
#endif
}
/// <summary>
/// Represents a time zone from the
/// [IANA Time Zone Database](https://www.iana.org/time-zones).
/// </summary>
public sealed partial class TimeZone : pb::IMessage<TimeZone>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<TimeZone> _parser = new pb::MessageParser<TimeZone>(() => new TimeZone());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TimeZone> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.DatetimeReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeZone() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeZone(TimeZone other) : this() {
id_ = other.id_;
version_ = other.version_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TimeZone Clone() {
return new TimeZone(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
/// <summary>
/// IANA Time Zone Database time zone, e.g. "America/New_York".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 2;
private string version_ = "";
/// <summary>
/// Optional. IANA Time Zone Database version number, e.g. "2019a".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Version {
get { return version_; }
set {
version_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TimeZone);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TimeZone other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Version != other.Version) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (Version.Length != 0) hash ^= Version.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Version.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Version);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Version.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Version);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (Version.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Version);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TimeZone other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.Version.Length != 0) {
Version = other.Version;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
Version = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
Version = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Text;
using FileHelpers.Dynamic;
using System.IO;
using FileHelpers.Helpers;
namespace FileHelpers.Detection
{
/// <summary>
/// Utility class used to auto detect the record format,
/// the number of fields, the type, etc.
/// </summary>
public sealed class SmartFormatDetector
{
/// <summary>
/// Initializes a new instance of the <see cref="SmartFormatDetector"/> class.
/// </summary>
public SmartFormatDetector()
{
QuotedChar = '"';
}
#region " Constants "
private const int MinSampleData = 10;
private const double MinDelimitedDeviation = 0.30001;
#endregion
#region " Properties "
private FormatHint mFormatHint;
/// <summary>
/// Provides a suggestion to the <see cref="SmartFormatDetector"/>
/// about the records in the file
/// </summary>
public FormatHint FormatHint
{
get { return mFormatHint; }
set { mFormatHint = value; }
}
private int mMaxSampleLines = 300;
/// <summary>
/// The number of lines of each file to be used as sample data.
/// </summary>
public int MaxSampleLines
{
get { return mMaxSampleLines; }
set { mMaxSampleLines = value; }
}
private Encoding mEncoding = Encoding.GetEncoding(0);
/// <summary>The encoding to Read and Write the streams.</summary>
/// <remarks>Default is the system's current ANSI code page.</remarks>
public Encoding Encoding
{
get { return mEncoding; }
set { mEncoding = value; }
}
private double mFixedLengthDeviationTolerance = 0.01;
///<summary>
///Indicates if the sample file has headers
///</summary>
public bool? FileHasHeaders { get; set; }
/// <summary>
/// Used to calculate when a file has fixed length records.
/// Between 0.0 - 1.0 (Default 0.01)
/// </summary>
public double FixedLengthDeviationTolerance
{
get { return mFixedLengthDeviationTolerance; }
set { mFixedLengthDeviationTolerance = value; }
}
#endregion
#region " Public Methods "
/// <summary>
/// Tries to detect the possible formats of the file using the <see cref="FormatHint"/>
/// </summary>
/// <param name="file">The file to be used as sample data</param>
/// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns>
public RecordFormatInfo[] DetectFileFormat(string file)
{
return DetectFileFormat(new string[] {file});
}
/// <summary>
/// Tries to detect the possible formats of the file using the <see cref="FormatHint"/>
/// </summary>
/// <param name="files">The files to be used as sample data</param>
/// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns>
public RecordFormatInfo[] DetectFileFormat(IEnumerable<string> files)
{
var readers = new List<TextReader>();
foreach (var file in files)
{
readers.Add(new StreamReader(file, Encoding));
}
var res = DetectFileFormat(readers);
foreach (var reader in readers)
{
reader.Close();
}
return res;
}
/// <summary>
/// Tries to detect the possible formats of the file using the <see cref="FormatHint"/>
/// </summary>
/// <param name="files">The files to be used as sample data</param>
/// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns>
public RecordFormatInfo[] DetectFileFormat(IEnumerable<TextReader> files)
{
var res = new List<RecordFormatInfo>();
string[][] sampleData = GetSampleLines(files, MaxSampleLines);
switch (mFormatHint) {
case FormatHint.Unknown:
CreateMixedOptions(sampleData, res);
break;
case FormatHint.FixedLength:
CreateFixedLengthOptions(sampleData, res);
break;
case FormatHint.Delimited:
CreateDelimiterOptions(sampleData, res);
break;
case FormatHint.DelimitedByTab:
CreateDelimiterOptions(sampleData, res, '\t');
break;
case FormatHint.DelimitedByComma:
CreateDelimiterOptions(sampleData, res, ',');
break;
case FormatHint.DelimitedBySemicolon:
CreateDelimiterOptions(sampleData, res, ';');
break;
default:
throw new InvalidOperationException("Unsuported FormatHint value.");
}
foreach (var option in res) {
DetectOptionals(option, sampleData);
DetectTypes(option, sampleData);
DetectQuoted(option, sampleData);
}
// Sort by confidence
res.Sort(
delegate(RecordFormatInfo x, RecordFormatInfo y) { return -1*x.Confidence.CompareTo(y.Confidence); });
return res.ToArray();
}
#endregion
#region " Fields Properties Methods "
private void DetectQuoted(RecordFormatInfo format, string[][] data)
{
if (format.ClassBuilder is FixedLengthClassBuilder)
return;
// TODO: Add FieldQuoted
}
private void DetectTypes(RecordFormatInfo format, string[][] data)
{
// TODO: Try to detect posible formats (mostly numbers or dates)
}
private void DetectOptionals(RecordFormatInfo option, string[][] data)
{
// TODO: Try to detect optional fields
}
#endregion
#region " Create Options Methods "
// UNKNOWN
private void CreateMixedOptions(string[][] data, List<RecordFormatInfo> res)
{
var stats = Indicators.CalculateAsFixedSize (data);
if (stats.Deviation / stats.Avg <= FixedLengthDeviationTolerance * Math.Min (1, NumberOfLines (data) / MinSampleData))
CreateFixedLengthOptions(data, res);
CreateDelimiterOptions(data, res);
//if (deviation > average * 0.01 &&
// deviation < average * 0.05)
// CreateFixedLengthOptions(data, res);
}
// FIXED LENGTH
private void CreateFixedLengthOptions(string[][] data, List<RecordFormatInfo> res)
{
var format = new RecordFormatInfo();
var stats = Indicators.CalculateAsFixedSize (data);
format.mConfidence = (int)(Math.Max (0, 1 - stats.Deviation / stats.Avg) * 100);
var builder = new FixedLengthClassBuilder("AutoDetectedClass");
CreateFixedLengthFields(data, builder);
format.mClassBuilder = builder;
res.Add(format);
}
/// <summary>
/// start and length of fixed length column
/// </summary>
private class FixedColumnInfo
{
/// <summary>
/// start position of column
/// </summary>
public int Start;
/// <summary>
/// Length of column
/// </summary>
public int Length;
}
private void CreateFixedLengthFields(string[][] data, FixedLengthClassBuilder builder)
{
List<FixedColumnInfo> res = null;
foreach (var dataFile in data) {
List<FixedColumnInfo> candidates = CreateFixedLengthCandidates(dataFile);
res = JoinFixedColCandidates(res, candidates);
}
for (int i = 0; i < res.Count; i++) {
FixedColumnInfo col = res[i];
builder.AddField("Field" + i.ToString().PadLeft(4, '0'), col.Length, typeof (string));
}
}
private List<FixedColumnInfo> CreateFixedLengthCandidates(string[] lines)
{
List<FixedColumnInfo> res = null;
foreach (var line in lines) {
var candidates = new List<FixedColumnInfo>();
int blanks = 0;
FixedColumnInfo col = null;
for (int i = 1; i < line.Length; i++) {
if (char.IsWhiteSpace(line[i]))
blanks += 1;
else {
if (blanks > 2) {
if (col == null) {
col = new FixedColumnInfo {
Start = 0,
Length = i
};
}
else {
FixedColumnInfo prevCol = col;
col = new FixedColumnInfo {
Start = prevCol.Start + prevCol.Length
};
col.Length = i - col.Start;
}
candidates.Add(col);
blanks = 0;
}
}
}
if (col == null) {
col = new FixedColumnInfo {
Start = 0,
Length = line.Length
};
}
else {
FixedColumnInfo prevCol = col;
col = new FixedColumnInfo {
Start = prevCol.Start + prevCol.Length
};
col.Length = line.Length - col.Start;
}
candidates.Add(col);
res = JoinFixedColCandidates(res, candidates);
}
return res;
}
private List<FixedColumnInfo> JoinFixedColCandidates(List<FixedColumnInfo> cand1, List<FixedColumnInfo> cand2)
{
if (cand1 == null)
return cand2;
if (cand2 == null)
return cand1;
// Merge the result based on confidence
return cand1;
}
bool HeadersInData (DelimiterInfo info, string[] headerValues, string[] rows)
{
var duplicate = 0;
var first = true;
foreach (var row in rows) {
if (first) {
first = false;
continue;
}
var values = row.Split (new char[]{ info.Delimiter });
if (values.Length != headerValues.Length)
continue;
for (int i = 0; i < values.Length; i++) {
if (values [i] == headerValues [i])
duplicate++;
}
}
return duplicate >= rows.Length * 0.25;
}
bool DetectIfContainsHeaders (DelimiterInfo info, string[][] sampleData)
{
if (sampleData.Length >= 2) {
return SameFirstLine (info, sampleData);
}
if (sampleData.Length >= 1) {
var firstLine = sampleData [0] [0].Split (new char[]{ info.Delimiter });
var res = AreAllHeaders (firstLine);
if (res == false)
return false; // if has headers that starts with numbers so near sure are data and no header is present
if (HeadersInData(info, firstLine, sampleData[0]))
return false;
return true;
}
return false;
}
bool SameFirstLine (DelimiterInfo info, string[][] sampleData)
{
for (int i = 1; i < sampleData.Length; i++) {
if (!SameHeaders (info, sampleData [0][0], sampleData [i][0]))
return false;
}
return true;
}
bool SameHeaders (DelimiterInfo info, string line1, string line2)
{
return line1.Replace (info.Delimiter.ToString (), "").Trim ()
== line2.Replace (info.Delimiter.ToString (), "").Trim ();
}
bool AreAllHeaders ( string[] rowData)
{
foreach (var item in rowData) {
var fieldData = item.Trim ();
if (fieldData.Length == 0)
return false;
if (char.IsDigit (fieldData [0]))
return false;
}
return true;
}
// DELIMITED
private void CreateDelimiterOptions(string[][] sampleData, List<RecordFormatInfo> res, char delimiter = '\0')
{
var delimiters = new List<DelimiterInfo>();
if (delimiter == '\0')
delimiters = GetDelimiters(sampleData);
else
delimiters.Add(GetDelimiterInfo(sampleData, delimiter));
foreach (var info in delimiters) {
var format = new RecordFormatInfo {
mConfidence = (int) ((1 - info.Deviation)*100)
};
AdjustConfidence(format, info);
var fileHasHeaders = false;
if (FileHasHeaders.HasValue)
fileHasHeaders = FileHasHeaders.Value;
else {
fileHasHeaders = DetectIfContainsHeaders (info, sampleData) ;
}
var builder = new DelimitedClassBuilder("AutoDetectedClass", info.Delimiter.ToString()) {
IgnoreFirstLines = fileHasHeaders
? 1
: 0
};
var firstLineSplitted = sampleData[0][0].Split(info.Delimiter);
for (int i = 0; i < info.Max + 1; i++) {
string name = "Field " + (i + 1).ToString().PadLeft(3, '0');
if (fileHasHeaders && i < firstLineSplitted.Length)
name = firstLineSplitted[i];
var f = builder.AddField(StringHelper.ToValidIdentifier(name));
if (i > info.Min)
f.FieldOptional = true;
}
format.mClassBuilder = builder;
res.Add(format);
}
}
private void AdjustConfidence(RecordFormatInfo format, DelimiterInfo info)
{
switch (info.Delimiter) {
case '"': // Avoid the quote identifier
case '\'': // Avoid the quote identifier
format.mConfidence = (int) (format.Confidence*0.2);
break;
case '/': // Avoid the date delimiters and url to be selected
case '.': // Avoid the decimal separator to be selected
format.mConfidence = (int) (format.Confidence*0.4);
break;
case '@': // Avoid the mails separator to be selected
case '&': // Avoid this is near a letter and URLS
case '=': // Avoid because URLS contains it
case ':': // Avoid because URLS contains it
format.mConfidence = (int) (format.Confidence*0.6);
break;
case '-': // Avoid this other date separator
format.mConfidence = (int) (format.Confidence*0.7);
break;
case ',': // Help the , ; tab | to be confident
case ';':
case '\t':
case '|':
format.mConfidence = (int) Math.Min(100, format.Confidence*1.15);
break;
}
}
#endregion
#region " Helper & Utility Methods "
private string[][] GetSampleLines(IEnumerable<string> files, int nroOfLines)
{
var res = new List<string[]>();
foreach (var file in files)
res.Add(RawReadFirstLinesArray(file, nroOfLines, mEncoding));
return res.ToArray();
}
private static string[][] GetSampleLines(IEnumerable<TextReader> files, int nroOfLines)
{
var res = new List<string[]>();
foreach (var file in files)
res.Add(RawReadFirstLinesArray(file, nroOfLines));
return res.ToArray();
}
private static int NumberOfLines(string[][] data)
{
int lines = 0;
foreach (var fileData in data)
lines += fileData.Length;
return lines;
}
/// <summary>
/// Shortcut method to read the first n lines of a text file as array.
/// </summary>
/// <param name="file">The file name</param>
/// <param name="lines">The number of lines to read.</param>
/// <param name="encoding">The Encoding used to read the file</param>
/// <returns>The first n lines of the file.</returns>
private static string[] RawReadFirstLinesArray(string file, int lines, Encoding encoding)
{
var res = new List<string>(lines);
using (var reader = new StreamReader(file, encoding))
{
for (int i = 0; i < lines; i++)
{
string line = reader.ReadLine();
if (line == null)
break;
else
res.Add(line);
}
}
return res.ToArray();
}
/// <summary>
/// Shortcut method to read the first n lines of a text file as array.
/// </summary>
/// <param name="stream">The text reader name</param>
/// <param name="lines">The number of lines to read.</param>
/// <returns>The first n lines of the file.</returns>
private static string[] RawReadFirstLinesArray(TextReader stream, int lines)
{
var res = new List<string>(lines);
for (int i = 0; i < lines; i++)
{
string line = stream.ReadLine();
if (line == null)
break;
else
res.Add(line);
}
return res.ToArray();
}
/// <summary>
/// Calculate statistics based on sample data for the delimitter supplied
/// </summary>
/// <param name="data"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
private DelimiterInfo GetDelimiterInfo(string[][] data, char delimiter)
{
var indicators = Indicators.CalculateByDelimiter (delimiter, data, QuotedChar);
return new DelimiterInfo (delimiter, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation);
}
private List<DelimiterInfo> GetDelimiters(string[][] data)
{
var frequency = new Dictionary<char, int>();
int lines = 0;
for (int i = 0; i < data.Length; i++) {
for (int j = 0; j < data[i].Length; j++) {
// Ignore Header Line (if any)
if (j == 0)
continue;
// ignore empty lines
string line = data[i][j];
if (string.IsNullOrEmpty (line))
continue;
// analyse line
lines++;
for (int ci = 0; ci < line.Length; ci++) {
char c = line[ci];
if (char.IsLetterOrDigit(c)
||
c == ' ')
continue;
int count;
if (frequency.TryGetValue(c, out count)) {
count++;
frequency[c] = count;
}
else
frequency.Add(c, 1);
}
}
}
var candidates = new List<DelimiterInfo>();
// sanity check
if (lines == 0)
return candidates;
// remove delimiters with low occurrence count
var delimiters = new List<char> (frequency.Count);
foreach (var pair in frequency)
{
if (pair.Value >= lines)
delimiters.Add (pair.Key);
}
// calculate
foreach (var key in delimiters)
{
var indicators = Indicators.CalculateByDelimiter (key, data, QuotedChar);
// Adjust based on the number of lines
if (lines < MinSampleData)
indicators.Deviation = indicators.Deviation * Math.Min (1, ((double)lines) / MinSampleData);
if (indicators.Avg > 1 &&
indicators.Deviation < MinDelimitedDeviation)
candidates.Add (new DelimiterInfo (key, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation));
}
return candidates;
}
#endregion
/// <summary>
/// Gets or sets the quoted char.
/// </summary>
/// <value>The quoted char.</value>
private char QuotedChar { get; set; }
#region " Statistics Functions "
/// <summary>
/// Collection of statistics about fields found
/// </summary>
private class Indicators
{
/// <summary>
/// Maximum number of fields found
/// </summary>
public int Max = int.MinValue;
/// <summary>
/// Mimumim number of fields found
/// </summary>
public int Min = int.MaxValue;
/// <summary>
/// Average number of delimiters foudn per line
/// </summary>
public double Avg = 0;
/// <summary>
/// Calculated deviation
/// </summary>
public double Deviation = 0;
/// <summary>
/// Total analysed lines
/// </summary>
public int Lines = 0;
private static double CalculateDeviation (IList<int> values, double avg)
{
double sum = 0;
for (int i = 0; i < values.Count; i++)
{
sum += Math.Pow (values[i] - avg, 2);
}
return Math.Sqrt (sum / values.Count);
}
private static int CountNumberOfDelimiters (string line, char delimiter)
{
int count = 0;
char c;
for (int i = 0; i < line.Length; i++)
{
c = line[i];
if (c == ' ' || char.IsLetterOrDigit (c))
continue;
count++;
}
return count;
}
public static Indicators CalculateByDelimiter (char delimiter, string[][] data, char? quotedChar)
{
var res = new Indicators ();
int totalDelimiters = 0;
int lines = 0;
List<int> delimiterPerLine = new List<int> (100);
foreach (var fileData in data)
{
foreach (var line in fileData)
{
if (string.IsNullOrEmpty (line))
continue;
lines++;
var delimiterInLine = 0;
if (quotedChar.HasValue)
delimiterInLine = QuoteHelper.CountNumberOfDelimiters (line, delimiter, quotedChar.Value);
else
delimiterInLine = CountNumberOfDelimiters (line, delimiter);
// add count for deviation analysis
delimiterPerLine.Add (delimiterInLine);
if (delimiterInLine > res.Max)
res.Max = delimiterInLine;
if (delimiterInLine < res.Min)
res.Min = delimiterInLine;
totalDelimiters += delimiterInLine;
}
}
res.Avg = totalDelimiters / (double)lines;
// calculate deviation
res.Deviation = CalculateDeviation (delimiterPerLine, res.Avg);
return res;
}
public static Indicators CalculateAsFixedSize (string[][] data)
{
var res = new Indicators ();
double sum = 0;
int lines = 0;
List<int> sizePerLine = new List<int> (100);
foreach (var fileData in data)
{
foreach (var line in fileData)
{
if (string.IsNullOrEmpty (line))
continue;
lines++;
sum += line.Length;
sizePerLine.Add (line.Length);
if (line.Length > res.Max)
res.Max = line.Length;
if (line.Length < res.Min)
res.Min = line.Length;
}
}
res.Avg = sum / (double)lines;
// calculate deviation
res.Deviation = CalculateDeviation (sizePerLine, res.Avg);
return res;
}
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFiDirect;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2_Connector : Page
{
private MainPage rootPage = MainPage.Current;
DeviceWatcher _deviceWatcher;
bool _fWatcherStarted = false;
WiFiDirectAdvertisementPublisher _publisher = new WiFiDirectAdvertisementPublisher();
public ObservableCollection<DiscoveredDevice> DiscoveredDevices { get; } = new ObservableCollection<DiscoveredDevice>();
public ObservableCollection<ConnectedDevice> ConnectedDevices { get; } = new ObservableCollection<ConnectedDevice>();
public Scenario2_Connector()
{
this.InitializeComponent();
}
private void btnWatcher_Click(object sender, RoutedEventArgs e)
{
if (_fWatcherStarted == false)
{
_publisher.Start();
if (_publisher.Status != WiFiDirectAdvertisementPublisherStatus.Started)
{
rootPage.NotifyUser("Failed to start advertisement.", NotifyType.ErrorMessage);
return;
}
DiscoveredDevices.Clear();
rootPage.NotifyUser("Finding Devices...", NotifyType.StatusMessage);
String deviceSelector = WiFiDirectDevice.GetDeviceSelector(
Utils.GetSelectedItemTag<WiFiDirectDeviceSelectorType>(cmbDeviceSelector));
_deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });
_deviceWatcher.Added += OnDeviceAdded;
_deviceWatcher.Removed += OnDeviceRemoved;
_deviceWatcher.Updated += OnDeviceUpdated;
_deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
_deviceWatcher.Stopped += OnStopped;
_deviceWatcher.Start();
btnWatcher.Content = "Stop Watcher";
_fWatcherStarted = true;
}
else
{
_publisher.Stop();
btnWatcher.Content = "Start Watcher";
_fWatcherStarted = false;
_deviceWatcher.Added -= OnDeviceAdded;
_deviceWatcher.Removed -= OnDeviceRemoved;
_deviceWatcher.Updated -= OnDeviceUpdated;
_deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
_deviceWatcher.Stopped -= OnStopped;
_deviceWatcher.Stop();
rootPage.NotifyUser("Device watcher stopped.", NotifyType.StatusMessage);
}
}
#region DeviceWatcherEvents
private async void OnDeviceAdded(DeviceWatcher deviceWatcher, DeviceInformation deviceInfo)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
DiscoveredDevices.Add(new DiscoveredDevice(deviceInfo));
});
}
private async void OnDeviceRemoved(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
foreach (DiscoveredDevice discoveredDevice in DiscoveredDevices)
{
if (discoveredDevice.DeviceInfo.Id == deviceInfoUpdate.Id)
{
DiscoveredDevices.Remove(discoveredDevice);
break;
}
}
});
}
private async void OnDeviceUpdated(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
foreach (DiscoveredDevice discoveredDevice in DiscoveredDevices)
{
if (discoveredDevice.DeviceInfo.Id == deviceInfoUpdate.Id)
{
discoveredDevice.UpdateDeviceInfo(deviceInfoUpdate);
break;
}
}
});
}
private void OnEnumerationCompleted(DeviceWatcher deviceWatcher, object o)
{
rootPage.NotifyUserFromBackground("DeviceWatcher enumeration completed", NotifyType.StatusMessage);
}
private void OnStopped(DeviceWatcher deviceWatcher, object o)
{
rootPage.NotifyUserFromBackground("DeviceWatcher stopped", NotifyType.StatusMessage);
}
#endregion
private void btnIe_Click(object sender, RoutedEventArgs e)
{
var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem;
if (discoveredDevice == null)
{
rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
return;
}
IList<WiFiDirectInformationElement> informationElements = null;
try
{
informationElements = WiFiDirectInformationElement.CreateFromDeviceInformation(discoveredDevice.DeviceInfo);
}
catch (Exception ex)
{
rootPage.NotifyUser("No Information element found: " + ex.Message, NotifyType.ErrorMessage);
}
if (informationElements != null)
{
StringWriter message = new StringWriter();
foreach (WiFiDirectInformationElement informationElement in informationElements)
{
string ouiName = CryptographicBuffer.EncodeToHexString(informationElement.Oui);
string value = string.Empty;
Byte[] bOui = informationElement.Oui.ToArray();
if (bOui.SequenceEqual(Globals.MsftOui))
{
// The format of Microsoft information elements is documented here:
// https://msdn.microsoft.com/en-us/library/dn392651.aspx
// with errata here:
// https://msdn.microsoft.com/en-us/library/mt242386.aspx
ouiName += " (Microsoft)";
}
else if (bOui.SequenceEqual(Globals.WfaOui))
{
ouiName += " (WFA)";
}
else if (bOui.SequenceEqual(Globals.CustomOui))
{
ouiName += " (Custom)";
if (informationElement.OuiType == Globals.CustomOuiType)
{
DataReader dataReader = DataReader.FromBuffer(informationElement.Value);
dataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
dataReader.ByteOrder = ByteOrder.LittleEndian;
// Read the string.
try
{
string data = dataReader.ReadString(dataReader.ReadUInt32());
value = $"Data: {data}";
}
catch (Exception)
{
value = "(Unable to parse)";
}
}
}
message.WriteLine($"OUI {ouiName}, Type {informationElement.OuiType} {value}");
}
message.Write($"Information elements found: {informationElements.Count}");
rootPage.NotifyUser(message.ToString(), NotifyType.StatusMessage);
}
}
private async void btnFromId_Click(object sender, RoutedEventArgs e)
{
var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem;
if (discoveredDevice == null)
{
rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
return;
}
rootPage.NotifyUser($"Connecting to {discoveredDevice.DeviceInfo.Name}...", NotifyType.StatusMessage);
if (!discoveredDevice.DeviceInfo.Pairing.IsPaired)
{
if (!await connectionSettingsPanel.RequestPairDeviceAsync(discoveredDevice.DeviceInfo.Pairing))
{
return;
}
}
try
{
// IMPORTANT: FromIdAsync needs to be called from the UI thread
var wfdDevice = await WiFiDirectDevice.FromIdAsync(discoveredDevice.DeviceInfo.Id);
// Register for the ConnectionStatusChanged event handler
wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
IReadOnlyList<EndpointPair> endpointPairs = wfdDevice.GetConnectionEndpointPairs();
HostName remoteHostName = endpointPairs[0].RemoteHostName;
rootPage.NotifyUser($"Devices connected on L2 layer, connecting to IP Address: {remoteHostName} Port: {Globals.strServerPort}",
NotifyType.StatusMessage);
// Wait for server to start listening on a socket
await Task.Delay(2000);
// Connect to Advertiser on L4 layer
StreamSocket clientSocket = new StreamSocket();
await clientSocket.ConnectAsync(remoteHostName, Globals.strServerPort);
rootPage.NotifyUser("Connected with remote side on L4 layer", NotifyType.StatusMessage);
SocketReaderWriter socketRW = new SocketReaderWriter(clientSocket, rootPage);
string sessionId = Path.GetRandomFileName();
ConnectedDevice connectedDevice = new ConnectedDevice(sessionId, wfdDevice, socketRW);
ConnectedDevices.Add(connectedDevice);
// The first message sent over the socket is the name of the connection.
await socketRW.WriteMessageAsync(sessionId);
while (await socketRW.ReadMessageAsync() != null)
{
// Keep reading messages
}
}
catch (TaskCanceledException)
{
rootPage.NotifyUser("FromIdAsync was canceled by user", NotifyType.ErrorMessage);
}
catch (Exception ex)
{
rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
}
}
private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
{
rootPage.NotifyUserFromBackground($"Connection status changed: {sender.ConnectionStatus}", NotifyType.StatusMessage);
}
private async void btnSendMessage_Click(object sender, RoutedEventArgs e)
{
var connectedDevice = (ConnectedDevice)lvConnectedDevices.SelectedItem;
await connectedDevice.SocketRW.WriteMessageAsync(txtSendMessage.Text);
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
var connectedDevice = (ConnectedDevice)lvConnectedDevices.SelectedItem;
ConnectedDevices.Remove(connectedDevice);
// Close socket and WiFiDirect object
connectedDevice.Dispose();
}
private async void btnUnpair_Click(object sender, RoutedEventArgs e)
{
var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem;
if (discoveredDevice == null)
{
rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage);
return;
}
DeviceUnpairingResult result = await discoveredDevice.DeviceInfo.Pairing.UnpairAsync();
rootPage.NotifyUser($"Unpair result: {result.Status}", NotifyType.StatusMessage);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories
{
public static partial class DataSliceOperationsExtensions
{
/// <summary>
/// Gets the first page of data slice instances with the link to the
/// next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='dataSliceRangeStartTime'>
/// Required. The data slice range start time in round-trip ISO 8601
/// format.
/// </param>
/// <param name='dataSliceRangeEndTime'>
/// Required. The data slice range end time in round-trip ISO 8601
/// format.
/// </param>
/// <returns>
/// The List data slices operation response.
/// </returns>
public static DataSliceListResponse List(this IDataSliceOperations operations, string resourceGroupName, string dataFactoryName, string tableName, string dataSliceRangeStartTime, string dataSliceRangeEndTime)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceOperations)s).ListAsync(resourceGroupName, dataFactoryName, tableName, dataSliceRangeStartTime, dataSliceRangeEndTime);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the first page of data slice instances with the link to the
/// next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='dataSliceRangeStartTime'>
/// Required. The data slice range start time in round-trip ISO 8601
/// format.
/// </param>
/// <param name='dataSliceRangeEndTime'>
/// Required. The data slice range end time in round-trip ISO 8601
/// format.
/// </param>
/// <returns>
/// The List data slices operation response.
/// </returns>
public static Task<DataSliceListResponse> ListAsync(this IDataSliceOperations operations, string resourceGroupName, string dataFactoryName, string tableName, string dataSliceRangeStartTime, string dataSliceRangeEndTime)
{
return operations.ListAsync(resourceGroupName, dataFactoryName, tableName, dataSliceRangeStartTime, dataSliceRangeEndTime, CancellationToken.None);
}
/// <summary>
/// Gets the next page of data slice instances with the link to the
/// next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next data slices page.
/// </param>
/// <returns>
/// The List data slices operation response.
/// </returns>
public static DataSliceListResponse ListNext(this IDataSliceOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next page of data slice instances with the link to the
/// next page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The url to the next data slices page.
/// </param>
/// <returns>
/// The List data slices operation response.
/// </returns>
public static Task<DataSliceListResponse> ListNextAsync(this IDataSliceOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Sets status of data slices over a time range for a specific table.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to set status of data slices.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse SetStatus(this IDataSliceOperations operations, string resourceGroupName, string dataFactoryName, string tableName, DataSliceSetStatusParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDataSliceOperations)s).SetStatusAsync(resourceGroupName, dataFactoryName, tableName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Sets status of data slices over a time range for a specific table.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.IDataSliceOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='tableName'>
/// Required. A unique table instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to set status of data slices.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> SetStatusAsync(this IDataSliceOperations operations, string resourceGroupName, string dataFactoryName, string tableName, DataSliceSetStatusParameters parameters)
{
return operations.SetStatusAsync(resourceGroupName, dataFactoryName, tableName, parameters, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class PlayerStatusWorker
{
public bool workerEnabled;
private Queue<PlayerStatus> addStatusQueue = new Queue<PlayerStatus>();
private Queue<string> removeStatusQueue = new Queue<string>();
public PlayerStatus myPlayerStatus;
private PlayerStatus lastPlayerStatus = new PlayerStatus();
public List<PlayerStatus> playerStatusList = new List<PlayerStatus>();
private const float PLAYER_STATUS_CHECK_INTERVAL = .2f;
private const float PLAYER_STATUS_SEND_THROTTLE = 1f;
private float lastPlayerStatusSend;
private float lastPlayerStatusCheck;
//Services
private DMPGame dmpGame;
private VesselWorker vesselWorker;
private LockSystem lockSystem;
private NetworkWorker networkWorker;
private Permissions permissions;
private NamedAction updateAction;
public PlayerStatusWorker(DMPGame dmpGame, Settings dmpSettings, VesselWorker vesselWorker, LockSystem lockSystem, NetworkWorker networkWorker, Permissions permissions)
{
this.dmpGame = dmpGame;
this.vesselWorker = vesselWorker;
this.lockSystem = lockSystem;
this.networkWorker = networkWorker;
this.permissions = permissions;
myPlayerStatus = new PlayerStatus();
myPlayerStatus.playerName = dmpSettings.playerName;
myPlayerStatus.statusText = "Syncing";
updateAction = new NamedAction(Update);
dmpGame.updateEvent.Add(updateAction);
}
private void Update()
{
if (workerEnabled)
{
if ((Client.realtimeSinceStartup - lastPlayerStatusCheck) > PLAYER_STATUS_CHECK_INTERVAL)
{
lastPlayerStatusCheck = Client.realtimeSinceStartup;
myPlayerStatus.vesselText = "";
myPlayerStatus.statusText = "";
if (HighLogic.LoadedSceneIsFlight)
{
//Send vessel+status update
if (FlightGlobals.ActiveVessel != null)
{
if (!vesselWorker.isSpectating)
{
myPlayerStatus.vesselText = FlightGlobals.ActiveVessel.vesselName;
string bodyName = FlightGlobals.ActiveVessel.mainBody.bodyName;
switch (FlightGlobals.ActiveVessel.situation)
{
case (Vessel.Situations.DOCKED):
myPlayerStatus.statusText = "Docked above " + bodyName;
break;
case (Vessel.Situations.ESCAPING):
if (FlightGlobals.ActiveVessel.orbit.timeToPe < 0)
{
myPlayerStatus.statusText = "Escaping " + bodyName;
}
else
{
myPlayerStatus.statusText = "Encountering " + bodyName;
}
break;
case (Vessel.Situations.FLYING):
if (!SafetyBubble.isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody, vesselWorker.safetyBubbleDistance))
{
myPlayerStatus.statusText = "Flying above " + bodyName;
}
else
{
myPlayerStatus.statusText = "Flying in safety bubble";
}
break;
case (Vessel.Situations.LANDED):
if (!SafetyBubble.isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody, vesselWorker.safetyBubbleDistance))
{
myPlayerStatus.statusText = "Landed on " + bodyName;
}
else
{
myPlayerStatus.statusText = "Landed in safety bubble";
}
break;
case (Vessel.Situations.ORBITING):
myPlayerStatus.statusText = "Orbiting " + bodyName;
break;
case (Vessel.Situations.PRELAUNCH):
if (!SafetyBubble.isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody, vesselWorker.safetyBubbleDistance))
{
myPlayerStatus.statusText = "Launching from " + bodyName;
}
else
{
myPlayerStatus.statusText = "Launching from safety bubble";
}
break;
case (Vessel.Situations.SPLASHED):
myPlayerStatus.statusText = "Splashed on " + bodyName;
break;
case (Vessel.Situations.SUB_ORBITAL):
if (FlightGlobals.ActiveVessel.verticalSpeed > 0)
{
myPlayerStatus.statusText = "Ascending from " + bodyName;
}
else
{
myPlayerStatus.statusText = "Descending to " + bodyName;
}
break;
default:
break;
}
}
else
{
if (lockSystem.LockExists("control-" + FlightGlobals.ActiveVessel.id.ToString()))
{
if (lockSystem.LockIsOurs("control-" + FlightGlobals.ActiveVessel.id.ToString()))
{
myPlayerStatus.statusText = "Waiting for vessel control";
}
else
{
myPlayerStatus.statusText = "Spectating " + lockSystem.LockOwner("control-" + FlightGlobals.ActiveVessel.id.ToString());
}
}
else
{
if (permissions.PlayerHasVesselPermission(myPlayerStatus.playerName, FlightGlobals.ActiveVessel.id))
{
myPlayerStatus.statusText = "Spectating future updates";
}
else
{
myPlayerStatus.statusText = "Spectating protected vessel";
}
}
}
}
else
{
myPlayerStatus.statusText = "Loading";
}
}
else
{
//Send status update
switch (HighLogic.LoadedScene)
{
case (GameScenes.EDITOR):
myPlayerStatus.statusText = "Building";
if (EditorDriver.editorFacility == EditorFacility.VAB)
{
myPlayerStatus.statusText = "Building in VAB";
}
if (EditorDriver.editorFacility == EditorFacility.SPH)
{
myPlayerStatus.statusText = "Building in SPH";
}
break;
case (GameScenes.SPACECENTER):
myPlayerStatus.statusText = "At Space Center";
break;
case (GameScenes.TRACKSTATION):
myPlayerStatus.statusText = "At Tracking Station";
break;
case (GameScenes.LOADING):
myPlayerStatus.statusText = "Loading";
break;
default:
break;
}
}
}
bool statusDifferent = false;
statusDifferent = statusDifferent || (myPlayerStatus.vesselText != lastPlayerStatus.vesselText);
statusDifferent = statusDifferent || (myPlayerStatus.statusText != lastPlayerStatus.statusText);
if (statusDifferent && ((Client.realtimeSinceStartup - lastPlayerStatusSend) > PLAYER_STATUS_SEND_THROTTLE))
{
lastPlayerStatusSend = Client.realtimeSinceStartup;
lastPlayerStatus.vesselText = myPlayerStatus.vesselText;
lastPlayerStatus.statusText = myPlayerStatus.statusText;
networkWorker.SendPlayerStatus(myPlayerStatus);
}
while (addStatusQueue.Count > 0)
{
PlayerStatus newStatusEntry = addStatusQueue.Dequeue();
bool found = false;
foreach (PlayerStatus playerStatusEntry in playerStatusList)
{
if (playerStatusEntry.playerName == newStatusEntry.playerName)
{
found = true;
playerStatusEntry.vesselText = newStatusEntry.vesselText;
playerStatusEntry.statusText = newStatusEntry.statusText;
}
}
if (!found)
{
playerStatusList.Add(newStatusEntry);
DarkLog.Debug("Added " + newStatusEntry.playerName + " to status list");
}
}
while (removeStatusQueue.Count > 0)
{
string removeStatusString = removeStatusQueue.Dequeue();
PlayerStatus removeStatus = null;
foreach (PlayerStatus currentStatus in playerStatusList)
{
if (currentStatus.playerName == removeStatusString)
{
removeStatus = currentStatus;
}
}
if (removeStatus != null)
{
playerStatusList.Remove(removeStatus);
DarkLog.Debug("Removed " + removeStatusString + " from status list");
}
else
{
DarkLog.Debug("Cannot remove non-existant player " + removeStatusString);
}
}
}
}
public void AddPlayerStatus(PlayerStatus playerStatus)
{
addStatusQueue.Enqueue(playerStatus);
}
public void RemovePlayerStatus(string playerName)
{
removeStatusQueue.Enqueue(playerName);
}
public int GetPlayerCount()
{
return playerStatusList.Count;
}
public PlayerStatus GetPlayerStatus(string playerName)
{
PlayerStatus returnStatus = null;
foreach (PlayerStatus ps in playerStatusList)
{
if (ps.playerName == playerName)
{
returnStatus = ps;
break;
}
}
return returnStatus;
}
public void Stop()
{
workerEnabled = false;
dmpGame.updateEvent.Remove(updateAction);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Add(System.Object,System.Object):System.Void")]
[assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")]
[assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.set_Item(System.Object,System.Object):System.Void")]
[assembly: SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope = "type", Target = "System.ComponentModel.PropertyDescriptorCollection")]
namespace System.ComponentModel
{
/// <summary>
/// Represents a collection of properties.
/// </summary>
public class PropertyDescriptorCollection : ICollection, IList, IDictionary
{
/// <summary>
/// An empty PropertyDescriptorCollection that can used instead of creating a new one with no items.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields")]
public static readonly PropertyDescriptorCollection Empty = new PropertyDescriptorCollection(null, true);
private IDictionary _cachedFoundProperties;
private bool _cachedIgnoreCase;
private PropertyDescriptor[] _properties;
private readonly string[] _namedSort;
private readonly IComparer _comparer;
private bool _propsOwned;
private bool _needSort;
private readonly bool _readOnly;
private readonly object _internalSyncObject = new object();
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.PropertyDescriptorCollection'/>
/// class.
/// </summary>
public PropertyDescriptorCollection(PropertyDescriptor[] properties)
{
if (properties == null)
{
_properties = Array.Empty<PropertyDescriptor>();
Count = 0;
}
else
{
_properties = properties;
Count = properties.Length;
}
_propsOwned = true;
}
/// <summary>
/// Initializes a new instance of a property descriptor collection, and allows you to mark the
/// collection as read-only so it cannot be modified.
/// </summary>
public PropertyDescriptorCollection(PropertyDescriptor[] properties, bool readOnly) : this(properties)
{
_readOnly = readOnly;
}
private PropertyDescriptorCollection(PropertyDescriptor[] properties, int propCount, string[] namedSort, IComparer comparer)
{
_propsOwned = false;
if (namedSort != null)
{
_namedSort = (string[])namedSort.Clone();
}
_comparer = comparer;
_properties = properties;
Count = propCount;
_needSort = true;
}
/// <summary>
/// Gets the number of property descriptors in the collection.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Gets the property with the specified index number.
/// </summary>
public virtual PropertyDescriptor this[int index]
{
get
{
if (index >= Count)
{
throw new IndexOutOfRangeException();
}
EnsurePropsOwned();
return _properties[index];
}
}
/// <summary>
/// Gets the property with the specified name.
/// </summary>
public virtual PropertyDescriptor this[string name] => Find(name, false);
public int Add(PropertyDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
EnsureSize(Count + 1);
_properties[Count++] = value;
return Count - 1;
}
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException();
}
Count = 0;
_cachedFoundProperties = null;
}
public bool Contains(PropertyDescriptor value) => IndexOf(value) >= 0;
public void CopyTo(Array array, int index)
{
EnsurePropsOwned();
Array.Copy(_properties, 0, array, index, Count);
}
private void EnsurePropsOwned()
{
if (!_propsOwned)
{
_propsOwned = true;
if (_properties != null)
{
PropertyDescriptor[] newProps = new PropertyDescriptor[Count];
Array.Copy(_properties, 0, newProps, 0, Count);
_properties = newProps;
}
}
if (_needSort)
{
_needSort = false;
InternalSort(_namedSort);
}
}
private void EnsureSize(int sizeNeeded)
{
if (sizeNeeded <= _properties.Length)
{
return;
}
if (_properties.Length == 0)
{
Count = 0;
_properties = new PropertyDescriptor[sizeNeeded];
return;
}
EnsurePropsOwned();
int newSize = Math.Max(sizeNeeded, _properties.Length * 2);
PropertyDescriptor[] newProps = new PropertyDescriptor[newSize];
Array.Copy(_properties, 0, newProps, 0, Count);
_properties = newProps;
}
/// <summary>
/// Gets the description of the property with the specified name.
/// </summary>
public virtual PropertyDescriptor Find(string name, bool ignoreCase)
{
lock (_internalSyncObject)
{
PropertyDescriptor p = null;
if (_cachedFoundProperties == null || _cachedIgnoreCase != ignoreCase)
{
_cachedIgnoreCase = ignoreCase;
if (ignoreCase)
{
_cachedFoundProperties = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
else
{
_cachedFoundProperties = new Hashtable();
}
}
// first try to find it in the cache
//
object cached = _cachedFoundProperties[name];
if (cached != null)
{
return (PropertyDescriptor)cached;
}
// Now start walking from where we last left off, filling
// the cache as we go.
//
for (int i = 0; i < Count; i++)
{
if (ignoreCase)
{
if (string.Equals(_properties[i].Name, name, StringComparison.OrdinalIgnoreCase))
{
_cachedFoundProperties[name] = _properties[i];
p = _properties[i];
break;
}
}
else
{
if (_properties[i].Name.Equals(name))
{
_cachedFoundProperties[name] = _properties[i];
p = _properties[i];
break;
}
}
}
return p;
}
}
public int IndexOf(PropertyDescriptor value) => Array.IndexOf(_properties, value, 0, Count);
public void Insert(int index, PropertyDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
EnsureSize(Count + 1);
if (index < Count)
{
Array.Copy(_properties, index, _properties, index + 1, Count - index);
}
_properties[index] = value;
Count++;
}
public void Remove(PropertyDescriptor value)
{
if (_readOnly)
{
throw new NotSupportedException();
}
int index = IndexOf(value);
if (index != -1)
{
RemoveAt(index);
}
}
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (index < Count - 1)
{
Array.Copy(_properties, index + 1, _properties, index, Count - index - 1);
}
_properties[Count - 1] = null;
Count--;
}
/// <summary>
/// Sorts the members of this PropertyDescriptorCollection, using the default sort for this collection,
/// which is usually alphabetical.
/// </summary>
public virtual PropertyDescriptorCollection Sort()
{
return new PropertyDescriptorCollection(_properties, Count, _namedSort, _comparer);
}
/// <summary>
/// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </summary>
public virtual PropertyDescriptorCollection Sort(string[] names)
{
return new PropertyDescriptorCollection(_properties, Count, names, _comparer);
}
/// <summary>
/// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </summary>
public virtual PropertyDescriptorCollection Sort(string[] names, IComparer comparer)
{
return new PropertyDescriptorCollection(_properties, Count, names, comparer);
}
/// <summary>
/// Sorts the members of this PropertyDescriptorCollection, using the specified IComparer to compare,
/// the PropertyDescriptors contained in the collection.
/// </summary>
public virtual PropertyDescriptorCollection Sort(IComparer comparer)
{
return new PropertyDescriptorCollection(_properties, Count, _namedSort, comparer);
}
/// <summary>
/// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will
/// be applied first, followed by sort using the specified IComparer.
/// </summary>
protected void InternalSort(string[] names)
{
if (_properties.Length == 0)
{
return;
}
InternalSort(_comparer);
if (names != null && names.Length > 0)
{
List<PropertyDescriptor> propList = new List<PropertyDescriptor>(_properties);
int foundCount = 0;
int propCount = _properties.Length;
for (int i = 0; i < names.Length; i++)
{
for (int j = 0; j < propCount; j++)
{
PropertyDescriptor currentProp = propList[j];
// Found a matching property. Here, we add it to our array. We also
// mark it as null in our array list so we don't add it twice later.
//
if (currentProp != null && currentProp.Name.Equals(names[i]))
{
_properties[foundCount++] = currentProp;
propList[j] = null;
break;
}
}
}
// At this point we have filled in the first "foundCount" number of propeties, one for each
// name in our name array. If a name didn't match, then it is ignored. Next, we must fill
// in the rest of the properties. We now have a sparse array containing the remainder, so
// it's easy.
//
for (int i = 0; i < propCount; i++)
{
if (propList[i] != null)
{
_properties[foundCount++] = propList[i];
}
}
Debug.Assert(foundCount == propCount, "We did not completely fill our property array");
}
}
/// <summary>
/// Sorts the members of this PropertyDescriptorCollection using the specified IComparer.
/// </summary>
protected void InternalSort(IComparer sorter)
{
if (sorter == null)
{
TypeDescriptor.SortDescriptorArray(this);
}
else
{
Array.Sort(_properties, sorter);
}
}
/// <summary>
/// Gets an enumerator for this <see cref='System.ComponentModel.PropertyDescriptorCollection'/>.
/// </summary>
public virtual IEnumerator GetEnumerator()
{
EnsurePropsOwned();
// we can only return an enumerator on the props we actually have...
if (_properties.Length != Count)
{
PropertyDescriptor[] enumProps = new PropertyDescriptor[Count];
Array.Copy(_properties, 0, enumProps, 0, Count);
return enumProps.GetEnumerator();
}
return _properties.GetEnumerator();
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => null;
int ICollection.Count => Count;
void IList.Clear() => Clear();
void IDictionary.Clear() => Clear();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
void IList.RemoveAt(int index) => RemoveAt(index);
void IDictionary.Add(object key, object value)
{
if (!(value is PropertyDescriptor newProp))
{
throw new ArgumentException(nameof(value));
}
Add(newProp);
}
bool IDictionary.Contains(object key)
{
if (key is string)
{
return this[(string)key] != null;
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator() => new PropertyDescriptorEnumerator(this);
bool IDictionary.IsFixedSize => _readOnly;
bool IDictionary.IsReadOnly => _readOnly;
object IDictionary.this[object key]
{
get
{
if (key is string)
{
return this[(string)key];
}
return null;
}
set
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (value != null && !(value is PropertyDescriptor))
{
throw new ArgumentException(nameof(value));
}
int index = -1;
if (key is int)
{
index = (int)key;
if (index < 0 || index >= Count)
{
throw new IndexOutOfRangeException();
}
}
else if (key is string)
{
for (int i = 0; i < Count; i++)
{
if (_properties[i].Name.Equals((string)key))
{
index = i;
break;
}
}
}
else
{
throw new ArgumentException(nameof(key));
}
if (index == -1)
{
Add((PropertyDescriptor)value);
}
else
{
EnsurePropsOwned();
_properties[index] = (PropertyDescriptor)value;
if (_cachedFoundProperties != null && key is string)
{
_cachedFoundProperties[key] = value;
}
}
}
}
ICollection IDictionary.Keys
{
get
{
string[] keys = new string[Count];
for (int i = 0; i < Count; i++)
{
keys[i] = _properties[i].Name;
}
return keys;
}
}
ICollection IDictionary.Values
{
get
{
// We can only return an enumerator on the props we actually have.
if (_properties.Length != Count)
{
PropertyDescriptor[] newProps = new PropertyDescriptor[Count];
Array.Copy(_properties, 0, newProps, 0, Count);
return newProps;
}
else
{
return (ICollection)_properties.Clone();
}
}
}
void IDictionary.Remove(object key)
{
if (key is string)
{
PropertyDescriptor pd = this[(string)key];
if (pd != null)
{
((IList)this).Remove(pd);
}
}
}
int IList.Add(object value) => Add((PropertyDescriptor)value);
bool IList.Contains(object value) => Contains((PropertyDescriptor)value);
int IList.IndexOf(object value) => IndexOf((PropertyDescriptor)value);
void IList.Insert(int index, object value) => Insert(index, (PropertyDescriptor)value);
bool IList.IsReadOnly => _readOnly;
bool IList.IsFixedSize => _readOnly;
void IList.Remove(object value) => Remove((PropertyDescriptor)value);
object IList.this[int index]
{
get => this[index];
set
{
if (_readOnly)
{
throw new NotSupportedException();
}
if (index >= Count)
{
throw new IndexOutOfRangeException();
}
if (value != null && !(value is PropertyDescriptor))
{
throw new ArgumentException(nameof(value));
}
EnsurePropsOwned();
_properties[index] = (PropertyDescriptor)value;
}
}
private class PropertyDescriptorEnumerator : IDictionaryEnumerator
{
private readonly PropertyDescriptorCollection _owner;
private int _index = -1;
public PropertyDescriptorEnumerator(PropertyDescriptorCollection owner)
{
_owner = owner;
}
public object Current => Entry;
public DictionaryEntry Entry
{
get
{
PropertyDescriptor curProp = _owner[_index];
return new DictionaryEntry(curProp.Name, curProp);
}
}
public object Key => _owner[_index].Name;
public object Value => _owner[_index].Name;
public bool MoveNext()
{
if (_index < (_owner.Count - 1))
{
_index++;
return true;
}
return false;
}
public void Reset() => _index = -1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static partial class ParallelQueryCombinationTests
{
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Cast_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int? i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Cast<int?>())
{
Assert.True(i.HasValue);
seen.Add(i.Value);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Cast_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Cast<int?>().ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Concat_Unordered(Labeled<Operation> operation)
{
static void Concat(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int i in left(DefaultStart, DefaultSize / 2, DefaultSource)
.Concat(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, DefaultSource)))
{
seen.Add(i);
}
seen.AssertComplete();
}
Concat(operation.Item, DefaultSource);
Concat(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Concat_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void Concat(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(
left(DefaultStart, DefaultSize / 2, DefaultSource)
.Concat(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, DefaultSource)).ToList(),
x => seen.Add(x));
seen.AssertComplete();
}
Concat(operation.Item, DefaultSource);
Concat(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void DefaultIfEmpty_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).DefaultIfEmpty())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void DefaultIfEmpty_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).DefaultIfEmpty().ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Distinct_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, DefaultSource).Select(x => x / 2).Distinct();
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Distinct_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, DefaultSource).Select(x => x / 2).Distinct();
Assert.All(query.ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Except_Unordered(Labeled<Operation> operation)
{
static void Except(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource)
.Except(right(DefaultStart + DefaultSize, DefaultSize, DefaultSource));
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
Except(operation.Item, DefaultSource);
Except(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Except_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void Except(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource)
.Except(right(DefaultStart + DefaultSize, DefaultSize, DefaultSource));
Assert.All(query.ToList(), x => seen.Add((int)x));
seen.AssertComplete();
}
Except(operation.Item, DefaultSource);
Except(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GetEnumerator_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, DefaultSource).GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
seen.Add(current);
Assert.Equal(current, enumerator.Current);
}
seen.AssertComplete();
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor))
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor).ToList())
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_ElementSelector_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor, y => -y))
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupBy_ElementSelector_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, (DefaultSize + (GroupFactor - 1)) / GroupFactor);
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, DefaultSource).GroupBy(x => x / GroupFactor, y => -y).ToList())
{
seenKey.Add(group.Key);
IntegerRangeSet seenElement = new IntegerRangeSet(1 - Math.Min(DefaultStart + DefaultSize, (group.Key + 1) * GroupFactor), Math.Min(GroupFactor, DefaultSize - (group.Key - 1) * GroupFactor));
Assert.All(group, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupJoin_Unordered(Labeled<Operation> operation)
{
static void GroupJoin(Operation left, Operation right)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, DefaultSize / GroupFactor);
foreach (KeyValuePair<int, IEnumerable<int>> group in left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.GroupJoin(right(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g)))
{
Assert.True(seenKey.Add(group.Key));
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, GroupFactor);
Assert.All(group.Value, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
GroupJoin(operation.Item, DefaultSource);
GroupJoin(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void GroupJoin_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void GroupJoin(Operation left, Operation right)
{
IntegerRangeSet seenKey = new IntegerRangeSet(DefaultStart / GroupFactor, DefaultSize / GroupFactor);
foreach (KeyValuePair<int, IEnumerable<int>> group in left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.GroupJoin(right(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g)).ToList())
{
Assert.True(seenKey.Add(group.Key));
IntegerRangeSet seenElement = new IntegerRangeSet(group.Key * GroupFactor, GroupFactor);
Assert.All(group.Value, x => seenElement.Add(x));
seenElement.AssertComplete();
}
seenKey.AssertComplete();
}
GroupJoin(operation.Item, DefaultSource);
GroupJoin(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Intersect_Unordered(Labeled<Operation> operation)
{
static void Intersect(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, DefaultSource)
.Intersect(right(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource));
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
Intersect(operation.Item, DefaultSource);
Intersect(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Intersect_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void Intersect(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, DefaultSource)
.Intersect(right(DefaultStart, DefaultSize + DefaultSize / 2, DefaultSource));
Assert.All(query.ToList(), x => seen.Add(x));
seen.AssertComplete();
}
Intersect(operation.Item, DefaultSource);
Intersect(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Join_Unordered(Labeled<Operation> operation)
{
static void Join(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<KeyValuePair<int, int>> query = left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.Join(right(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y));
foreach (KeyValuePair<int, int> p in query)
{
Assert.Equal(p.Key, p.Value / GroupFactor);
seen.Add(p.Value);
}
seen.AssertComplete();
}
Join(operation.Item, DefaultSource);
Join(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Join_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void Join(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<KeyValuePair<int, int>> query = left(DefaultStart / GroupFactor, DefaultSize / GroupFactor, DefaultSource)
.Join(right(DefaultStart, DefaultSize, DefaultSource), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y));
foreach (KeyValuePair<int, int> p in query.ToList())
{
Assert.Equal(p.Key, p.Value / GroupFactor);
seen.Add(p.Value);
}
seen.AssertComplete();
}
Join(operation.Item, DefaultSource);
Join(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void OfType_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void OfType_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Select(x => -x))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Select(x => -x).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Index_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Select((x, index) => { indices.Add(index); return -x; }))
{
seen.Add(i);
}
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Select_Index_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize + 1, DefaultSize);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Select((x, index) => { indices.Add(index); return -x; }).ToList(), x => seen.Add(x));
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }))
{
seen.Add(i);
}
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => seen.Add(x));
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_ResultSelector_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_ResultSelector_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_ResultSelector_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
foreach (int i in operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x))
{
seen.Add(i);
}
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void SelectMany_Indexed_ResultSelector_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(-DefaultStart - DefaultSize * 2 + 1, DefaultSize * 2);
IntegerRangeSet indices = new IntegerRangeSet(0, DefaultSize);
Assert.All(operation.Item(0, DefaultSize, DefaultSource).SelectMany((x, index) => { indices.Add(index); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => seen.Add(x));
seen.AssertComplete();
indices.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Skip_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Skip(DefaultSize / 2))
{
seen.Add(i);
count++;
}
Assert.Equal((DefaultSize - 1) / 2 + 1, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Skip_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Skip(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; });
Assert.Equal((DefaultSize - 1) / 2 + 1, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Take_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Take(DefaultSize / 2))
{
seen.Add(i);
count++;
}
Assert.Equal(DefaultSize / 2, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Take_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
int count = 0;
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Take(DefaultSize / 2).ToList(), x => { seen.Add(x); count++; });
Assert.Equal(DefaultSize / 2, count);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
//[MemberData(nameof(BinaryOperations))]
public static void ToArray_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).ToArray(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Union_Unordered(Labeled<Operation> operation)
{
static void Union(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart, DefaultSize * 3 / 4, DefaultSource)
.Union(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, DefaultSource));
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
Union(operation.Item, DefaultSource);
Union(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Union_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void Union(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart, DefaultSize * 3 / 4, DefaultSource)
.Union(right(DefaultStart + DefaultSize / 2, DefaultSize / 2, DefaultSource));
Assert.All(query.ToList(), x => seen.Add(x));
seen.AssertComplete();
}
Union(operation.Item, DefaultSource);
Union(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Where(x => x < DefaultStart + DefaultSize / 2))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Indexed_Unordered(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
foreach (int i in operation.Item(DefaultStart, DefaultSize, DefaultSource).Where((x, index) => x < DefaultStart + DefaultSize / 2))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Where_Indexed_Unordered_NotPipelined(Labeled<Operation> operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize / 2);
Assert.All(operation.Item(DefaultStart, DefaultSize, DefaultSource).Where((x, index) => x < DefaultStart + DefaultSize / 2).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Zip_Unordered(Labeled<Operation> operation)
{
static void Zip(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart, DefaultSize, DefaultSource)
.Zip(right(0, DefaultSize, DefaultSource), (x, y) => x);
foreach (int i in query)
{
seen.Add(i);
}
seen.AssertComplete();
}
Zip(operation.Item, DefaultSource);
Zip(DefaultSource, operation.Item);
}
[Theory]
[MemberData(nameof(UnaryOperations))]
[MemberData(nameof(BinaryOperations))]
public static void Zip_Unordered_NotPipelined(Labeled<Operation> operation)
{
static void Zip(Operation left, Operation right)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
ParallelQuery<int> query = left(DefaultStart, DefaultSize, DefaultSource)
.Zip(right(0, DefaultSize, DefaultSource), (x, y) => x);
Assert.All(query.ToList(), x => seen.Add(x));
seen.AssertComplete();
}
Zip(operation.Item, DefaultSource);
Zip(DefaultSource, operation.Item);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Lucene.Net.Index;
using Lucene.Net.Store;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
[TestFixture]
public class TestElevationComparator:LuceneTestCase
{
private System.Collections.IDictionary priority = new System.Collections.Hashtable();
//@Test
[Test]
public virtual void TestSorting()
{
Directory directory = new MockRAMDirectory();
IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetMaxBufferedDocs(2);
writer.SetMergeFactor(1000);
writer.AddDocument(Adoc(new System.String[]{"id", "a", "title", "ipod", "str_s", "a"}));
writer.AddDocument(Adoc(new System.String[]{"id", "b", "title", "ipod ipod", "str_s", "b"}));
writer.AddDocument(Adoc(new System.String[]{"id", "c", "title", "ipod ipod ipod", "str_s", "c"}));
writer.AddDocument(Adoc(new System.String[]{"id", "x", "title", "boosted", "str_s", "x"}));
writer.AddDocument(Adoc(new System.String[]{"id", "y", "title", "boosted boosted", "str_s", "y"}));
writer.AddDocument(Adoc(new System.String[]{"id", "z", "title", "boosted boosted boosted", "str_s", "z"}));
IndexReader r = writer.GetReader();
writer.Close();
IndexSearcher searcher = new IndexSearcher(r);
RunTest(searcher, true);
RunTest(searcher, false);
searcher.Close();
r.Close();
directory.Close();
}
private void RunTest(IndexSearcher searcher, bool reversed)
{
BooleanQuery newq = new BooleanQuery(false);
TermQuery query = new TermQuery(new Term("title", "ipod"));
newq.Add(query, BooleanClause.Occur.SHOULD);
newq.Add(GetElevatedQuery(new System.String[]{"id", "a", "id", "x"}), BooleanClause.Occur.SHOULD);
Sort sort = new Sort(new SortField[]{new SortField("id", new ElevationComparatorSource(priority), false), new SortField(null, SortField.SCORE, reversed)});
TopDocsCollector topCollector = TopFieldCollector.create(sort, 50, false, true, true, true);
searcher.Search(newq, null, topCollector);
TopDocs topDocs = topCollector.TopDocs(0, 10);
int nDocsReturned = topDocs.ScoreDocs.Length;
Assert.AreEqual(4, nDocsReturned);
// 0 & 3 were elevated
Assert.AreEqual(0, topDocs.ScoreDocs[0].doc);
Assert.AreEqual(3, topDocs.ScoreDocs[1].doc);
if (reversed)
{
Assert.AreEqual(2, topDocs.ScoreDocs[2].doc);
Assert.AreEqual(1, topDocs.ScoreDocs[3].doc);
}
else
{
Assert.AreEqual(1, topDocs.ScoreDocs[2].doc);
Assert.AreEqual(2, topDocs.ScoreDocs[3].doc);
}
/*
for (int i = 0; i < nDocsReturned; i++) {
ScoreDoc scoreDoc = topDocs.scoreDocs[i];
ids[i] = scoreDoc.doc;
scores[i] = scoreDoc.score;
documents[i] = searcher.doc(ids[i]);
System.out.println("ids[i] = " + ids[i]);
System.out.println("documents[i] = " + documents[i]);
System.out.println("scores[i] = " + scores[i]);
}
*/
}
private Query GetElevatedQuery(System.String[] vals)
{
BooleanQuery q = new BooleanQuery(false);
q.SetBoost(0);
int max = (vals.Length / 2) + 5;
for (int i = 0; i < vals.Length - 1; i += 2)
{
q.Add(new TermQuery(new Term(vals[i], vals[i + 1])), BooleanClause.Occur.SHOULD);
priority[vals[i + 1]] = (System.Int32) max--;
// System.out.println(" pri doc=" + vals[i+1] + " pri=" + (1+max));
}
return q;
}
private Document Adoc(System.String[] vals)
{
Document doc = new Document();
for (int i = 0; i < vals.Length - 2; i += 2)
{
doc.Add(new Field(vals[i], vals[i + 1], Field.Store.YES, Field.Index.ANALYZED));
}
return doc;
}
}
[Serializable]
class ElevationComparatorSource:FieldComparatorSource
{
private class AnonymousClassFieldComparator:FieldComparator
{
public AnonymousClassFieldComparator(int numHits, System.String fieldname, ElevationComparatorSource enclosingInstance)
{
InitBlock(numHits, fieldname, enclosingInstance);
}
private void InitBlock(int numHits, System.String fieldname, ElevationComparatorSource enclosingInstance)
{
this.numHits = numHits;
this.fieldname = fieldname;
this.enclosingInstance = enclosingInstance;
values = new int[numHits];
}
private int numHits;
private System.String fieldname;
private ElevationComparatorSource enclosingInstance;
public ElevationComparatorSource Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal Lucene.Net.Search.StringIndex idIndex;
private int[] values;
internal int bottomVal;
public override int Compare(int slot1, int slot2)
{
return values[slot2] - values[slot1]; // values will be small enough that there is no overflow concern
}
public override void SetBottom(int slot)
{
bottomVal = values[slot];
}
private int DocVal(int doc)
{
System.String id = idIndex.lookup[idIndex.order[doc]];
object prio = Enclosing_Instance.priority[id];
return prio == null ? 0 : (int)prio;
}
public override int CompareBottom(int doc)
{
return DocVal(doc) - bottomVal;
}
public override void Copy(int slot, int doc)
{
values[slot] = DocVal(doc);
}
public override void SetNextReader(IndexReader reader, int docBase)
{
idIndex = Lucene.Net.Search.FieldCache_Fields.DEFAULT.GetStringIndex(reader, fieldname);
}
public override System.IComparable Value(int slot)
{
return (System.Int32) values[slot];
}
}
private System.Collections.IDictionary priority;
public ElevationComparatorSource(System.Collections.IDictionary boosts)
{
this.priority = boosts;
}
public override FieldComparator NewComparator(System.String fieldname, int numHits, int sortPos, bool reversed)
{
return new AnonymousClassFieldComparator(numHits, fieldname, this);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Site.Configuration;
namespace Rainbow.Framework.Site.Data
{
/// <summary>
/// Summary description for recycler.
/// </summary>
public class RecyclerDB
{
private const string strNoModule = "NO_MODULE";
/// <summary>
/// MoveModuleToNewTab assigns the given module to the given tab
/// </summary>
/// <param name="TabID">The tab ID.</param>
/// <param name="ModuleID">The module ID.</param>
public static void MoveModuleToNewTab(int TabID, int ModuleID)
{
// Create Instance of Connection and Command Object
using (SqlConnection MyConnection = Config.SqlConnectionString)
{
using (SqlCommand MyCommand = new SqlCommand("rb_MoveModuleToNewTab", MyConnection))
{
// Mark the Command as a SPROC
MyCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter ParameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
ParameterModuleID.Value = ModuleID;
MyCommand.Parameters.Add(ParameterModuleID);
SqlParameter ParameterTabID = new SqlParameter("@TabID", SqlDbType.Int, 4);
ParameterTabID.Value = TabID;
MyCommand.Parameters.Add(ParameterTabID);
MyConnection.Open();
try
{
MyCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
ErrorHandler.Publish(LogLevel.Warn,
"An Error Occurred in MoveModuleToNewTab. Parameter : " +
ModuleID.ToString(), ex);
}
}
}
}
/// <summary>
/// The GetModulesInRecycler method returns a SqlDataReader containing all of the
/// Modules for a specific portal module that have been 'deleted' to the recycler.
/// <a href="GetModulesInRecycler.htm" style="color:green">GetModulesInRecycler Stored Procedure</a>
/// </summary>
/// <param name="PortalID">The portal ID.</param>
/// <param name="SortField">The sort field.</param>
/// <returns>SqlDataReader</returns>
public static DataTable GetModulesInRecycler(int PortalID, string SortField)
{
// Create Instance of Connection and Command Object
using (SqlConnection MyConnection = Config.SqlConnectionString)
{
using (SqlDataAdapter MyCommand = new SqlDataAdapter("rb_GetModulesInRecycler", MyConnection))
{
// Mark the Command as a SPROC
MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter ParameterModuleID = new SqlParameter("@PortalID", SqlDbType.Int, 4);
ParameterModuleID.Value = PortalID;
MyCommand.SelectCommand.Parameters.Add(ParameterModuleID);
SqlParameter ParameterSortField = new SqlParameter("@SortField", SqlDbType.VarChar, 50);
ParameterSortField.Value = SortField;
MyCommand.SelectCommand.Parameters.Add(ParameterSortField);
// Create and Fill the DataSet
using (DataTable myDataTable = new DataTable())
{
try
{
MyCommand.Fill(myDataTable);
}
finally
{
MyConnection.Close(); //by Manu fix close bug #2
}
// Translate
foreach (DataRow dr in myDataTable.Rows)
{
if (dr[1].ToString() == strNoModule)
{
dr[1] = General.GetString(strNoModule);
break;
}
}
// Return the datareader
return myDataTable;
}
}
}
}
/// <summary>
/// Modules the is in recycler.
/// </summary>
/// <param name="ModuleID">The module ID.</param>
/// <returns></returns>
public static bool ModuleIsInRecycler(int ModuleID)
{
ModuleSettings ms = GetModuleSettingsForIndividualModule(ModuleID);
if (ms.PageID == 0)
return true;
else
return false;
}
/// <summary>
/// MOST OF THIS METHOD'S CODE IS COPIED DIRECTLY FROM THE PortalSettings() CLASS
/// THE RECYCLER NEEDS TO BE ABLE TO RETRIEVE A MODULE'S ModuleSettings INDEPENDENT
/// OF THE TAB THE MODULE IS LOCATED ON (AND INDEPENDENT OF THE CURRENT 'ActiveTab'
/// </summary>
/// <param name="ModuleID">The module ID.</param>
/// <returns></returns>
public static ModuleSettings GetModuleSettingsForIndividualModule(int ModuleID)
{
// Create Instance of Connection and Command Object
using (SqlConnection MyConnection = Config.SqlConnectionString)
{
using (SqlCommand MyCommand = new SqlCommand("rb_GetModuleSettingsForIndividualModule", MyConnection))
{
// Mark the Command as a SPROC
MyCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter ParameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
ParameterModuleID.Value = ModuleID;
MyCommand.Parameters.Add(ParameterModuleID);
// Open the database connection and execute the command
MyConnection.Open();
SqlDataReader result;
object myValue;
result = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
ModuleSettings m = new ModuleSettings();
// Read the resultset -- There is only one row!
while (result.Read())
{
m.ModuleID = (int) result["ModuleID"];
m.ModuleDefID = (int) result["ModuleDefID"];
m.PageID = (int) result["TabID"];
m.PaneName = (string) result["PaneName"];
m.ModuleTitle = (string) result["ModuleTitle"];
myValue = result["AuthorizedEditRoles"];
m.AuthorizedEditRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["AuthorizedViewRoles"];
m.AuthorizedViewRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["AuthorizedAddRoles"];
m.AuthorizedAddRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["AuthorizedDeleteRoles"];
m.AuthorizedDeleteRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["AuthorizedPropertiesRoles"];
m.AuthorizedPropertiesRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
// [email protected] (19/08/2004) Add support for move & delete module roles
myValue = result["AuthorizedMoveModuleRoles"];
m.AuthorizedMoveModuleRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["AuthorizedDeleteModuleRoles"];
m.AuthorizedDeleteModuleRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
// Change by [email protected]
// Date: 6/2/2003
myValue = result["AuthorizedPublishingRoles"];
m.AuthorizedPublishingRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["SupportWorkflow"];
m.SupportWorkflow = !Convert.IsDBNull(myValue) ? (bool) myValue : false;
// Date: 27/2/2003
myValue = result["AuthorizedApproveRoles"];
m.AuthorizedApproveRoles = !Convert.IsDBNull(myValue) ? (string) myValue : "";
myValue = result["WorkflowState"];
m.WorkflowStatus = !Convert.IsDBNull(myValue)
? (WorkflowState) (0 + (byte) myValue)
: WorkflowState.Original;
// End Change [email protected]
// Start Change [email protected]
try
{
myValue = result["SupportCollapsable"];
}
catch
{
myValue = DBNull.Value;
}
m.SupportCollapsable = DBNull.Value != myValue ? (bool) myValue : false;
// End Change [email protected]
// Start Change [email protected]
try
{
myValue = result["ShowEveryWhere"];
}
catch
{
myValue = DBNull.Value;
}
m.ShowEveryWhere = DBNull.Value != myValue ? (bool) myValue : false;
// End Change [email protected]
m.CacheTime = int.Parse(result["CacheTime"].ToString());
m.ModuleOrder = int.Parse(result["ModuleOrder"].ToString());
myValue = result["ShowMobile"];
m.ShowMobile = !Convert.IsDBNull(myValue) ? (bool) myValue : false;
m.DesktopSrc = result["DesktopSrc"].ToString();
m.MobileSrc = result["MobileSrc"].ToString();
m.Admin = bool.Parse(result["Admin"].ToString());
}
return m;
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripMenuItem.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using Microsoft.Win32;
using System.Drawing.Imaging;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Forms.Layout;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Windows.Forms.Design;
using System.Globalization;
using System.Windows.Forms.Internal;
using System.Runtime.Versioning;
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem"]/*' />
/// <devdoc>
/// ToolStripMenuItem
/// </devdoc>
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.MenuStrip | ToolStripItemDesignerAvailability.ContextMenuStrip)]
[DesignerSerializer("System.Windows.Forms.Design.ToolStripMenuItemCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)]
public class ToolStripMenuItem : ToolStripDropDownItem {
private static MenuTimer menuTimer = new MenuTimer();
private static readonly int PropShortcutKeys = PropertyStore.CreateKey();
private static readonly int PropCheckState = PropertyStore.CreateKey();
private static readonly int PropMdiForm = PropertyStore.CreateKey();
private bool checkOnClick = false;
private bool showShortcutKeys = true;
private ToolStrip lastOwner = null;
// SUPPORT for mapping NATIVE menu commands to ToolStripMenuItems -----
// corresponds to wID in MENUITEMINFO structure
private int nativeMenuCommandID = -1;
private IntPtr targetWindowHandle = IntPtr.Zero;
private IntPtr nativeMenuHandle = IntPtr.Zero;
// Keep checked images shared between menu items, but per thread so we dont have locking issues in GDI+
[ThreadStatic]
private static Image indeterminateCheckedImage;
[ThreadStatic]
private static Image checkedImage;
private string shortcutKeyDisplayString;
private string cachedShortcutText;
private Size cachedShortcutSize = Size.Empty;
private byte openMouseId = 0;
private static readonly object EventCheckedChanged = new object();
private static readonly object EventCheckStateChanged = new object();
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.ToolStripMenuItem"]/*' />
public ToolStripMenuItem() : base() {
Initialize(); // all additional work should be done in Initialize
}
public ToolStripMenuItem(string text):base(text,null,(EventHandler)null) {
Initialize();
}
public ToolStripMenuItem(Image image):base(null,image,(EventHandler)null) {
Initialize();
}
public ToolStripMenuItem(string text, Image image):base(text,image,(EventHandler)null) {
Initialize();
}
public ToolStripMenuItem(string text, Image image, EventHandler onClick):base(text,image,onClick) {
Initialize();
}
public ToolStripMenuItem(string text, Image image, EventHandler onClick, string name) : base(text,image,onClick, name){
Initialize();
}
public ToolStripMenuItem(string text, Image image, params ToolStripItem[] dropDownItems):base(text,image,dropDownItems) {
Initialize();
}
public ToolStripMenuItem(string text, Image image, EventHandler onClick, Keys shortcutKeys):base(text,image,onClick) {
Initialize();
this.ShortcutKeys = shortcutKeys;
}
internal ToolStripMenuItem(Form mdiForm) {
Initialize();
Properties.SetObject(PropMdiForm,mdiForm);
}
/// <devdoc> this constructor is only used when we're trying to
/// mimic a native menu like the system menu. In that case
/// we've got to go ahead and collect the command id and the
/// target window to send WM_COMMAND/WM_SYSCOMMAND messages to.
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
internal ToolStripMenuItem(IntPtr hMenu, int nativeMenuCommandId, IWin32Window targetWindow) {
Initialize();
this.Overflow = ToolStripItemOverflow.Never;
this.nativeMenuCommandID = nativeMenuCommandId;
this.targetWindowHandle = Control.GetSafeHandle(targetWindow);
this.nativeMenuHandle = hMenu;
// Since fetching the image and the text is an awful lot of work
// we're going to just cache it and assume the native stuff
// doesnt update.
// we'll only live-update enabled.
// if this becomes a problem we can override Image and Text properties
// to live-return the results.
// fetch image
this.Image = GetNativeMenuItemImage();
this.ImageScaling = ToolStripItemImageScaling.None;
// fetch text
string text = GetNativeMenuItemTextAndShortcut();
// the shortcut is tab separated from the item text.
if (text != null) {
// separate out the two fields.
string[] textFields = text.Split('\t');
if (textFields.Length >= 1){
this.Text = textFields[0];
}
if (textFields.Length >= 2) {
// VSWhidbey 448242: We dont care about the shortcut here, the OS is going to
// handle it for us by sending a WM_(SYS)COMMAND during TranslateAcellerator
// Just display whatever the OS would have.
this.ShowShortcutKeys = true;
this.ShortcutKeyDisplayString = textFields[1];
}
}
}
internal override void AutoHide(ToolStripItem otherItemBeingSelected) {
if (IsOnDropDown) {
MenuTimer.Transition(this,otherItemBeingSelected as ToolStripMenuItem);
}
else {
base.AutoHide(otherItemBeingSelected);
}
}
private void ClearShortcutCache() {
cachedShortcutSize = Size.Empty;
cachedShortcutText = null;
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.CreateDefaultDropDown"]/*' />
protected override ToolStripDropDown CreateDefaultDropDown() {
// AutoGenerate a Winbar DropDown - set the property so we hook events
return new ToolStripDropDownMenu(this, true);
}
internal override ToolStripItemInternalLayout CreateInternalLayout() {
return new ToolStripMenuItemInternalLayout(this);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override AccessibleObject CreateAccessibilityInstance() {
return new ToolStripMenuItemAccessibleObject(this);
}
private void Initialize() {
this.Overflow = ToolStripItemOverflow.Never;
this.MouseDownAndUpMustBeInSameItem = false;
this.SupportsDisabledHotTracking = true;
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
return new Size(32, 19);
}
}
/// <include file='doc\WinBarMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.DefaultMargin"]/*' />
protected internal override Padding DefaultMargin {
get {
return Padding.Empty;
}
}
/// <include file='doc\WinBarMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.DefaultPadding"]/*' />
protected override Padding DefaultPadding {
get {
if (IsOnDropDown) {
return new Padding(0, 1, 0, 1);
}
else {
return new Padding(4, 0, 4, 0);
}
}
}
public override bool Enabled {
get{
if (nativeMenuCommandID != -1) {
// if we're based off a native menu item,
// we need to ask it if it's enabled.
if (base.Enabled && nativeMenuHandle != IntPtr.Zero && targetWindowHandle != IntPtr.Zero) {
return GetNativeMenuItemEnabled();
}
return false;
}
else {
return base.Enabled;
}
}
set {
base.Enabled = value;
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.Checked"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the item is checked.
/// </para>
/// </devdoc>
[
Bindable(true),
DefaultValue(false),
SRCategory(SR.CatAppearance),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.CheckBoxCheckedDescr)
]
public bool Checked {
get {
return CheckState != CheckState.Unchecked;
}
set {
if (value != Checked) {
CheckState = value ? CheckState.Checked : CheckState.Unchecked;
InvokePaint();
}
}
}
/// <devdoc>
/// Keeps a shared copy of the checked image between all menu items
/// Fishes out the appropriate one based on CheckState.
/// </devdoc>
internal Image CheckedImage {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
CheckState checkedState = CheckState;
if (checkedState == CheckState.Indeterminate) {
if (indeterminateCheckedImage == null) {
Bitmap indeterminateCheckedBmp = new Bitmap(typeof(ToolStripMenuItem), "IndeterminateChecked.bmp");
if (indeterminateCheckedBmp != null) {
//
indeterminateCheckedBmp.MakeTransparent(indeterminateCheckedBmp.GetPixel(1,1));
if (DpiHelper.IsScalingRequired) {
DpiHelper.ScaleBitmapLogicalToDevice(ref indeterminateCheckedBmp);
}
indeterminateCheckedImage = indeterminateCheckedBmp;
}
}
return indeterminateCheckedImage;
}
else if (checkedState == CheckState.Checked) {
if (checkedImage == null) {
Bitmap checkedBmp = new Bitmap(typeof(ToolStripMenuItem), "Checked.bmp");
if (checkedBmp != null) {
//
checkedBmp.MakeTransparent(checkedBmp.GetPixel(1,1));
if (DpiHelper.IsScalingRequired) {
DpiHelper.ScaleBitmapLogicalToDevice(ref checkedBmp);
}
checkedImage = checkedBmp;
}
}
return checkedImage;
}
return null;
}
}
/// <include file='doc\WinBarMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.CheckOnClick"]/*' />
[
DefaultValue(false),
SRCategory(SR.CatBehavior),
SRDescription(SR.ToolStripButtonCheckOnClickDescr)
]
public bool CheckOnClick {
get {
return checkOnClick;
}
set {
checkOnClick = value;
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.CheckState"]/*' />
/// <devdoc>
/// <para>Gets
/// or sets a value indicating whether the check box is checked.</para>
/// </devdoc>
[
Bindable(true),
SRCategory(SR.CatAppearance),
DefaultValue(CheckState.Unchecked),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.CheckBoxCheckStateDescr)
]
public CheckState CheckState {
get {
bool found = false;
object checkState = Properties.GetInteger(PropCheckState, out found);
return (found) ? (CheckState)checkState : CheckState.Unchecked;
}
set {
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(CheckState));
}
if (value != CheckState) {
Properties.SetInteger(PropCheckState, (int)value);
OnCheckedChanged(EventArgs.Empty);
OnCheckStateChanged(EventArgs.Empty);
}
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.CheckedChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// value of the <see cref='System.Windows.Forms.CheckBox.Checked'/>
/// property changes.</para>
/// </devdoc>
[SRDescription(SR.CheckBoxOnCheckedChangedDescr)]
public event EventHandler CheckedChanged {
add {
Events.AddHandler(EventCheckedChanged, value);
}
remove {
Events.RemoveHandler(EventCheckedChanged, value);
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.CheckStateChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// value of the <see cref='System.Windows.Forms.CheckBox.CheckState'/>
/// property changes.</para>
/// </devdoc>
[SRDescription(SR.CheckBoxOnCheckStateChangedDescr)]
public event EventHandler CheckStateChanged {
add {
Events.AddHandler(EventCheckStateChanged, value);
}
remove {
Events.RemoveHandler(EventCheckStateChanged, value);
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.Overflow"]/*' />
/// <devdoc>
/// <para>Specifies whether or not the item is glued to the winbar or overflow or
/// can float between the two.</para>
/// </devdoc>
[
DefaultValue(ToolStripItemOverflow.Never),
SRDescription(SR.ToolStripItemOverflowDescr),
SRCategory(SR.CatLayout)
]
public new ToolStripItemOverflow Overflow {
get {
return base.Overflow;
}
set {
base.Overflow = value;
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.ShortcutKeys"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the shortcut keys associated with the menu
/// item.
/// </para>
/// </devdoc>
[
Localizable(true),
DefaultValue(Keys.None),
SRDescription(SR.MenuItemShortCutDescr)
]
public Keys ShortcutKeys {
get {
bool found = false;
object shortcutKeys = Properties.GetInteger(PropShortcutKeys, out found );
return (found) ? (Keys)shortcutKeys : Keys.None;
}
set {
if ((value != Keys.None) && !ToolStripManager.IsValidShortcut(value)){
// prevent use of alt, ctrl, shift modifiers with no key code.
throw new InvalidEnumArgumentException("value", (int)value, typeof(Keys));
}
Keys originalShortcut = ShortcutKeys;
if (originalShortcut != value) {
ClearShortcutCache();
ToolStrip owner = this.Owner;
if (owner != null) {
// add to the shortcut caching system.
if (originalShortcut != Keys.None) {
owner.Shortcuts.Remove(originalShortcut);
}
if (owner.Shortcuts.Contains(value)) {
// last one in wins.
owner.Shortcuts[value] = this;
}
else {
owner.Shortcuts.Add(value, this);
}
}
Properties.SetInteger(PropShortcutKeys, (int)value);
if (ShowShortcutKeys && IsOnDropDown) {
ToolStripDropDownMenu parent = GetCurrentParentDropDown() as ToolStripDropDownMenu;
if (parent != null) {
LayoutTransaction.DoLayout(this.ParentInternal, this, "ShortcutKeys");
parent.AdjustSize();
}
}
}
}
}
[
SRDescription(SR.ToolStripMenuItemShortcutKeyDisplayStringDescr),
SRCategory(SR.CatAppearance),
DefaultValue(null),
Localizable(true)
]
public string ShortcutKeyDisplayString {
get {
return shortcutKeyDisplayString;
}
set {
if (shortcutKeyDisplayString != value) {
shortcutKeyDisplayString = value;
ClearShortcutCache();
if (ShowShortcutKeys) {
ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown;
if (parent != null) {
LayoutTransaction.DoLayout(parent, this, "ShortcutKeyDisplayString");
parent.AdjustSize();
}
}
}
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.ShowShortcutKeys"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value that indicates whether the shortcut
/// keys that are assocaited
/// with the menu item are displayed next to the menu item
/// caption.
/// </para>
/// </devdoc>
[
DefaultValue(true),
Localizable(true),
SRDescription(SR.MenuItemShowShortCutDescr)
]
public bool ShowShortcutKeys {
get {
return showShortcutKeys;
}
set {
if (value != showShortcutKeys) {
ClearShortcutCache();
showShortcutKeys = value;
ToolStripDropDown parent = this.ParentInternal as ToolStripDropDown;
if (parent != null) {
LayoutTransaction.DoLayout(parent, this, "ShortcutKeys");
parent.AdjustSize();
}
}
}
}
/// <devdoc>
/// An item is toplevel if it is parented to anything other than a ToolStripDropDownMenu
/// This implies that a ToolStripMenuItem in an overflow IS a toplevel item
/// </devdoc>
internal bool IsTopLevel {
get {
return (this.ParentInternal as ToolStripDropDown == null);
}
}
[Browsable(false)]
public bool IsMdiWindowListEntry {
get{
return MdiForm != null;
}
}
internal static MenuTimer MenuTimer {
get {
return menuTimer;
}
}
/// <devdoc> Tag property for internal use </devdoc>
internal Form MdiForm {
get {
if (Properties.ContainsObject(PropMdiForm)) {
return Properties.GetObject(PropMdiForm) as Form;
}
return null;
}
}
internal ToolStripMenuItem Clone() {
// dirt simple clone - just properties, no subitems
ToolStripMenuItem menuItem = new ToolStripMenuItem();
menuItem.Events.AddHandlers(this.Events);
menuItem.AccessibleName = this.AccessibleName;
menuItem.AccessibleRole = this.AccessibleRole;
menuItem.Alignment = this.Alignment;
menuItem.AllowDrop = this.AllowDrop;
menuItem.Anchor = this.Anchor;
menuItem.AutoSize = this.AutoSize;
menuItem.AutoToolTip = this.AutoToolTip;
menuItem.BackColor = this.BackColor;
menuItem.BackgroundImage = this.BackgroundImage;
menuItem.BackgroundImageLayout = this.BackgroundImageLayout;
menuItem.Checked = this.Checked;
menuItem.CheckOnClick = this.CheckOnClick;
menuItem.CheckState = this.CheckState;
menuItem.DisplayStyle = this.DisplayStyle;
menuItem.Dock = this.Dock;
menuItem.DoubleClickEnabled = this.DoubleClickEnabled;
menuItem.Enabled = this.Enabled;
menuItem.Font = this.Font;
menuItem.ForeColor = this.ForeColor;
menuItem.Image = this.Image;
menuItem.ImageAlign = this.ImageAlign;
menuItem.ImageScaling = this.ImageScaling;
menuItem.ImageTransparentColor = this.ImageTransparentColor;
menuItem.Margin = this.Margin;
menuItem.MergeAction = this.MergeAction;
menuItem.MergeIndex = this.MergeIndex;
menuItem.Name = this.Name;
menuItem.Overflow = this.Overflow;
menuItem.Padding = this.Padding;
menuItem.RightToLeft= this.RightToLeft;
// No settings support for cloned items.
// menuItem.SaveSettings= this.SaveSettings;
// menuItem.SettingsKey = this.SettingsKey;
menuItem.ShortcutKeys = this.ShortcutKeys;
menuItem.ShowShortcutKeys = this.ShowShortcutKeys;
menuItem.Tag = this.Tag;
menuItem.Text = this.Text;
menuItem.TextAlign = this.TextAlign;
menuItem.TextDirection = this.TextDirection;
menuItem.TextImageRelation = this.TextImageRelation;
menuItem.ToolTipText = this.ToolTipText;
// cant actually use "Visible" property as that returns whether or not the parent
// is visible too.. instead use ParticipatesInLayout as this queries the actual state.
menuItem.Visible = ((IArrangedElement)this).ParticipatesInLayout;
if (!AutoSize) {
menuItem.Size = this.Size;
}
return menuItem;
}
protected override void Dispose(bool disposing) {
if (disposing) {
if (lastOwner != null) {
Keys shortcut = this.ShortcutKeys;
if (shortcut != Keys.None && lastOwner.Shortcuts.ContainsKey(shortcut)) {
lastOwner.Shortcuts.Remove(shortcut);
}
lastOwner = null;
if (MdiForm != null) {
Properties.SetObject(PropMdiForm,null);
}
}
}
base.Dispose(disposing);
}
private bool GetNativeMenuItemEnabled() {
if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) {
Debug.Fail("why were we called to fetch native menu item info with nothing assigned?");
return false;
}
NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW();
info.cbSize = Marshal.SizeOf(typeof(NativeMethods.MENUITEMINFO_T_RW));
info.fMask = NativeMethods.MIIM_STATE;
info.fType = NativeMethods.MIIM_STATE;
info.wID = nativeMenuCommandID;
UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info);
return ((info.fState & NativeMethods.MFS_DISABLED) == 0);
}
// returns text and shortcut separated by tab.
private string GetNativeMenuItemTextAndShortcut() {
if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) {
Debug.Fail("why were we called to fetch native menu item info with nothing assigned?");
return null;
}
string text = null;
// fetch the string length
NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW();
info.fMask = NativeMethods.MIIM_STRING;
info.fType = NativeMethods.MIIM_STRING;
info.wID = nativeMenuCommandID;
info.dwTypeData = IntPtr.Zero;
UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info);
if (info.cch > 0) {
// fetch the string
info.cch += 1; // according to MSDN we need to increment the count we receive by 1.
info.wID = nativeMenuCommandID;
IntPtr allocatedStringBuffer = Marshal.AllocCoTaskMem(info.cch * Marshal.SystemDefaultCharSize);
info.dwTypeData = allocatedStringBuffer;
try {
UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info);
// convert the string into managed data.
if (info.dwTypeData != IntPtr.Zero){
// we have to use PtrToStringAuto as we can't use Marshal.SizeOf to determine
// the size of the struct with a StringBuilder member.
text = Marshal.PtrToStringAuto(info.dwTypeData, info.cch);
}
}
finally {
if (allocatedStringBuffer != IntPtr.Zero) {
// use our local instead of the info structure member *just* in case windows decides to clobber over it.
// we want to be sure to deallocate the memory we know we allocated.
Marshal.FreeCoTaskMem(allocatedStringBuffer);
}
}
}
return text;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Process, ResourceScope.Machine | ResourceScope.Process)]
private Image GetNativeMenuItemImage(){
if (nativeMenuCommandID == -1 || nativeMenuHandle == IntPtr.Zero) {
Debug.Fail("why were we called to fetch native menu item info with nothing assigned?");
return null;
}
NativeMethods.MENUITEMINFO_T_RW info = new NativeMethods.MENUITEMINFO_T_RW();
info.fMask = NativeMethods.MIIM_BITMAP;
info.fType = NativeMethods.MIIM_BITMAP;
info.wID = nativeMenuCommandID;
UnsafeNativeMethods.GetMenuItemInfo(new HandleRef(this, nativeMenuHandle), nativeMenuCommandID, /*fByPosition instead of ID=*/ false, info);
if (info.hbmpItem != IntPtr.Zero && info.hbmpItem.ToInt32() > NativeMethods.HBMMENU_POPUP_MINIMIZE) {
return Bitmap.FromHbitmap(info.hbmpItem);
}
else {
// its a system defined bitmap
int buttonToUse = -1;
switch (info.hbmpItem.ToInt32()) {
case NativeMethods.HBMMENU_MBAR_CLOSE:
case NativeMethods.HBMMENU_MBAR_CLOSE_D:
case NativeMethods.HBMMENU_POPUP_CLOSE:
buttonToUse = (int)CaptionButton.Close;
break;
case NativeMethods.HBMMENU_MBAR_MINIMIZE:
case NativeMethods.HBMMENU_MBAR_MINIMIZE_D:
case NativeMethods.HBMMENU_POPUP_MINIMIZE:
buttonToUse = (int)CaptionButton.Minimize;
break;
case NativeMethods.HBMMENU_MBAR_RESTORE:
case NativeMethods.HBMMENU_POPUP_RESTORE:
buttonToUse = (int)CaptionButton.Restore;
break;
case NativeMethods.HBMMENU_POPUP_MAXIMIZE:
buttonToUse = (int)CaptionButton.Maximize;
break;
case NativeMethods.HBMMENU_SYSTEM:
//
case NativeMethods.HBMMENU_CALLBACK:
// owner draw not supported
default:
break;
}
if (buttonToUse > -1) {
// we've mapped to a system defined bitmap we know how to draw
Bitmap image = new Bitmap(16, 16);
using (Graphics g = Graphics.FromImage(image)) {
ControlPaint.DrawCaptionButton(g, new Rectangle(Point.Empty, image.Size), (CaptionButton)buttonToUse, ButtonState.Flat);
g.DrawRectangle(SystemPens.Control, 0, 0, image.Width - 1, image.Height - 1);
}
image.MakeTransparent(SystemColors.Control);
return image;
}
}
return null;
}
internal Size GetShortcutTextSize() {
if (!ShowShortcutKeys) {
return Size.Empty;
}
string shortcutString = GetShortcutText();
if (string.IsNullOrEmpty(shortcutString)) {
return Size.Empty;
}
else if (cachedShortcutSize == Size.Empty) {
cachedShortcutSize = TextRenderer.MeasureText(shortcutString, Font);
}
return cachedShortcutSize;
}
private string GetShortcutText() {
if (cachedShortcutText == null) {
cachedShortcutText = ShortcutToText(this.ShortcutKeys, this.ShortcutKeyDisplayString);
}
return cachedShortcutText;
}
internal void HandleAutoExpansion() {
if (Enabled && ParentInternal != null && ParentInternal.MenuAutoExpand && HasDropDownItems) {
ShowDropDown();
DropDown.SelectNextToolStripItem(null, /*forward=*/true);
}
}
/// <include file='doc\WinBarMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnClick"]/*' />
protected override void OnClick(EventArgs e) {
if (checkOnClick) {
this.Checked = !this.Checked;
}
base.OnClick(e);
if (nativeMenuCommandID != -1) {
// fire off the appropriate native handler by posting a message to the window target.
if ((nativeMenuCommandID & 0xF000) != 0) {
// These are system menu items like Minimize, Maximize, Restore, Resize, Move, Close.
// use PostMessage instead of SendMessage so that the DefWndProc can appropriately handle
// the system message... if we use SendMessage the dismissal of our window
// breaks things like the modal sizing loop.
UnsafeNativeMethods.PostMessage( new HandleRef(this, targetWindowHandle), NativeMethods.WM_SYSCOMMAND,nativeMenuCommandID, 0);
}
else {
// These are user added items like ".Net Window..."
// be consistent with sending a WM_SYSCOMMAND, use POST not SEND.
UnsafeNativeMethods.PostMessage( new HandleRef(this, targetWindowHandle), NativeMethods.WM_COMMAND, nativeMenuCommandID, 0);
}
this.Invalidate();
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnCheckedChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.ToolStripMenuItem.CheckedChanged'/>
/// event.</para>
/// </devdoc>
protected virtual void OnCheckedChanged(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventCheckedChanged];
if (handler != null) handler(this,e);
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnCheckStateChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.ToolStripMenuItem.CheckStateChanged'/> event.</para>
/// </devdoc>
protected virtual void OnCheckStateChanged(EventArgs e) {
AccessibilityNotifyClients(AccessibleEvents.StateChange);
EventHandler handler = (EventHandler)Events[EventCheckStateChanged];
if (handler != null) handler(this,e);
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnDropDownHide"]/*' />
protected override void OnDropDownHide(EventArgs e) {
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnDropDownHide] MenuTimer.Cancel called");
MenuTimer.Cancel(this);
base.OnDropDownHide(e);
}
protected override void OnDropDownShow(EventArgs e) {
// if someone has beaten us to the punch by arrowing around
// cancel the current menu timer.
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnDropDownShow] MenuTimer.Cancel called");
MenuTimer.Cancel(this);
if (ParentInternal != null) {
ParentInternal.MenuAutoExpand = true;
}
base.OnDropDownShow(e);
}
protected override void OnFontChanged(EventArgs e) {
ClearShortcutCache();
base.OnFontChanged(e);
}
/// <devdoc/><internalonly/>
internal void OnMenuAutoExpand() {
this.ShowDropDown();
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnMouseDown"]/*' />
/// <devdoc/>
protected override void OnMouseDown(MouseEventArgs e) {
// Opening should happen on mouse down
// we use a mouse down ID to ensure that the reshow
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseDown] MenuTimer.Cancel called");
MenuTimer.Cancel(this);
OnMouseButtonStateChange(e, /*isMouseDown=*/true);
}
protected override void OnMouseUp(MouseEventArgs e) {
OnMouseButtonStateChange(e, /*isMouseDown=*/false);
base.OnMouseUp(e);
}
private void OnMouseButtonStateChange(MouseEventArgs e, bool isMouseDown) {
bool showDropDown = true;
if (IsOnDropDown) {
ToolStripDropDown dropDown = GetCurrentParentDropDown() as ToolStripDropDown;
// VSWhidbey 260536 - right click support for context menus.
// used in ToolStripItem to determine whether to fire click OnMouseUp.
SupportsRightClick = (dropDown.GetFirstDropDown() is ContextMenuStrip);
}
else {
showDropDown = !DropDown.Visible;
SupportsRightClick = false;
}
if (e.Button == MouseButtons.Left ||
(e.Button == MouseButtons.Right && SupportsRightClick)) {
if (isMouseDown && showDropDown) {
// opening should happen on mouse down.
Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID");
openMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId();
this.ShowDropDown(/*mousePush =*/true);
}
else if (!isMouseDown && !showDropDown) {
// closing should happen on mouse up. ensure it's not the mouse
// up for the mouse down we opened with.
Debug.Assert(ParentInternal != null, "Parent is null here, not going to get accurate ID");
byte closeMouseId = (ParentInternal == null) ? (byte)0: ParentInternal.GetMouseId();
int openedMouseID =openMouseId;
if (closeMouseId != openedMouseID) {
openMouseId = 0; // reset the mouse id, we should never get this value from toolstrip.
ToolStripManager.ModalMenuFilter.CloseActiveDropDown(DropDown, ToolStripDropDownCloseReason.AppClicked);
Select();
}
}
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnMouseEnter"]/*' />
/// <devdoc/>
protected override void OnMouseEnter(EventArgs e) {
Debug.Assert(this.ParentInternal != null, "Why is parent null");
// If we are in a submenu pop down the submenu.
if (this.ParentInternal != null && this.ParentInternal.MenuAutoExpand && Selected) {
Debug.WriteLineIf(ToolStripItem.MouseDebugging.TraceVerbose, "received mouse enter - calling drop down");
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseEnter] MenuTimer.Cancel / MenuTimer.Start called");
MenuTimer.Cancel(this);
MenuTimer.Start(this);
}
base.OnMouseEnter(e);
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnMouseLeave"]/*' />
/// <devdoc/>
protected override void OnMouseLeave(EventArgs e) {
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[ToolStripMenuItem.OnMouseLeave] MenuTimer.Cancel called");
MenuTimer.Cancel(this);
base.OnMouseLeave(e);
}
protected override void OnOwnerChanged(EventArgs e) {
Keys shortcut = this.ShortcutKeys;
if (shortcut != Keys.None) {
if (lastOwner != null) {
lastOwner.Shortcuts.Remove(shortcut);
}
if (Owner != null) {
if (Owner.Shortcuts.Contains(shortcut)) {
// last one in wins
Owner.Shortcuts[shortcut] = this;
}
else {
Owner.Shortcuts.Add(shortcut, this);
}
lastOwner = Owner;
}
}
base.OnOwnerChanged(e);
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.OnPaint"]/*' />
/// <devdoc/>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) {
if (this.Owner != null) {
ToolStripRenderer renderer = this.Renderer;
Graphics g = e.Graphics;
renderer.DrawMenuItemBackground(new ToolStripItemRenderEventArgs(g, this));
Color textColor = SystemColors.MenuText;
if (IsForeColorSet) {
textColor = this.ForeColor;
}
else if (!this.IsTopLevel || (ToolStripManager.VisualStylesEnabled)) {
if (Selected || Pressed) {
textColor = SystemColors.HighlightText;
}
else {
textColor = SystemColors.MenuText;
}
}
bool rightToLeft = (RightToLeft == RightToLeft.Yes);
ToolStripMenuItemInternalLayout menuItemInternalLayout = this.InternalLayout as ToolStripMenuItemInternalLayout;
if (menuItemInternalLayout != null && menuItemInternalLayout.UseMenuLayout) {
// Support for special DropDownMenu layout
#if DEBUG_PAINT
g.DrawRectangle(Pens.Green, menuItemInternalLayout.TextRectangle);
g.DrawRectangle(Pens.HotPink, menuItemInternalLayout.ImageRectangle);
g.DrawRectangle(Pens.Black, menuItemInternalLayout.CheckRectangle);
g.DrawRectangle(Pens.Red, menuItemInternalLayout.ArrowRectangle);
g.DrawRectangle(Pens.Blue, new Rectangle(Point.Empty, new Size(-1,-1) + this.Size));
#endif
if (CheckState != CheckState.Unchecked && menuItemInternalLayout.PaintCheck) {
Rectangle checkRectangle = menuItemInternalLayout.CheckRectangle;
if (!menuItemInternalLayout.ShowCheckMargin) {
checkRectangle = menuItemInternalLayout.ImageRectangle;
}
if (checkRectangle.Width != 0) {
renderer.DrawItemCheck(new ToolStripItemImageRenderEventArgs(g, this, CheckedImage, checkRectangle));
}
}
if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) {
// render text AND shortcut
renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, textColor, this.Font, (rightToLeft) ? ContentAlignment.MiddleRight : ContentAlignment.MiddleLeft));
bool showShortCut = ShowShortcutKeys;
if (!DesignMode){
showShortCut = showShortCut && !HasDropDownItems;
}
if (showShortCut) {
renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, GetShortcutText(), InternalLayout.TextRectangle, textColor, this.Font, (rightToLeft) ? ContentAlignment.MiddleLeft : ContentAlignment.MiddleRight));
}
}
if (HasDropDownItems) {
ArrowDirection arrowDir = (rightToLeft) ? ArrowDirection.Left : ArrowDirection.Right;
Color arrowColor = (Selected ||Pressed) ? SystemColors.HighlightText : SystemColors.MenuText;
arrowColor = (Enabled) ? arrowColor : SystemColors.ControlDark;
renderer.DrawArrow(new ToolStripArrowRenderEventArgs(g, this, menuItemInternalLayout.ArrowRectangle, arrowColor, arrowDir));
}
if (menuItemInternalLayout.PaintImage && (DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) {
renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle));
}
}
else {
// Toplevel item support, menu items hosted on a plain winbar dropdown
if ((DisplayStyle & ToolStripItemDisplayStyle.Text) == ToolStripItemDisplayStyle.Text) {
renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(g, this, this.Text, InternalLayout.TextRectangle, textColor, this.Font, InternalLayout.TextFormat));
}
if ((DisplayStyle & ToolStripItemDisplayStyle.Image) == ToolStripItemDisplayStyle.Image && Image != null) {
renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(g, this, InternalLayout.ImageRectangle));
}
}
}
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.ProcessCmdKey"]/*' />
/// <devdoc>
/// handle shortcut keys here.
/// </devdoc>
[
SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)
]
protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) {
if (Enabled && ShortcutKeys == keyData && !HasDropDownItems) {
FireEvent(ToolStripItemEventType.Click);
return true;
}
// call base here to get ESC, ALT, etc.. handling.
return base.ProcessCmdKey(ref m, keyData);
}
/// <include file='doc\ToolStripMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.ProcessMnemonic"]/*' />
[UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs
protected internal override bool ProcessMnemonic(char charCode) {
// no need to check IsMnemonic, toolstrip.ProcessMnemonic checks this already.
if (HasDropDownItems) {
Select();
ShowDropDown();
DropDown.SelectNextToolStripItem(null, /*forward=*/true);
return true;
}
return base.ProcessMnemonic(charCode);
}
/// <include file='doc\WinBarMenuItem.uex' path='docs/doc[@for="ToolStripMenuItem.SetBounds"]/*' />
/// <devdoc> overridden here so we scooch over when we're in the ToolStripDropDownMenu</devdoc>
internal protected override void SetBounds(Rectangle rect) {
ToolStripMenuItemInternalLayout internalLayout = InternalLayout as ToolStripMenuItemInternalLayout;
if (internalLayout != null && internalLayout.UseMenuLayout) {
ToolStripDropDownMenu dropDownMenu = Owner as ToolStripDropDownMenu;
// Scooch over by the padding amount. The padding is added to
// the ToolStripDropDownMenu to keep the non-menu item riffraff
// aligned to the text rectangle. When flow layout comes through to set our position
// via IArrangedElement DEFY IT!
if (dropDownMenu != null) {
rect.X -= dropDownMenu.Padding.Left;
rect.X = Math.Max(rect.X,0);
}
}
base.SetBounds(rect);
}
/// <devdoc> this is to support routing to native menu commands </devdoc>
internal void SetNativeTargetWindow(IWin32Window window) {
targetWindowHandle = Control.GetSafeHandle(window);
}
/// <devdoc> this is to support routing to native menu commands </devdoc>
internal void SetNativeTargetMenu(IntPtr hMenu) {
nativeMenuHandle = hMenu;
}
internal static string ShortcutToText(Keys shortcutKeys, string shortcutKeyDisplayString) {
if (!string.IsNullOrEmpty(shortcutKeyDisplayString)) {
return shortcutKeyDisplayString;
}
else if (shortcutKeys == Keys.None) {
return String.Empty;
}
else {
return TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(shortcutKeys);
}
}
/// <devdoc>
/// An implementation of AccessibleChild for use with ToolStripItems
/// </devdoc>
[System.Runtime.InteropServices.ComVisible(true)]
internal class ToolStripMenuItemAccessibleObject : ToolStripDropDownItemAccessibleObject {
private ToolStripMenuItem ownerItem = null;
public ToolStripMenuItemAccessibleObject(ToolStripMenuItem ownerItem) : base(ownerItem) {
this.ownerItem = ownerItem;
}
public override AccessibleStates State {
get {
if (ownerItem.Enabled ) {
AccessibleStates state = base.State;
if ((state & AccessibleStates.Pressed) == AccessibleStates.Pressed){
// for some reason menu items are never "pressed".
state &= ~AccessibleStates.Pressed;
}
if (ownerItem.Checked) {
state |= AccessibleStates.Checked;
}
return state;
}
return base.State;
}
}
}
}
internal class MenuTimer {
private System.Windows.Forms.Timer autoMenuExpandTimer = new System.Windows.Forms.Timer();
// consider - weak reference?
private ToolStripMenuItem currentItem = null;
private ToolStripMenuItem fromItem = null;
private bool inTransition = false;
private int quickShow = 1;
private int slowShow;
public MenuTimer() {
// MenuShowDelay can be set to 0. In this case, set to something low so it's inperceptable.
autoMenuExpandTimer.Tick += new EventHandler(OnTick);
// since MenuShowDelay is registry tweakable we've gotta make sure we've got some sort
// of interval
slowShow = Math.Max(quickShow, SystemInformation.MenuShowDelay);
}
// the current item to autoexpand.
private ToolStripMenuItem CurrentItem {
get {
return currentItem;
}
set{
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose && currentItem != value, "[MenuTimer.CurrentItem] changed: " + ((value == null) ? "null" : value.ToString()));
currentItem = value;
}
}
public bool InTransition {
get { return inTransition; }
set { inTransition = value; }
}
public void Start(ToolStripMenuItem item) {
if (InTransition) {
return;
}
StartCore(item);
}
private void StartCore(ToolStripMenuItem item) {
if (item != CurrentItem) {
Cancel(CurrentItem);
}
CurrentItem = item;
if (item != null) {
CurrentItem = item;
autoMenuExpandTimer.Interval = item.IsOnDropDown ? slowShow : quickShow;
autoMenuExpandTimer.Enabled = true;
}
}
public void Transition(ToolStripMenuItem fromItem, ToolStripMenuItem toItem) {
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[MenuTimer.Transition] transitioning items " + fromItem.ToString() + " " + toItem.ToString());
if (toItem == null && InTransition) {
Cancel();
// in this case we're likely to have hit an item that's not a menu item
// or nothing is selected.
EndTransition(/*forceClose*/ true);
return;
}
if (this.fromItem != fromItem) {
this.fromItem = fromItem;
CancelCore();
StartCore(toItem);
}
// set up the current item to be the toItem so it will be auto expanded when complete.
CurrentItem = toItem;
InTransition = true;
}
public void Cancel() {
if (InTransition) {
return;
}
CancelCore();
}
///<devdoc> cancels if and only if this item was the one that
/// requested the timer
///</devdoc>
public void Cancel(ToolStripMenuItem item) {
if (InTransition) {
return;
}
if (item == CurrentItem) {
CancelCore();
}
}
private void CancelCore() {
autoMenuExpandTimer.Enabled = false;
CurrentItem = null;
}
private void EndTransition(bool forceClose) {
ToolStripMenuItem lastSelected = fromItem;
fromItem = null; // immediately clear BEFORE we call user code.
if (InTransition) {
InTransition = false;
// we should roolup if the current item has changed and is selected.
bool rollup = forceClose || (CurrentItem != null && CurrentItem != lastSelected && CurrentItem.Selected);
if (rollup && lastSelected != null && lastSelected.HasDropDownItems) {
lastSelected.HideDropDown();
}
}
}
internal void HandleToolStripMouseLeave(ToolStrip toolStrip) {
if (InTransition && toolStrip == fromItem.ParentInternal) {
// restore the selection back to CurrentItem.
// we're about to fall off the edge of the toolstrip, something should be selected
// at all times while we're InTransition mode - otherwise it looks really funny
// to have an auto expanded item
if (CurrentItem != null) {
CurrentItem.Select();
}
}
else {
// because we've split up selected/pressed, we need to make sure
// that onmouseleave we make sure there's a selected menu item.
if (toolStrip.IsDropDown && toolStrip.ActiveDropDowns.Count > 0) {
ToolStripDropDown dropDown = toolStrip.ActiveDropDowns[0] as ToolStripDropDown;
ToolStripMenuItem menuItem = (dropDown == null) ? null : dropDown.OwnerItem as ToolStripMenuItem;
if (menuItem != null && menuItem.Pressed) {
menuItem.Select();
}
}
}
}
private void OnTick(object sender, EventArgs e) {
autoMenuExpandTimer.Enabled = false;
if (CurrentItem == null) {
return;
}
EndTransition(/*forceClose*/false);
if (CurrentItem != null && !CurrentItem.IsDisposed && CurrentItem.Selected && CurrentItem.Enabled && ToolStripManager.ModalMenuFilter.InMenuMode) {
Debug.WriteLineIf(ToolStrip.MenuAutoExpandDebug.TraceVerbose, "[MenuTimer.OnTick] calling OnMenuAutoExpand");
CurrentItem.OnMenuAutoExpand();
}
}
}
internal class ToolStripMenuItemInternalLayout : ToolStripItemInternalLayout {
private ToolStripMenuItem ownerItem;
public ToolStripMenuItemInternalLayout(ToolStripMenuItem ownerItem) : base(ownerItem) {
this.ownerItem = ownerItem;
}
public bool ShowCheckMargin {
get{
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
return menu.ShowCheckMargin;
}
return false;
}
}
public bool ShowImageMargin {
get{
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
return menu.ShowImageMargin;
}
return false;
}
}
public bool PaintCheck {
get {
return ShowCheckMargin || ShowImageMargin;
}
}
public bool PaintImage {
get {
return ShowImageMargin;
}
}
public Rectangle ArrowRectangle {
get {
if (UseMenuLayout) {
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
// since menuItem.Padding isnt taken into consideration, we've got to recalc the centering of
// the arrow rect per item
Rectangle arrowRect = menu.ArrowRectangle;
arrowRect.Y = LayoutUtils.VAlign(arrowRect.Size, ownerItem.ClientBounds, ContentAlignment.MiddleCenter).Y;
return arrowRect;
}
}
return Rectangle.Empty;
}
}
public Rectangle CheckRectangle {
get {
if (UseMenuLayout) {
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
Rectangle checkRectangle = menu.CheckRectangle;
if (ownerItem.CheckedImage != null) {
int imageHeight = ownerItem.CheckedImage.Height;
// make sure we're vertically centered
checkRectangle.Y += (checkRectangle.Height - imageHeight)/2;
checkRectangle.Height = imageHeight;
return checkRectangle;
}
}
}
return Rectangle.Empty;
}
}
public override Rectangle ImageRectangle {
get {
if (UseMenuLayout) {
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
// since menuItem.Padding isnt taken into consideration, we've got to recalc the centering of
// the image rect per item
Rectangle imageRect = menu.ImageRectangle;
if (ownerItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) {
imageRect.Size = menu.ImageScalingSize;
}
else {
//If we don't have an image, use the CheckedImage
Image image = ownerItem.Image ?? ownerItem.CheckedImage;
imageRect.Size = image.Size;
}
imageRect.Y = LayoutUtils.VAlign(imageRect.Size, ownerItem.ClientBounds, ContentAlignment.MiddleCenter).Y;
return imageRect;
}
}
return base.ImageRectangle;
}
}
public override Rectangle TextRectangle {
get {
if (UseMenuLayout) {
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
return menu.TextRectangle;
}
}
return base.TextRectangle;
}
}
public bool UseMenuLayout {
get {
return ownerItem.Owner is ToolStripDropDownMenu;
}
}
public override Size GetPreferredSize(Size constrainingSize) {
if (UseMenuLayout) {
ToolStripDropDownMenu menu = ownerItem.Owner as ToolStripDropDownMenu;
if (menu != null) {
return menu.MaxItemSize;
}
}
return base.GetPreferredSize(constrainingSize);
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Activities.Presentation
{
using System.Activities.Presentation.Annotations;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.View;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
public class ActivityDesigner : WorkflowViewElement
{
UserControl defaultDisplayNameReadOnlyControl;
TextBox defaultDisplayNameBox;
bool defaultDisplayNameReadOnlyControlMouseDown;
private AnnotationManager annotationManager;
[Fx.Tag.KnownXamlExternal]
public DrawingBrush Icon
{
get { return (DrawingBrush)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof(DrawingBrush), typeof(ActivityDesigner), new UIPropertyMetadata(null));
internal static readonly DependencyProperty ActivityDelegatesProperty = DependencyProperty.Register("ActivityDelegates", typeof(ObservableCollection<ActivityDelegateInfo>), typeof(ActivityDesigner));
internal static readonly DependencyProperty HasActivityDelegatesProperty = DependencyProperty.Register("HasActivityDelegates", typeof(bool), typeof(ActivityDesigner));
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.InitializeReferenceTypeStaticFieldsInline,
Justification = "Calls to OverrideMetadata for a dependency property should be done in the static constructor.")]
static ActivityDesigner()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ActivityDesigner), new FrameworkPropertyMetadata(typeof(ActivityDesigner)));
}
public ActivityDesigner()
{
this.Loaded += (sender, args) =>
{
this.SetupDefaultIcon();
this.annotationManager.Initialize();
};
this.Unloaded += (sender, args) =>
{
this.annotationManager.Uninitialize();
};
this.annotationManager = new AnnotationManager(this);
}
internal ObservableCollection<ActivityDelegateInfo> ActivityDelegates
{
get { return (ObservableCollection<ActivityDelegateInfo>)GetValue(ActivityDelegatesProperty); }
set { SetValue(ActivityDelegatesProperty, value); }
}
internal bool HasActivityDelegates
{
get { return (bool)GetValue(HasActivityDelegatesProperty); }
set { SetValue(HasActivityDelegatesProperty, value); }
}
protected override void OnModelItemChanged(object newItem)
{
base.OnModelItemChanged(newItem);
this.PopulateActivityDelegates((ModelItem)newItem);
}
private void PopulateActivityDelegates(ModelItem modelItem)
{
if (this.ActivityDelegates == null)
{
this.ActivityDelegates = new ObservableCollection<ActivityDelegateInfo>();
}
else
{
this.ActivityDelegates.Clear();
}
List<ActivityDelegateInfo> list = ActivityDelegateUtilities.CreateActivityDelegateInfo(modelItem);
if (list.Count > 0)
{
foreach (ActivityDelegateInfo entry in list)
{
this.ActivityDelegates.Add(entry);
}
this.HasActivityDelegates = true;
}
else
{
this.HasActivityDelegates = false;
}
}
protected override string GetAutomationIdMemberName()
{
return "DisplayName";
}
protected internal override string GetAutomationItemStatus()
{
StringBuilder descriptiveText = new StringBuilder();
EmitPropertyValuePair(descriptiveText, "IsPrimarySelection");
EmitPropertyValuePair(descriptiveText, "IsSelection");
EmitPropertyValuePair(descriptiveText, "IsCurrentLocation");
EmitPropertyValuePair(descriptiveText, "IsCurrentContext");
EmitPropertyValuePair(descriptiveText, "IsBreakpointEnabled");
EmitPropertyValuePair(descriptiveText, "IsBreakpointBounded");
EmitPropertyValuePair(descriptiveText, "ValidationState");
descriptiveText.Append(base.GetAutomationItemStatus());
return descriptiveText.ToString();
}
void EmitPropertyValuePair(StringBuilder description, string propertyName)
{
PropertyDescriptor property = TypeDescriptor.GetProperties(this.ModelItem)[propertyName];
object propertyValue = (property == null) ? null : property.GetValue(this.ModelItem);
string propertyValueString = propertyValue == null ? "null" : propertyValue.ToString();
description.AppendFormat("{0}={1} ", propertyName, propertyValueString);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (this.defaultDisplayNameBox != null)
{
this.defaultDisplayNameBox.LostFocus -= new RoutedEventHandler(OnDefaultDisplayNameBoxLostFocus);
this.defaultDisplayNameBox.ContextMenuOpening -= new ContextMenuEventHandler(OnDefaultDisplayNameBoxContextMenuOpening);
}
if (this.defaultDisplayNameReadOnlyControl != null)
{
this.defaultDisplayNameReadOnlyControl.MouseLeftButtonDown -= new MouseButtonEventHandler(OnDefaultDisplayNameReadOnlyControlMouseLeftButtonDown);
this.defaultDisplayNameReadOnlyControl.GotKeyboardFocus -= new KeyboardFocusChangedEventHandler(OnDefaultDisplayNameReadOnlyControlGotKeyboardFocus);
}
this.defaultDisplayNameReadOnlyControl = this.Template.FindName("DisplayNameReadOnlyControl_6E8E4954_F6B2_4c6c_9E28_33A7A78F1E81", this) as UserControl;
this.defaultDisplayNameBox = this.Template.FindName("DisplayNameBox_570C5205_7195_4d4e_953A_8E4B57EF7E7F", this) as TextBox;
UIElement defaultAnnotationIndicator = this.Template.FindName("AnnotationIndicator_570C5205_7195_4d4e_953A_8E4B57EF7E7F", this) as UIElement;
DockedAnnotationDecorator defaultDockedAnnotationDecorator = this.Template.FindName("DockedAnnotationDecorator_570C5205_7195_4d4e_953A_8E4B57EF7E7F", this) as DockedAnnotationDecorator;
if (defaultAnnotationIndicator != null && defaultDockedAnnotationDecorator != null)
{
this.annotationManager.AnnotationVisualProvider = new ActivityDesignerAnnotationVisualProvider(new UIElementToAnnotationIndicatorAdapter(defaultAnnotationIndicator), defaultDockedAnnotationDecorator);
}
if (this.defaultDisplayNameBox != null && this.defaultDisplayNameReadOnlyControl != null)
{
this.defaultDisplayNameBox.LostFocus += new RoutedEventHandler(OnDefaultDisplayNameBoxLostFocus);
this.defaultDisplayNameBox.ContextMenuOpening += new ContextMenuEventHandler(OnDefaultDisplayNameBoxContextMenuOpening);
this.defaultDisplayNameReadOnlyControl.MouseLeftButtonDown += new MouseButtonEventHandler(OnDefaultDisplayNameReadOnlyControlMouseLeftButtonDown);
this.defaultDisplayNameReadOnlyControl.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(OnDefaultDisplayNameReadOnlyControlGotKeyboardFocus);
}
Border titleBar = this.Template.FindName("TitleBar_C36A1CF2_4B36_4F0D_B427_9825C2E110DE", this) as Border;
if (titleBar != null)
{
this.DragHandle = titleBar;
}
}
void OnDefaultDisplayNameReadOnlyControlGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (this.defaultDisplayNameBox != null && this.defaultDisplayNameReadOnlyControl != null)
{
DesignerView designerView = this.Context.Services.GetService<DesignerView>();
if (!designerView.IsReadOnly && !designerView.IsMultipleSelectionMode)
{
this.EnterDisplayNameEditMode();
}
}
}
void OnDefaultDisplayNameReadOnlyControlMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.defaultDisplayNameReadOnlyControlMouseDown = true;
}
void OnDefaultDisplayNameBoxLostFocus(object sender, RoutedEventArgs e)
{
if (this.defaultDisplayNameBox != null && this.defaultDisplayNameReadOnlyControl != null)
{
this.ExitDisplayNameEditMode();
}
}
void OnDefaultDisplayNameBoxContextMenuOpening(object sender, ContextMenuEventArgs e)
{
// to disable the context menu
e.Handled = true;
}
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
this.defaultDisplayNameReadOnlyControlMouseDown = false;
base.OnPreviewMouseDown(e);
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
// We have to check the defaultDisplayNameReadOnlyControlMouseDown flag to determine whether the mouse is clicked on
// the defaultDisplayNameReadOnlyControl. This is because the mouse capture is set on the WorkflowViewElement in
// OnMouseDown, and as a result MouseUp event is not fired on the defaultDisplayNameReadOnlyControl.
if (this.defaultDisplayNameBox != null && this.defaultDisplayNameReadOnlyControl != null &&
this.defaultDisplayNameReadOnlyControlMouseDown)
{
this.defaultDisplayNameReadOnlyControlMouseDown = false;
DesignerView designerView = this.Context.Services.GetService<DesignerView>();
if (!designerView.IsReadOnly)
{
this.EnterDisplayNameEditMode();
}
}
base.OnMouseUp(e);
}
void EnterDisplayNameEditMode()
{
this.defaultDisplayNameBox.Visibility = Visibility.Visible;
this.defaultDisplayNameReadOnlyControl.Visibility = Visibility.Collapsed;
this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() =>
{
Keyboard.Focus(this.defaultDisplayNameBox);
this.defaultDisplayNameBox.ScrollToHome();
}));
}
void ExitDisplayNameEditMode()
{
this.defaultDisplayNameReadOnlyControl.Visibility = Visibility.Visible;
this.defaultDisplayNameBox.Visibility = Visibility.Collapsed;
}
private void SetupDefaultIcon()
{
if (this.Icon == null)
{
this.Icon = GetDefaultIcon();
}
}
internal DrawingBrush GetDefaultIcon()
{
DrawingBrush icon = null;
// Look for a named icon if this property is not set
if (this.ModelItem != null)
{
string iconKey = this.ModelItem.ItemType.IsGenericType ? this.ModelItem.ItemType.GetGenericTypeDefinition().Name : this.ModelItem.ItemType.Name;
int genericParamsIndex = iconKey.IndexOf('`');
if (genericParamsIndex > 0)
{
iconKey = iconKey.Remove(genericParamsIndex);
}
iconKey = iconKey + "Icon";
try
{
if (WorkflowDesignerIcons.IconResourceDictionary.Contains(iconKey))
{
object resourceItem = WorkflowDesignerIcons.IconResourceDictionary[iconKey];
if (resourceItem is DrawingBrush)
{
icon = (DrawingBrush)resourceItem;
}
}
}
catch (ResourceReferenceKeyNotFoundException) { }
catch (InvalidCastException) { }
}
if (icon == null)
{
// as a last resort fall back to the default generic leaf activity icon.
icon = WorkflowDesignerIcons.Activities.DefaultCustomActivity;
}
return icon;
}
protected internal override void OnEditAnnotation()
{
this.annotationManager.OnEditAnnotation();
}
private class ActivityDesignerAnnotationVisualProvider : IAnnotationVisualProvider
{
private DockedAnnotationDecorator decorator;
private IAnnotationIndicator indicator;
private IFloatingAnnotation floatingAnnotation;
private IDockedAnnotation dockedAnnotation;
public ActivityDesignerAnnotationVisualProvider(IAnnotationIndicator indicator, DockedAnnotationDecorator decorator)
{
this.indicator = indicator;
this.decorator = decorator;
}
public IAnnotationIndicator GetAnnotationIndicator()
{
return this.indicator;
}
public IFloatingAnnotation GetFloatingAnnotation()
{
if (this.floatingAnnotation == null)
{
this.floatingAnnotation = new FloatingAnnotationView();
}
return this.floatingAnnotation;
}
public IDockedAnnotation GetDockedAnnotation()
{
if (this.dockedAnnotation == null)
{
DockedAnnotationView view = new DockedAnnotationView();
Binding annotationTextbinding = new Binding("ModelItem.AnnotationText");
view.SetBinding(DockedAnnotationView.AnnotationTextProperty, annotationTextbinding);
Binding maxWidthBinding = new Binding("ActualWidth");
maxWidthBinding.ElementName = "annotationWidthSetter";
view.SetBinding(DockedAnnotationView.MaxWidthProperty, maxWidthBinding);
this.dockedAnnotation = view;
this.decorator.Child = view;
}
return this.dockedAnnotation;
}
}
}
}
| |
using NPOI.Util;
namespace NPOI.SS.Formula
{
using System;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Util;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
using System.Globalization;
/**
* Contains all the contextual information required to Evaluate an operation
* within a formula
*
* For POI internal use only
*
* @author Josh Micich
*/
public class OperationEvaluationContext
{
public static readonly FreeRefFunction UDF = UserDefinedFunction.instance;
private IEvaluationWorkbook _workbook;
private int _sheetIndex;
private int _rowIndex;
private int _columnIndex;
private EvaluationTracker _tracker;
private WorkbookEvaluator _bookEvaluator;
public OperationEvaluationContext(WorkbookEvaluator bookEvaluator, IEvaluationWorkbook workbook, int sheetIndex, int srcRowNum,
int srcColNum, EvaluationTracker tracker)
{
_bookEvaluator = bookEvaluator;
_workbook = workbook;
_sheetIndex = sheetIndex;
_rowIndex = srcRowNum;
_columnIndex = srcColNum;
_tracker = tracker;
}
public IEvaluationWorkbook GetWorkbook()
{
return _workbook;
}
public int RowIndex
{
get
{
return _rowIndex;
}
}
public int ColumnIndex
{
get
{
return _columnIndex;
}
}
SheetRangeEvaluator CreateExternSheetRefEvaluator(IExternSheetReferenceToken ptg)
{
return CreateExternSheetRefEvaluator(ptg.ExternSheetIndex);
}
SheetRangeEvaluator CreateExternSheetRefEvaluator(String firstSheetName, String lastSheetName, int externalWorkbookNumber)
{
ExternalSheet externalSheet = _workbook.GetExternalSheet(firstSheetName, lastSheetName, externalWorkbookNumber);
return CreateExternSheetRefEvaluator(externalSheet);
}
SheetRangeEvaluator CreateExternSheetRefEvaluator(int externSheetIndex)
{
ExternalSheet externalSheet = _workbook.GetExternalSheet(externSheetIndex);
return CreateExternSheetRefEvaluator(externalSheet);
}
SheetRangeEvaluator CreateExternSheetRefEvaluator(ExternalSheet externalSheet)
{
WorkbookEvaluator targetEvaluator;
int otherFirstSheetIndex;
int otherLastSheetIndex = -1;
if (externalSheet == null || externalSheet.WorkbookName == null)
{
// sheet is in same workbook
targetEvaluator = _bookEvaluator;
if (externalSheet == null)
{
otherFirstSheetIndex = 0;
}
else
{
otherFirstSheetIndex = _workbook.GetSheetIndex(externalSheet.SheetName);
}
if (externalSheet is ExternalSheetRange)
{
String lastSheetName = ((ExternalSheetRange)externalSheet).LastSheetName;
otherLastSheetIndex = _workbook.GetSheetIndex(lastSheetName);
}
}
else
{
// look up sheet by name from external workbook
String workbookName = externalSheet.WorkbookName;
try
{
targetEvaluator = _bookEvaluator.GetOtherWorkbookEvaluator(workbookName);
}
catch (WorkbookNotFoundException e)
{
throw new RuntimeException(e.Message, e);
}
otherFirstSheetIndex = targetEvaluator.GetSheetIndex(externalSheet.SheetName);
if (externalSheet is ExternalSheetRange)
{
String lastSheetName = ((ExternalSheetRange)externalSheet).LastSheetName;
otherLastSheetIndex = targetEvaluator.GetSheetIndex(lastSheetName);
}
if (otherFirstSheetIndex < 0)
{
throw new Exception("Invalid sheet name '" + externalSheet.SheetName
+ "' in bool '" + workbookName + "'.");
}
}
if (otherLastSheetIndex == -1)
{
// Reference to just one sheet
otherLastSheetIndex = otherFirstSheetIndex;
}
SheetRefEvaluator[] Evals = new SheetRefEvaluator[otherLastSheetIndex - otherFirstSheetIndex + 1];
for (int i = 0; i < Evals.Length; i++)
{
int otherSheetIndex = i + otherFirstSheetIndex;
Evals[i] = new SheetRefEvaluator(targetEvaluator, _tracker, otherSheetIndex);
}
return new SheetRangeEvaluator(otherFirstSheetIndex, otherLastSheetIndex, Evals);
}
/**
* @return <code>null</code> if either workbook or sheet is not found
*/
private SheetRefEvaluator CreateExternSheetRefEvaluator(String workbookName, String sheetName)
{
WorkbookEvaluator targetEvaluator;
if (workbookName == null)
{
targetEvaluator = _bookEvaluator;
}
else
{
if (sheetName == null)
{
throw new ArgumentException("sheetName must not be null if workbookName is provided");
}
try
{
targetEvaluator = _bookEvaluator.GetOtherWorkbookEvaluator(workbookName);
}
catch (WorkbookNotFoundException)
{
return null;
}
}
int otherSheetIndex = sheetName == null ? _sheetIndex : targetEvaluator.GetSheetIndex(sheetName);
if (otherSheetIndex < 0)
{
return null;
}
return new SheetRefEvaluator(targetEvaluator, _tracker, otherSheetIndex);
}
public SheetRangeEvaluator GetRefEvaluatorForCurrentSheet()
{
SheetRefEvaluator sre = new SheetRefEvaluator(_bookEvaluator, _tracker, _sheetIndex);
return new SheetRangeEvaluator(_sheetIndex, sre);
}
/**
* Resolves a cell or area reference dynamically.
* @param workbookName the name of the workbook Containing the reference. If <code>null</code>
* the current workbook is assumed. Note - to Evaluate formulas which use multiple workbooks,
* a {@link CollaboratingWorkbooksEnvironment} must be set up.
* @param sheetName the name of the sheet Containing the reference. May be <code>null</code>
* (when <c>workbookName</c> is also null) in which case the current workbook and sheet is
* assumed.
* @param refStrPart1 the single cell reference or first part of the area reference. Must not
* be <code>null</code>.
* @param refStrPart2 the second part of the area reference. For single cell references this
* parameter must be <code>null</code>
* @param isA1Style specifies the format for <c>refStrPart1</c> and <c>refStrPart2</c>.
* Pass <c>true</c> for 'A1' style and <c>false</c> for 'R1C1' style.
* TODO - currently POI only supports 'A1' reference style
* @return a {@link RefEval} or {@link AreaEval}
*/
public ValueEval GetDynamicReference(String workbookName, String sheetName, String refStrPart1,
String refStrPart2, bool isA1Style)
{
if (!isA1Style)
{
throw new Exception("R1C1 style not supported yet");
}
SheetRefEvaluator se = CreateExternSheetRefEvaluator(workbookName, sheetName);
if (se == null)
{
return ErrorEval.REF_INVALID;
}
SheetRangeEvaluator sre = new SheetRangeEvaluator(_sheetIndex, se);
// ugly typecast - TODO - make spReadsheet version more easily accessible
SpreadsheetVersion ssVersion = ((IFormulaParsingWorkbook)_workbook).GetSpreadsheetVersion();
NameType part1refType = ClassifyCellReference(refStrPart1, ssVersion);
switch (part1refType)
{
case NameType.BadCellOrNamedRange:
return ErrorEval.REF_INVALID;
case NameType.NamedRange:
IEvaluationName nm = ((IFormulaParsingWorkbook)_workbook).GetName(refStrPart1, _sheetIndex);
if (!nm.IsRange)
{
throw new Exception("Specified name '" + refStrPart1 + "' is not a range as expected.");
}
return _bookEvaluator.EvaluateNameFormula(nm.NameDefinition, this);
}
if (refStrPart2 == null)
{
// no ':'
switch (part1refType)
{
case NameType.Column:
case NameType.Row:
return ErrorEval.REF_INVALID;
case NameType.Cell:
CellReference cr = new CellReference(refStrPart1);
return new LazyRefEval(cr.Row, cr.Col, sre);
}
throw new InvalidOperationException("Unexpected reference classification of '" + refStrPart1 + "'.");
}
NameType part2refType = ClassifyCellReference(refStrPart1, ssVersion);
switch (part2refType)
{
case NameType.BadCellOrNamedRange:
return ErrorEval.REF_INVALID;
case NameType.NamedRange:
throw new Exception("Cannot Evaluate '" + refStrPart1
+ "'. Indirect Evaluation of defined names not supported yet");
}
if (part2refType != part1refType)
{
// LHS and RHS of ':' must be compatible
return ErrorEval.REF_INVALID;
}
int firstRow, firstCol, lastRow, lastCol;
switch (part1refType)
{
case NameType.Column:
firstRow = 0;
if (part2refType.Equals(NameType.Column))
{
lastRow = ssVersion.LastRowIndex;
firstCol = ParseRowRef(refStrPart1);
lastCol = ParseRowRef(refStrPart2);
}
else
{
lastRow = ssVersion.LastRowIndex;
firstCol = ParseColRef(refStrPart1);
lastCol = ParseColRef(refStrPart2);
}
break;
case NameType.Row:
// support of cell range in the form of integer:integer
firstCol = 0;
if (part2refType.Equals(NameType.Row))
{
firstRow = ParseColRef(refStrPart1);
lastRow = ParseColRef(refStrPart2);
lastCol = ssVersion.LastColumnIndex;
}
else
{
lastCol = ssVersion.LastColumnIndex;
firstRow = ParseRowRef(refStrPart1);
lastRow = ParseRowRef(refStrPart2);
}
break;
case NameType.Cell:
CellReference cr;
cr = new CellReference(refStrPart1);
firstRow = cr.Row;
firstCol = cr.Col;
cr = new CellReference(refStrPart2);
lastRow = cr.Row;
lastCol = cr.Col;
break;
default:
throw new InvalidOperationException("Unexpected reference classification of '" + refStrPart1 + "'.");
}
return new LazyAreaEval(firstRow, firstCol, lastRow, lastCol, sre);
}
private static int ParseRowRef(String refStrPart)
{
return CellReference.ConvertColStringToIndex(refStrPart);
}
private static int ParseColRef(String refStrPart)
{
return Int32.Parse(refStrPart, CultureInfo.InvariantCulture) - 1;
}
private static NameType ClassifyCellReference(String str, SpreadsheetVersion ssVersion)
{
int len = str.Length;
if (len < 1)
{
return NameType.BadCellOrNamedRange;
}
return CellReference.ClassifyCellReference(str, ssVersion);
}
public FreeRefFunction FindUserDefinedFunction(String functionName)
{
return _bookEvaluator.FindUserDefinedFunction(functionName);
}
public ValueEval GetRefEval(int rowIndex, int columnIndex)
{
SheetRangeEvaluator sre = GetRefEvaluatorForCurrentSheet();
return new LazyRefEval(rowIndex, columnIndex, sre);
}
public ValueEval GetRef3DEval(Ref3DPtg rptg)
{
SheetRangeEvaluator sre = CreateExternSheetRefEvaluator(rptg.ExternSheetIndex);
return new LazyRefEval(rptg.Row, rptg.Column, sre);
}
public ValueEval GetRef3DEval(Ref3DPxg rptg)
{
SheetRangeEvaluator sre = CreateExternSheetRefEvaluator(rptg.SheetName, rptg.LastSheetName, rptg.ExternalWorkbookNumber);
return new LazyRefEval(rptg.Row, rptg.Column, sre);
}
public ValueEval GetAreaEval(int firstRowIndex, int firstColumnIndex,
int lastRowIndex, int lastColumnIndex)
{
SheetRangeEvaluator sre = GetRefEvaluatorForCurrentSheet();
return new LazyAreaEval(firstRowIndex, firstColumnIndex, lastRowIndex, lastColumnIndex, sre);
}
public ValueEval GetArea3DEval(Area3DPtg aptg)
{
SheetRangeEvaluator sre = CreateExternSheetRefEvaluator(aptg.ExternSheetIndex);
return new LazyAreaEval(aptg.FirstRow, aptg.FirstColumn,
aptg.LastRow, aptg.LastColumn, sre);
}
public ValueEval GetArea3DEval(Area3DPxg aptg)
{
SheetRangeEvaluator sre = CreateExternSheetRefEvaluator(aptg.SheetName, aptg.LastSheetName, aptg.ExternalWorkbookNumber);
return new LazyAreaEval(aptg.FirstRow, aptg.FirstColumn,
aptg.LastRow, aptg.LastColumn, sre);
}
public ValueEval GetNameXEval(NameXPtg nameXPtg)
{
ExternalSheet externSheet = _workbook.GetExternalSheet(nameXPtg.SheetRefIndex);
if (externSheet == null || externSheet.WorkbookName == null)
{
// External reference to our own workbook's name
return GetLocalNameXEval(nameXPtg);
}
// Look it up for the external workbook
String workbookName = externSheet.WorkbookName;
ExternalName externName = _workbook.GetExternalName(
nameXPtg.SheetRefIndex,
nameXPtg.NameIndex
);
return GetExternalNameXEval(externName, workbookName);
}
public ValueEval GetNameXEval(NameXPxg nameXPxg)
{
ExternalSheet externSheet = _workbook.GetExternalSheet(nameXPxg.SheetName, null, nameXPxg.ExternalWorkbookNumber);
if (externSheet == null || externSheet.WorkbookName == null)
{
// External reference to our own workbook's name
return GetLocalNameXEval(nameXPxg);
}
// Look it up for the external workbook
String workbookName = externSheet.WorkbookName;
ExternalName externName = _workbook.GetExternalName(
nameXPxg.NameName,
nameXPxg.SheetName,
nameXPxg.ExternalWorkbookNumber
);
return GetExternalNameXEval(externName, workbookName);
}
private ValueEval GetLocalNameXEval(NameXPxg nameXPxg)
{
// Look up the sheet, if present
int sIdx = -1;
if (nameXPxg.SheetName != null)
{
sIdx = _workbook.GetSheetIndex(nameXPxg.SheetName);
}
// Is it a name or a function?
String name = nameXPxg.NameName;
IEvaluationName evalName = _workbook.GetName(name, sIdx);
if (evalName != null)
{
// Process it as a name
return new ExternalNameEval(evalName);
}
else
{
// Must be an external function
return new FunctionNameEval(name);
}
}
private ValueEval GetLocalNameXEval(NameXPtg nameXPtg)
{
String name = _workbook.ResolveNameXText(nameXPtg);
// Try to parse it as a name
int sheetNameAt = name.IndexOf('!');
IEvaluationName evalName = null;
if (sheetNameAt > -1)
{
// Sheet based name
String sheetName = name.Substring(0, sheetNameAt);
String nameName = name.Substring(sheetNameAt + 1);
evalName = _workbook.GetName(nameName, _workbook.GetSheetIndex(sheetName));
}
else
{
// Workbook based name
evalName = _workbook.GetName(name, -1);
}
if (evalName != null)
{
// Process it as a name
return new ExternalNameEval(evalName);
}
else
{
// Must be an external function
return new FunctionNameEval(name);
}
}
public int SheetIndex
{
get
{
return _sheetIndex;
}
}
// Fetch the workbook this refers to, and the name as defined with that
private ValueEval GetExternalNameXEval(ExternalName externName, String workbookName)
{
try
{
WorkbookEvaluator refWorkbookEvaluator = _bookEvaluator.GetOtherWorkbookEvaluator(workbookName);
IEvaluationName evaluationName = refWorkbookEvaluator.GetName(externName.Name, externName.Ix - 1);
if (evaluationName != null && evaluationName.HasFormula)
{
if (evaluationName.NameDefinition.Length > 1)
{
throw new Exception("Complex name formulas not supported yet");
}
// Need to Evaluate the reference in the context of the other book
OperationEvaluationContext refWorkbookContext = new OperationEvaluationContext(
refWorkbookEvaluator, refWorkbookEvaluator.Workbook, -1, -1, -1, _tracker);
Ptg ptg = evaluationName.NameDefinition[0];
if (ptg is Ref3DPtg)
{
Ref3DPtg ref3D = (Ref3DPtg)ptg;
return refWorkbookContext.GetRef3DEval(ref3D);
}
else if (ptg is Ref3DPxg)
{
Ref3DPxg ref3D = (Ref3DPxg)ptg;
return refWorkbookContext.GetRef3DEval(ref3D);
}
else if (ptg is Area3DPtg)
{
Area3DPtg area3D = (Area3DPtg)ptg;
return refWorkbookContext.GetArea3DEval(area3D);
}
else if (ptg is Area3DPxg)
{
Area3DPxg area3D = (Area3DPxg)ptg;
return refWorkbookContext.GetArea3DEval(area3D);
}
}
return ErrorEval.REF_INVALID;
}
catch (WorkbookNotFoundException)
{
return ErrorEval.REF_INVALID;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Reflection;
using NUnit.Framework;
namespace NUnitLite
{
public class TestSuite : ITest
{
#region Instance Variables
private string name;
private string fullName;
private RunState runState = RunState.Runnable;
private string ignoreReason;
private IDictionary properties = new Hashtable();
private ArrayList tests = new ArrayList(10);
#endregion
#region Constructors
public TestSuite(string name)
{
this.name = name;
}
public TestSuite(Type type)
{
this.name = type.Name;
this.fullName = type.FullName;
object[] attrs = type.GetCustomAttributes( typeof(PropertyAttribute), true);
foreach (PropertyAttribute attr in attrs)
foreach( DictionaryEntry entry in attr.Properties )
this.Properties[entry.Key] = entry.Value;
IgnoreAttribute ignore = (IgnoreAttribute)Reflect.GetAttribute(type, typeof(IgnoreAttribute));
if (ignore != null)
{
this.runState = RunState.Ignored;
this.ignoreReason = ignore.Reason;
}
if ( !InvalidTestSuite(type) )
{
foreach (MethodInfo method in type.GetMethods())
{
if (TestCase.IsTestMethod(method))
this.AddTest(new TestCase(method));
//{
// ITest test = TestCase.HasValidSignature(method)
// ? (ITest)new TestCase(method)
// : (ITest)new InvalidTestCase(method.Name,
// "Test methods must have signature void MethodName()");
// this.AddTest(test);
//}
}
}
}
#endregion
#region Properties
public string Name
{
get { return name; }
}
public string FullName
{
get { return fullName; }
}
public RunState RunState
{
get { return runState; }
}
public string IgnoreReason
{
get { return ignoreReason; }
}
public IDictionary Properties
{
get { return properties; }
}
public int TestCaseCount
{
get
{
int count = 0;
foreach (ITest test in this.tests)
count += test.TestCaseCount;
return count;
}
}
public IList Tests
{
get { return tests; }
}
#endregion
#region Public Methods
public TestResult Run()
{
return Run(new NullListener());
}
public TestResult Run(ITestListener listener)
{
int count = 0, failures = 0, errors = 0;
listener.TestStarted(this);
TestResult result = new TestResult(this);
switch (this.RunState)
{
case RunState.NotRunnable:
result.Error(this.IgnoreReason);
break;
case RunState.Ignored:
result.NotRun(this.IgnoreReason);
break;
case RunState.Runnable:
foreach (ITest test in tests)
{
++count;
TestResult r = test.Run(listener);
result.AddResult(r);
switch (r.ResultState)
{
case ResultState.Error:
++errors;
break;
case ResultState.Failure:
++failures;
break;
default:
break;
}
}
if (count == 0)
result.NotRun("Class has no tests");
else if (errors > 0 || failures > 0)
result.Failure("One or more component tests failed");
else
result.Success();
break;
}
listener.TestFinished(result);
return result;
}
public void AddTest(ITest test)
{
tests.Add(test);
}
#endregion
#region Private Methods
private bool InvalidTestSuite(Type type)
{
if (!Reflect.HasConstructor(type))
{
this.runState = RunState.NotRunnable;
this.ignoreReason = string.Format( "Class {0} has no default constructor", type.Name);
return true;
}
return false;
}
#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.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
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>
/// ServerUsagesOperations operations.
/// </summary>
internal partial class ServerUsagesOperations : IServiceOperations<SqlManagementClient>, IServerUsagesOperations
{
/// <summary>
/// Initializes a new instance of the ServerUsagesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ServerUsagesOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Returns server usages.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </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<IEnumerable<ServerUsage>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByServer", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/usages").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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<IEnumerable<ServerUsage>>();
_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<ServerUsage>>(_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;
}
}
}
| |
// 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.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketOptionNameTest
{
private static bool SocketsReuseUnicastPortSupport
{
get
{
return Capability.SocketsReuseUnicastPortSupport().HasValue &&
Capability.SocketsReuseUnicastPortSupport().Value;
}
}
private static bool NoSocketsReuseUnicastPortSupport
{
get
{
return Capability.SocketsReuseUnicastPortSupport().HasValue &&
!Capability.SocketsReuseUnicastPortSupport().Value;
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketGetOption_NoSocketsReuseUnicastPortSupport_Throws()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.Throws<SocketException>(() =>
socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort));
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketGetOption_SocketsReuseUnicastPortSupport_OptionIsZero()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(0, optionValue);
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketSetOption_NoSocketsReuseUnicastPortSupport_Throws()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.Throws<SocketException>(() =>
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1));
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SocketsReuseUnicastPortSupport))]
public void ReuseUnicastPort_CreateSocketSetOptionToZeroAndGetOption_SocketsReuseUnicastPortSupport_OptionIsZero()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 0);
int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(0, optionValue);
}
// TODO: Issue #4887
// The socket option 'ReuseUnicastPost' only works on Windows 10 systems. In addition, setting the option
// is a no-op unless specialized network settings using PowerShell configuration are first applied to the
// machine. This is currently difficult to test in the CI environment. So, this ests will be disabled for now
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(4887)]
public void ReuseUnicastPort_CreateSocketSetOptionToOneAndGetOption_SocketsReuseUnicastPortSupport_OptionIsOne()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1);
int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort);
Assert.Equal(1, optionValue);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void MulticastOption_CreateSocketSetGetOption_GroupAndInterfaceIndex_SetSucceeds_GetThrows()
{
int interfaceIndex = 0;
IPAddress groupIp = IPAddress.Parse("239.1.2.3");
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(groupIp, interfaceIndex));
Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership));
}
}
[OuterLoop] // TODO: Issue #11345
public async Task MulticastInterface_Set_AnyInterface_Succeeds()
{
// On all platforms, index 0 means "any interface"
await MulticastInterface_Set_Helper(0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // see comment below
public async Task MulticastInterface_Set_Loopback_Succeeds()
{
// On Windows, we can apparently assume interface 1 is "loopback." On other platforms, this is not a
// valid assumption. We could maybe use NetworkInterface.LoopbackInterfaceIndex to get the index, but
// this would introduce a dependency on System.Net.NetworkInformation, which depends on System.Net.Sockets,
// which is what we're testing here.... So for now, we'll just assume "loopback == 1" and run this on
// Windows only.
await MulticastInterface_Set_Helper(1);
}
private async Task MulticastInterface_Set_Helper(int interfaceIndex)
{
IPAddress multicastAddress = IPAddress.Parse("239.1.2.3");
string message = "hello";
int port;
using (Socket receiveSocket = CreateBoundUdpSocket(out port),
sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
receiveSocket.ReceiveTimeout = 1000;
receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex));
// https://github.com/Microsoft/BashOnWindows/issues/990
if (!PlatformDetection.IsWindowsSubsystemForLinux)
{
sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex));
}
var receiveBuffer = new byte[1024];
var receiveTask = receiveSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), SocketFlags.None);
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port));
}
int bytesReceived = await receiveTask;
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);
Assert.Equal(receivedMessage, message);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void MulticastInterface_Set_InvalidIndex_Throws()
{
int interfaceIndex = 31415;
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<SocketException>(() =>
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex)));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // In WSL, the connect() call fails immediately.
[InlineData(false)]
[InlineData(true)]
public void FailedConnect_GetSocketOption_SocketOptionNameError(bool simpleGet)
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false })
{
// Fail a Connect
using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); // bind but don't listen
Assert.ThrowsAny<Exception>(() => client.Connect(server.LocalEndPoint));
}
// Verify via Select that there's an error
const int FailedTimeout = 10 * 1000 * 1000; // 10 seconds
var errorList = new List<Socket> { client };
Socket.Select(null, null, errorList, FailedTimeout);
Assert.Equal(1, errorList.Count);
// Get the last error and validate it's what's expected
int errorCode;
if (simpleGet)
{
errorCode = (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
}
else
{
byte[] optionValue = new byte[sizeof(int)];
client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, optionValue);
errorCode = BitConverter.ToInt32(optionValue, 0);
}
Assert.Equal((int)SocketError.ConnectionRefused, errorCode);
// Then get it again
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// The Windows implementation doesn't clear the error code after retrieved.
// https://github.com/dotnet/corefx/issues/8464
Assert.Equal(errorCode, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
else
{
// The Unix implementation matches the getsockopt and MSDN docs and clears the error code as part of retrieval.
Assert.Equal((int)SocketError.Success, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
}
}
// Create an Udp Socket and binds it to an available port
private static Socket CreateBoundUdpSocket(out int localPort)
{
Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// sending a message will bind the socket to an available port
string sendMessage = "dummy message";
int port = 54320;
IPAddress multicastAddress = IPAddress.Parse("239.1.1.1");
receiveSocket.SendTo(Encoding.UTF8.GetBytes(sendMessage), new IPEndPoint(multicastAddress, port));
localPort = (receiveSocket.LocalEndPoint as IPEndPoint).Port;
return receiveSocket;
}
[Theory]
[InlineData(null, null, null, true)]
[InlineData(null, null, false, true)]
[InlineData(null, false, false, true)]
[InlineData(null, true, false, true)]
[InlineData(null, true, true, false)]
[InlineData(true, null, null, true)]
[InlineData(true, null, false, true)]
[InlineData(true, null, true, true)]
[InlineData(true, false, null, true)]
[InlineData(true, false, false, true)]
[InlineData(true, false, true, true)]
public void ReuseAddress(bool? exclusiveAddressUse, bool? firstSocketReuseAddress, bool? secondSocketReuseAddress, bool expectFailure)
{
using (Socket a = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
if (exclusiveAddressUse.HasValue)
{
a.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, exclusiveAddressUse.Value);
}
if (firstSocketReuseAddress.HasValue)
{
a.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, firstSocketReuseAddress.Value);
}
a.Bind(new IPEndPoint(IPAddress.Loopback, 0));
using (Socket b = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
if (secondSocketReuseAddress.HasValue)
{
b.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, secondSocketReuseAddress.Value);
}
if (expectFailure)
{
Assert.ThrowsAny<SocketException>(() => b.Bind(a.LocalEndPoint));
}
else
{
b.Bind(a.LocalEndPoint);
}
}
}
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // ExclusiveAddressUse option is a Windows-specific option (when set to "true," tells Windows not to allow reuse of same local address)
[InlineData(false, null, null, true)]
[InlineData(false, null, false, true)]
[InlineData(false, false, null, true)]
[InlineData(false, false, false, true)]
[InlineData(false, true, null, true)]
[InlineData(false, true, false, true)]
[InlineData(false, true, true, false)]
public void ReuseAddress_Windows(bool? exclusiveAddressUse, bool? firstSocketReuseAddress, bool? secondSocketReuseAddress, bool expectFailure)
{
ReuseAddress(exclusiveAddressUse, firstSocketReuseAddress, secondSocketReuseAddress, expectFailure);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // SetIPProtectionLevel not supported on Unix
[InlineData(IPProtectionLevel.EdgeRestricted, AddressFamily.InterNetwork, SocketOptionLevel.IP)]
[InlineData(IPProtectionLevel.Restricted, AddressFamily.InterNetwork, SocketOptionLevel.IP)]
[InlineData(IPProtectionLevel.Unrestricted, AddressFamily.InterNetwork, SocketOptionLevel.IP)]
[InlineData(IPProtectionLevel.EdgeRestricted, AddressFamily.InterNetworkV6, SocketOptionLevel.IPv6)]
[InlineData(IPProtectionLevel.Restricted, AddressFamily.InterNetworkV6, SocketOptionLevel.IPv6)]
[InlineData(IPProtectionLevel.Unrestricted, AddressFamily.InterNetworkV6, SocketOptionLevel.IPv6)]
public void SetIPProtectionLevel_Windows(IPProtectionLevel level, AddressFamily family, SocketOptionLevel optionLevel)
{
using (var socket = new Socket(family, SocketType.Stream, ProtocolType.Tcp))
{
socket.SetIPProtectionLevel(level);
int result = (int)socket.GetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel);
Assert.Equal(result, (int)level);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // SetIPProtectionLevel not supported on Unix
[InlineData(IPProtectionLevel.EdgeRestricted, AddressFamily.InterNetwork)]
[InlineData(IPProtectionLevel.Restricted, AddressFamily.InterNetwork)]
[InlineData(IPProtectionLevel.Unrestricted, AddressFamily.InterNetwork)]
[InlineData(IPProtectionLevel.EdgeRestricted, AddressFamily.InterNetworkV6)]
[InlineData(IPProtectionLevel.Restricted, AddressFamily.InterNetworkV6)]
[InlineData(IPProtectionLevel.Unrestricted, AddressFamily.InterNetworkV6)]
public void SetIPProtectionLevel_Unix(IPProtectionLevel level, AddressFamily family)
{
using (var socket = new Socket(family, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => socket.SetIPProtectionLevel(level));
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SetIPProtectionLevel_ArgumentException(AddressFamily family)
{
using (var socket = new Socket(family, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<ArgumentException>("level", () => socket.SetIPProtectionLevel(IPProtectionLevel.Unspecified));
}
}
}
}
| |
using Lewis.Xml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace Lewis.OptionsDialog
{
public partial class OptionsDialog : Form
{
private TreeNode topLevel = new TreeNode();
public EventHandler<OptionsClosingEvent> DialogClosing;
private string _values = string.Empty;
private ToolTip toolTip = new ToolTip();
public OptionsDialog()
{
// Set up the delays for the ToolTip.
toolTip.AutoPopDelay = 5000;
toolTip.InitialDelay = 500;
toolTip.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip.ShowAlways = true;
InitializeComponent();
this.splitContainer1.Panel2.Controls.Clear();
this.Load += new EventHandler(OptionsDialog_Load);
this.FormClosing += new FormClosingEventHandler(OptionsDialog_FormClosing);
this.treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
CreateDynamicControls();
}
public OptionsDialog(string values)
{
// Set up the delays for the ToolTip.
toolTip.AutoPopDelay = 5000;
toolTip.InitialDelay = 500;
toolTip.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip.ShowAlways = true;
toolTip.UseFading = true;
toolTip.IsBalloon = true;
_values = values;
InitializeComponent();
this.splitContainer1.Panel2.Controls.Clear();
this.Load += new EventHandler(OptionsDialog_Load);
this.FormClosing += new FormClosingEventHandler(OptionsDialog_FormClosing);
this.treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
CreateDynamicControls();
SetControlsProperties();
}
public string ControlsValues
{
get { return _values; }
set
{
_values = value;
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
// change panels to current node;
if (e.Node.Tag != null && typeof(TableLayoutPanel).IsInstanceOfType(e.Node.Tag))
{
this.splitContainer1.Panel2.Controls.Clear();
Panel p = (Panel)e.Node.Tag;
this.splitContainer1.Panel2.Controls.Add(p);
p.Dock = DockStyle.Fill;
p.Visible = true;
toolTip.Active = true;
}
}
private void OptionsDialog_Load(object sender, EventArgs e)
{
// Sanity check 521, 325
if (this.Width < 200 || this.Height < 100)
{
this.Height = 325;
this.Width = 521;
}
}
private void OptionsDialog_FormClosing(object sender, FormClosingEventArgs e)
{
// serialize the child controls values and save if OK button pressed
string values = string.Empty;
if (this.DialogResult == DialogResult.OK)
{
values = ParseOptionsControls();
}
OptionsClosingEvent args = new OptionsClosingEvent(this.DialogResult, values);
EventHandler<OptionsClosingEvent> handler = DialogClosing;
if (handler != null)
{
// raises the event.
handler(this, args);
}
}
private void btnOk_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void CreateDynamicControls()
{
string xmlControls = ResourceReader.ReadFromResource("Lewis.SST.Forms.Options.optionsControls.xml");
if (!xmlControls.Equals(string.Empty))
{
XmlDocument xControls = new XmlDocument();
xControls.LoadXml(xmlControls);
string name = xControls.SelectSingleNode("/options/settings").Attributes["name"].Value;
topLevel.Text = name;
treeView1.Nodes.Add(topLevel);
XmlNodeList xnl = xControls.SelectNodes("/options/settings/panel");
if (xnl != null)
{
foreach (XmlNode node in xnl)
{
// add new panel for each new tree node
ColumnStyle cstyle = new ColumnStyle(SizeType.Percent);
cstyle.Width = 50; // 50%
TreeNode tn = new TreeNode(node.Attributes["name"].Value);
TableLayoutPanel p = new TableLayoutPanel();
p.AutoSize = true;
p.AutoScroll = true;
p.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset;
p.Padding = new Padding(1, 1, 4, 5);
p.Name = tn.Text;
p.Anchor = AnchorStyles.None;
p.ColumnStyles.Add(cstyle);
p.ColumnCount = 2;
p.Visible = false;
XmlNodeList xnlControls = node.SelectNodes("./controls/control");
for (int ii = 0; ii < xnlControls.Count; ii++)
{
XmlNode xnCtrl = (XmlNode)xnlControls[ii];
string type = xnCtrl.Attributes["type"].Value;
string label = xnCtrl.Attributes["label"].Value;
string ctrlName = xnCtrl.Attributes["name"].Value;
string tooTip = xnCtrl.Attributes["tooltip"].Value;
Type t = OptionValues.GetTypeFromAppDomain(type, "System.Windows.Forms");
Object obj = Activator.CreateInstance(t);
((Control)obj).Name = ctrlName;
if (type.ToLower().Equals("textbox"))
{
((TextBox)obj).MaxLength = 255;
((TextBox)obj).ScrollBars = ScrollBars.Horizontal;
}
toolTip.SetToolTip((Control)obj, tooTip);
Label lbl = new Label();
lbl.Padding = new Padding(2, 6, 0, 0);
lbl.AutoSize = true;
lbl.Text = label;
p.Controls.Add((Control)lbl, 0, ii);
p.Controls.Add((Control)obj, 1, ii);
}
tn.Tag = p;
topLevel.Nodes.Add(tn);
}
}
treeView1.ExpandAll();
}
}
private void SetPropertyValue(object obj, string propName, object val)
{
PropertyDescriptor prop = TypeDescriptor.GetProperties(obj.GetType())[propName];
if (null != prop)
{
// Check for string type
if (prop.PropertyType.IsAssignableFrom(val.GetType()))
{
// Just set the value
prop.SetValue(obj, val);
}
else
{
// Need to do type conversion - use a type converter
TypeConverter tc = TypeDescriptor.GetConverter(prop.PropertyType);
object newVal = null;
if ((null != tc) && (tc.CanConvertFrom(typeof(string))))
{
newVal = tc.ConvertFrom(val);
if (null != newVal)
{
// Conversion worked, set value
prop.SetValue(obj, newVal);
}
}
}
}
else if (val.GetType() == typeof(string))
{
// Maybe an event?
//SetEventValue(obj, propName, val as string);
}
}
private void SetControlsProperties()
{
if (_values != null && _values.Length > 0)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(_values);
XmlNodeList xnl = xDoc.SelectNodes("/options/settings/panel");
if (xnl != null)
{
foreach (XmlNode xn in xnl)
{
foreach (TreeNode tn in topLevel.Nodes)
{
if (tn.Text.ToLower().Equals(xn.Attributes["name"].Value.ToLower()))
{
if (tn.Tag != null && typeof(TableLayoutPanel).IsInstanceOfType(tn.Tag))
{
foreach (Control c in ((TableLayoutPanel)tn.Tag).Controls)
{
if (!typeof(Label).IsInstanceOfType(c))
{
XmlNode ctrl = xn.SelectSingleNode("/options/settings/panel/controls/control[@name='" + c.Name + "']");
if (ctrl != null)
{
if (ctrl.InnerText != null && ctrl.InnerText.Length > 0)
{
string[] ctrlItems = ctrl.InnerText.Split(':');
string property = ctrlItems.Length > 0 ? ctrlItems[0].Trim() : null;
string value = null;
if ( ctrlItems.Length > 1 )
{
for (int ii = 1; ii < ctrlItems.Length ; ii++)
{
bool addColon = ii < ctrlItems.Length - 1;
value += ctrlItems[ii].Trim() + (addColon ? ":" : "");
}
}
SetPropertyValue(c, property, value);
}
}
}
}
}
}
}
}
}
}
}
private string ParseOptionsControls()
{
XmlDocument xDoc = new XmlDocument();
XmlElement options = xDoc.CreateElement("options");
xDoc.AppendChild(options);
XmlElement settings = xDoc.CreateElement("settings");
options.AppendChild(settings);
foreach (TreeNode tn in topLevel.Nodes)
{
if (tn.Tag != null && typeof(TableLayoutPanel).IsInstanceOfType(tn.Tag))
{
XmlElement panel = xDoc.CreateElement("panel");
panel.SetAttribute("name", tn.Text);
settings.AppendChild(panel);
XmlElement controls = xDoc.CreateElement("controls");
panel.AppendChild(controls);
foreach (Control c in ((TableLayoutPanel)tn.Tag).Controls)
{
if (!typeof(Label).IsInstanceOfType(c))
{
int firstPos = c.ToString().IndexOf(',');
int lastPos = c.ToString().Substring(0, firstPos).LastIndexOf('.');
string ctrlType = c.ToString().Substring(0, firstPos).Substring(lastPos + 1).Trim();
string ctrlValue = string.Empty;
if (ctrlType.ToLower().Equals("textbox"))
{
ctrlValue = "Text: " + c.Text;
}
else
{
ctrlValue = c.ToString().Substring(firstPos + 1).Trim();
}
XmlElement ctrl = xDoc.CreateElement("control");
ctrl.SetAttribute("name", c.Name);
ctrl.SetAttribute("type", ctrlType);
ctrl.InnerText = ctrlValue;
controls.AppendChild(ctrl);
}
}
}
}
XmlDeclaration declare = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
xDoc.PrependChild(declare);
_values = xDoc.OuterXml;
return _values;
}
}
public class OptionsClosingEvent : EventArgs
{
private DialogResult _dr;
private string _values;
public OptionsClosingEvent(DialogResult dr, string values)
{
_dr = dr;
_values = values;
}
public DialogResult Response
{
get { return _dr; }
}
public string Values
{
get { return _values; }
}
}
public static class OptionValues
{
public static Type GetTypeFromAppDomain(string name, string ns)
{
Type type = null;
string fullName = ns + "." + name;
Assembly system = null;
// Check if loaded in AppDomain
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
// See if the assembly is already loaded
type = assembly.GetType(fullName);
// If found, then done
if (type != null)
break;
// Check for System assembly
if ("mscorlib" == assembly.GetName().Name.ToLower())
system = assembly;
}
// If not found, then check System
if ((null == type) && (null != system))
{
type = system.GetType("System." + name);
}
return type;
}
public static object GetValue(string Name, string settings)
{
string value = null;
object retVal = null;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(settings);
XmlNode ctrl = xDoc.SelectSingleNode("/options/settings/panel/controls/control[@name='" + Name + "']");
if (ctrl != null)
{
string[] ctrlItems = ctrl.InnerText.Split(':');
if (ctrlItems != null)
{
string type = ctrl.Attributes["type"].Value;
if (type != null)
{
string property = ctrlItems.Length > 0 ? ctrlItems[0].Trim() : null;
if (ctrlItems.Length > 1)
{
for (int ii = 1; ii < ctrlItems.Length; ii++)
{
bool addColon = ii < ctrlItems.Length - 1;
value += ctrlItems[ii].Trim() + (addColon ? ":" : "");
}
}
Type t = OptionValues.GetTypeFromAppDomain(type, "System.Windows.Forms");
if (t != null)
{
TypeConverter tc = TypeDescriptor.GetConverter(t.GetProperty(property).PropertyType);
if (tc != null && tc.CanConvertFrom(typeof(string)))
{
retVal = tc.ConvertFrom(value);
}
}
}
}
}
return retVal == null ? value : retVal;
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Reporting.Rdl.Utility;
namespace Reporting.Rdl
{
///<summary>
/// DataRegion base class definition and processing.
/// Warning if you inherit from DataRegion look at Expression.cs first.
///</summary>
[Serializable]
internal class DataRegion : ReportItem
{
bool _KeepTogether; // Indicates the entire data region (all
// repeated sections) should be kept
// together on one page if possible.
Expression _NoRows; // (string) Message to display in the DataRegion
// (instead of the region layout) when
// no rows of data are available.
// Note: Style information on the data region applies to this text
string _DataSetName; // Indicates which data set to use for this data region.
//Mandatory for top level DataRegions
//(not contained within another
//DataRegion) if there is not exactly
//one data set in the report. If there is
//exactly one data set in the report, the
//data region uses that data set. (Note:
//If there are zero data sets in the
//report, data regions can not be used,
//as there is no valid DataSetName to
//use) Ignored for DataRegions that are
//not top level.
DataSetDefn _DataSetDefn; // resolved data set name;
bool _PageBreakAtStart; // Indicates the report should page break
// at the start of the data region.
bool _PageBreakAtEnd; // Indicates the report should page break
// at the end of the data region.
Filters _Filters; // Filters to apply to each row of data in the data region.
DataRegion _ParentDataRegion; // when DataRegions are nested; the nested regions have the parent set
internal DataRegion(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode)
{
_KeepTogether=false;
_NoRows=null;
_DataSetName=null;
_DataSetDefn=null;
_PageBreakAtStart=false;
_PageBreakAtEnd=false;
_Filters=null;
}
internal bool DataRegionElement(XmlNode xNodeLoop)
{
switch (xNodeLoop.Name)
{
case "KeepTogether":
_KeepTogether = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "NoRows":
_NoRows = new Expression(OwnerReport, this, xNodeLoop, ExpressionType.String);
break;
case "DataSetName":
_DataSetName = xNodeLoop.InnerText;
break;
case "PageBreakAtStart":
_PageBreakAtStart = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "PageBreakAtEnd":
_PageBreakAtEnd = Conversion.ToBoolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "Filters":
_Filters = new Filters(OwnerReport, this, xNodeLoop);
break;
default: // Will get many that are handled by the specific
// type of data region: ie list,chart,matrix,table
if (ReportItemElement(xNodeLoop)) // try at ReportItem level
break;
return false;
}
return true;
}
// Handle parsing of function in final pass
override internal void FinalPass()
{
base.FinalPass();
if (this is Table)
{ // Grids don't have any data responsibilities
Table t = this as Table;
if (t.IsGrid)
return;
}
// DataRegions aren't allowed in PageHeader or PageFooter;
if (this.InPageHeaderOrFooter())
OwnerReport.rl.LogError(8, String.Format("The DataRegion '{0}' is not allowed in a PageHeader or PageFooter", this.Name == null? "unknown": Name.Nm) );
ResolveNestedDataRegions();
if (_ParentDataRegion != null) // when nested we use the dataset of the parent
{
_DataSetDefn = _ParentDataRegion.DataSetDefn;
}
else if (_DataSetName != null)
{
if (OwnerReport.DataSetsDefn != null)
_DataSetDefn = (DataSetDefn) OwnerReport.DataSetsDefn.Items[_DataSetName];
if (_DataSetDefn == null)
{
OwnerReport.rl.LogError(8, String.Format("DataSetName '{0}' not specified in DataSets list.", _DataSetName));
}
}
else
{ // No name but maybe we can default to a single Dataset
if (_DataSetDefn == null && OwnerReport.DataSetsDefn != null &&
OwnerReport.DataSetsDefn.Items.Count == 1)
{
foreach (DataSetDefn d in OwnerReport.DataSetsDefn.Items.Values)
{
_DataSetDefn = d;
break; // since there is only 1 this will obtain it
}
}
if (_DataSetDefn == null)
OwnerReport.rl.LogError(8, string.Format("{0} must specify a DataSetName.",this.Name == null? "DataRegions": this.Name.Nm));
}
if (_NoRows != null)
_NoRows.FinalPass();
if (_Filters != null)
_Filters.FinalPass();
return;
}
void ResolveNestedDataRegions()
{
ReportLink rl = this.Parent;
while (rl != null)
{
if (rl is DataRegion)
{
this._ParentDataRegion = rl as DataRegion;
break;
}
rl = rl.Parent;
}
return;
}
override internal void Run(IPresent ip, Row row)
{
base.Run(ip, row);
}
internal void RunPageRegionBegin(Pages pgs)
{
if (this.TC == null && this.PageBreakAtStart && !pgs.CurrentPage.IsEmpty())
{ // force page break at beginning of dataregion
pgs.NextOrNew();
pgs.CurrentPage.YOffset = OwnerReport.TopOfPage;
}
}
internal void RunPageRegionEnd(Pages pgs)
{
if (this.TC == null && this.PageBreakAtEnd && !pgs.CurrentPage.IsEmpty())
{ // force page break at beginning of dataregion
pgs.NextOrNew();
pgs.CurrentPage.YOffset = OwnerReport.TopOfPage;
}
}
internal bool AnyRows(IPresent ip, Rows data)
{
if (data == null || data.Data == null ||
data.Data.Count <= 0)
{
string msg;
if (this.NoRows != null)
msg = this.NoRows.EvaluateString(ip.Report(), null);
else
msg = null;
ip.DataRegionNoRows(this, msg);
return false;
}
return true;
}
internal bool AnyRowsPage(Pages pgs, Rows data)
{
if (data != null && data.Data != null &&
data.Data.Count > 0)
return true;
string msg;
if (this.NoRows != null)
msg = this.NoRows.EvaluateString(pgs.Report, null);
else
msg = null;
if (msg == null)
return false;
// OK we have a message we need to put out
RunPageRegionBegin(pgs); // still perform page break if needed
PageText pt = new PageText(msg);
SetPagePositionAndStyle(pgs.Report, pt, null);
if (pt.SI.BackgroundImage != null)
pt.SI.BackgroundImage.H = pt.H; // and in the background image
pgs.CurrentPage.AddObject(pt);
RunPageRegionEnd(pgs); // perform end page break if needed
SetPagePositionEnd(pgs, pt.Y + pt.H);
return false;
}
internal Rows GetFilteredData(Report rpt, Row row)
{
try
{
Rows data;
if (this._Filters == null)
{
if (this._ParentDataRegion == null)
{
data = DataSetDefn.Query.GetMyData(rpt);
return data == null? null: new Rows(rpt, data); // We need to copy in case DataSet is shared by multiple DataRegions
}
else
return GetNestedData(rpt, row);
}
if (this._ParentDataRegion == null)
{
data = DataSetDefn.Query.GetMyData(rpt);
if (data != null)
data = new Rows(rpt, data);
}
else
data = GetNestedData(rpt, row);
if (data == null)
return null;
List<Row> ar = new List<Row>();
foreach (Row r in data.Data)
{
if (_Filters.Apply(rpt, r))
ar.Add(r);
}
ar.TrimExcess();
data.Data = ar;
_Filters.ApplyFinalFilters(rpt, data, true);
// Adjust the rowcount
int rCount = 0;
foreach (Row r in ar)
{
r.RowNumber = rCount++;
}
return data;
}
catch (Exception e)
{
this.OwnerReport.rl.LogError(8, e.Message);
return null;
}
}
Rows GetNestedData(Report rpt, Row row)
{
if (row == null)
return null;
ReportLink rl = this.Parent;
while (rl != null)
{
if (rl is TableGroup || rl is List || rl is MatrixCell)
break;
rl = rl.Parent;
}
if (rl == null)
return null; // should have been caught as an error
Grouping g=null;
if (rl is TableGroup)
{
TableGroup tg = rl as TableGroup;
g = tg.Grouping;
}
else if (rl is List)
{
List l = rl as List;
g = l.Grouping;
}
else if (rl is MatrixCell)
{
MatrixCellEntry mce = this.GetMC(rpt);
return new Rows(rpt, mce.Data);
}
if (g == null)
return null;
GroupEntry ge = row.R.CurrentGroups[g.GetIndex(rpt)];
return new Rows(rpt, row.R, ge.StartRow, ge.EndRow, null);
}
internal void DataRegionFinish()
{
// All dataregion names need to be saved!
if (this.Name != null)
{
try
{
OwnerReport.LUAggrScope.Add(this.Name.Nm, this); // add to referenceable regions
}
catch // wish duplicate had its own exception
{
OwnerReport.rl.LogError(8, "Duplicate name '" + this.Name.Nm + "'.");
}
}
return;
}
internal bool KeepTogether
{
get { return _KeepTogether; }
set { _KeepTogether = value; }
}
internal Expression NoRows
{
get { return _NoRows; }
set { _NoRows = value; }
}
internal string DataSetName
{
get { return _DataSetName; }
set { _DataSetName = value; }
}
internal DataSetDefn DataSetDefn
{
get { return _DataSetDefn; }
set { _DataSetDefn = value; }
}
internal bool PageBreakAtStart
{
get { return _PageBreakAtStart; }
set { _PageBreakAtStart = value; }
}
internal bool PageBreakAtEnd
{
get { return _PageBreakAtEnd; }
set { _PageBreakAtEnd = value; }
}
internal Filters Filters
{
get { return _Filters; }
set { _Filters = value; }
}
}
}
| |
#region Namespaces
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml;
using Epi;
#endregion //Namespaces
namespace Epi.Fields
{
/// <summary>
/// Related view field
/// </summary>
public class RelatedViewField : FieldWithoutSeparatePrompt, IFieldWithCheckCodeClick //RenderableField
{
#region Private Members
private XmlElement viewElement;
private XmlElement fieldElement;
private XmlNode fieldNode;
private string condition = string.Empty;
private bool shouldReturnToParent;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">The page the field belongs to</param>
public RelatedViewField(Page page)
: base(page)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">The view the field belongs to</param>
public RelatedViewField(View view)
: base(view)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">The page the field belongs to</param>
/// <param name="viewElement">Xml Element representation of Related View Field</param>
public RelatedViewField(Page page, XmlElement viewElement)
: base(page)
{
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">The view the field belongs to</param>
/// <param name="fieldNode"></param>
public RelatedViewField(View view, XmlNode fieldNode)
: base(view)
{
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
/// <summary>
/// Load a Related View Field from a <see cref="System.Data.DataRow"/>
/// </summary>
/// <param name="row"></param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
condition = row["RelateCondition"].ToString();
//checkCodeBefore = row["ControlBeforeCheckCode"].ToString();
//checkCodeAfter = row["ControlAfterCheckCode"].ToString();
shouldReturnToParent = (bool)row["ShouldReturnToParent"];
if (row["RelatedViewId"] != System.DBNull.Value)
{
relatedViewID = (int)row["RelatedViewId"];
}
}
public RelatedViewField Clone()
{
RelatedViewField clone = (RelatedViewField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
#endregion
#region Public Events
/// <summary>
/// Occurs when a user requests to see the related view of this field
/// </summary>
public event ChildViewRequestedEventHandler ChildViewRequested;
#endregion
#region Public Properties
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.Relate;
}
}
/// <summary>
/// Gets the related view of the field
/// </summary>
public View ChildView
{
get
{
return GetMetadata().GetChildView(this);
}
}
/// <summary>
/// Gets/sets the condition for going to related view
/// </summary>
public string Condition
{
get
{
return (condition);
}
set
{
condition = value;
}
}
/// <summary>
/// Gets/sets whether the related view should return to its parent
/// </summary>
public bool ShouldReturnToParent
{
get
{
return (shouldReturnToParent);
}
set
{
shouldReturnToParent = value;
}
}
private int relatedViewID;
/// <summary>
/// Id of view list as related to this field
/// </summary>
public int RelatedViewID
{
get { return relatedViewID; }
set { relatedViewID = value; }
}
//isu6 - Implementing checkcode for Related view field.
/// <summary>
/// CheckCode After property for all DropDown list fields
/// </summary>
public string CheckCodeAfter
{
get
{
return (checkCodeAfter);
}
set
{
checkCodeAfter = value;
}
}
/// <summary>
/// CheckCode Before property for all DropDown list fields
/// </summary>
public string CheckCodeClick
{
get
{
return (checkCodeBefore);
}
set
{
checkCodeBefore = value;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Check Code After member variable
/// </summary>
protected string checkCodeAfter = string.Empty;
/// <summary>
/// Check Code Before member variable
/// </summary>
protected string checkCodeBefore = string.Empty;
#endregion Protected Properties
#region Public Methods
/// <summary>
/// Deletes the field
/// </summary>
public override void Delete()
{
View childView = this.GetProject().GetViewById(RelatedViewID);
if (childView != null)
{
childView.IsRelatedView = false;
GetMetadata().UpdateView(childView);
}
GetMetadata().DeleteField(this);
view.MustRefreshFieldCollection = true;
}
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
///// <summary>
///// Inserts the field to the database
///// </summary>
//protected override void InsertField()
//{
// insertStarted = true;
// _inserter = new BackgroundWorker();
// _inserter.DoWork += new DoWorkEventHandler(inserter_DoWork);
// _inserter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_inserter_RunWorkerCompleted);
// _inserter.RunWorkerAsync();
//}
//void _inserter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldInserted(this);
//}
//void inserter_DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// this.Id = GetMetadata().CreateField(this);
// base.OnFieldAdded();
// fieldsWaitingToUpdate--;
// }
//}
///// <summary>
///// Update the field to the database
///// </summary>
//protected override void UpdateField()
//{
// _updater = new BackgroundWorker();
// _updater.DoWork += new DoWorkEventHandler(DoWork);
// _updater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_updater_RunWorkerCompleted);
// _updater.RunWorkerAsync();
//}
//void _updater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldUpdated(this);
//}
//private void DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// GetMetadata().UpdateField(this);
// fieldsWaitingToUpdate--;
// }
//}
#endregion Protected Methods
#region Event Handlers
/// <summary>
/// Handles the click event of the Edit Field menu item
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void MnuEditRelate_Click(object sender, EventArgs e)
{
//base.RaiseEventFieldDefinitionRequested();
}
/// <summary>
/// Handles the click event of the Related View menu item
/// </summary>
/// <param name="sender">.NET supplied object</param>
/// <param name="e">.NET supplied event parameters</param>
private void MnuRelatedView_Click(object sender, EventArgs e)
{
if (ChildViewRequested != null)
{
ChildViewRequested(this, new ChildViewRequestedEventArgs(ChildView));
}
}
#endregion Event Handlers
#region Private Methods
/// <summary>
/// Creates an Xml attribute and sets a value.
/// (NOTE: fieldElement must be set to viewElement.OwnerDocument.CreateElement("Field").)
/// </summary>
/// <param name="Attribute">System.Xml.XmlAttribute.</param>
/// <param name="Value">Sets the value of the node.</param>
private void AppendAttributeValue(string Attribute, string Value)
{
try
{
XmlAttribute xmlAttribute = viewElement.OwnerDocument.CreateAttribute(Attribute);
xmlAttribute.Value = Value;
if (fieldElement == null) fieldElement = viewElement.OwnerDocument.CreateElement("Field");
fieldElement.Attributes.Append(xmlAttribute);
}
catch (ArgumentException ex)
{
throw new GeneralException(SharedStrings.EXCEPTION_OCCURRED, ex);
}
}
#endregion //Private Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsCompositeBoolIntClient
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Extension methods for IntModel.
/// </summary>
public static partial class IntModelExtensions
{
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetNull(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetNullAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetInvalid(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetInvalidAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetOverflowInt32(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetOverflowInt32Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetUnderflowInt32(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetUnderflowInt32Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetOverflowInt64(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<long?> GetOverflowInt64Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetUnderflowInt64(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<long?> GetUnderflowInt64Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax32(this IIntModel operations, int intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMax32Async(this IIntModel operations, int intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax64(this IIntModel operations, long intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMax64Async(this IIntModel operations, long intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin32(this IIntModel operations, int intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMin32Async(this IIntModel operations, int intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin64(this IIntModel operations, long intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMin64Async(this IIntModel operations, long intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUnixTime(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutUnixTimeDate(this IIntModel operations, DateTime intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUnixTimeDateAsync(this IIntModel operations, DateTime intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetInvalidUnixTime(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetInvalidUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetNullUnixTime(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetNullUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.